1 openerp.web.search = function(openerp) {
2 var QWeb = openerp.web.qweb,
6 sum: function (obj) { return _.reduce(obj, function (a, b) { return a + b; }, 0); }
9 // Have SearchBox optionally use callback function to produce inputs and facets
10 // (views) set on callbacks.make_facet and callbacks.make_input keys when
11 // initializing VisualSearch
12 var SearchBox_renderFacet = function (facet, position) {
13 var view = new (this.app.options.callbacks['make_facet'] || VS.ui.SearchFacet)({
19 // Input first, facet second.
20 this.renderSearchInput();
21 this.facetViews.push(view);
22 this.$('.VS-search-inner').children().eq(position*2).after(view.render().el);
25 _.defer(_.bind(view.calculateSize, view));
28 }; // warning: will not match
29 // Ensure we're replacing the function we think
30 if (SearchBox_renderFacet.toString() !== VS.ui.SearchBox.prototype.renderFacet.toString().replace(/(VS\.ui\.SearchFacet)/, "(this.app.options.callbacks['make_facet'] || $1)")) {
32 "Trying to replace wrong version of VS.ui.SearchBox#renderFacet. "
33 + "Please fix replacement.");
35 var SearchBox_renderSearchInput = function () {
36 var input = new (this.app.options.callbacks['make_input'] || VS.ui.SearchInput)({position: this.inputViews.length, app: this.app});
37 this.$('.VS-search-inner').append(input.render().el);
38 this.inputViews.push(input);
40 // Ensure we're replacing the function we think
41 if (SearchBox_renderSearchInput.toString() !== VS.ui.SearchBox.prototype.renderSearchInput.toString().replace(/(VS\.ui\.SearchInput)/, "(this.app.options.callbacks['make_input'] || $1)")) {
43 "Trying to replace wrong version of VS.ui.SearchBox#renderSearchInput. "
44 + "Please fix replacement.");
46 var SearchBox_searchEvent = function (e) {
50 this.app.options.callbacks.search(query, this.app.searchQuery);
52 if (SearchBox_searchEvent.toString() !== VS.ui.SearchBox.prototype.searchEvent.toString().replace(
53 /this\.value\(\);\n[ ]{4}this\.focusSearch\(e\);\n[ ]{4}this\.value\(query\)/,
54 'null;\n this.renderFacets();\n this.focusSearch(e)')) {
56 "Trying to replace wrong version of VS.ui.SearchBox#searchEvent. "
57 + "Please fix replacement.");
59 _.extend(VS.ui.SearchBox.prototype, {
60 renderFacet: SearchBox_renderFacet,
61 renderSearchInput: SearchBox_renderSearchInput,
62 searchEvent: SearchBox_searchEvent
64 _.extend(VS.model.SearchFacet.prototype, {
66 if (this.has('json')) {
67 return this.get('json');
69 return this.get('value');
73 openerp.web.SearchView = openerp.web.Widget.extend(/** @lends openerp.web.SearchView# */{
74 template: "SearchView",
76 * @constructs openerp.web.SearchView
77 * @extends openerp.web.OldWidget
85 init: function(parent, dataset, view_id, defaults, hidden) {
87 this.dataset = dataset;
88 this.model = dataset.model;
89 this.view_id = view_id;
91 this.defaults = defaults || {};
92 this.has_defaults = !_.isEmpty(this.defaults);
97 this.hidden = !!hidden;
98 this.headless = this.hidden && !this.has_defaults;
100 this.filter_data = {};
102 this.ready = $.Deferred();
106 var p = this._super();
108 this.setup_global_completion();
110 container: this.$element,
113 make_facet: this.proxy('make_visualsearch_facet'),
114 make_input: this.proxy('make_visualsearch_input'),
115 search: function (query, searchCollection) {
118 facetMatches: function (callback) {
120 valueMatches : function(facet, searchTerm, callback) {
125 var search = function () { self.vs.searchBox.searchEvent({}); };
126 // searchQuery operations
128 .off('add').on('add', search)
129 .off('change').on('change', search)
130 .off('reset').on('reset', search)
131 .off('remove').on('remove', function (record, collection, options) {
132 if (options['trigger_search']) {
138 this.$element.hide();
141 this.ready.resolve();
143 var load_view = this.rpc("/web/searchview/load", {
145 view_id: this.view_id,
146 context: this.dataset.get_context() });
147 // FIXME: local eval of domain and context to get rid of special endpoint
148 var filters = this.rpc('/web/searchview/get_filters', {
150 }).then(function (filters) { self.custom_filters = filters; });
152 $.when(load_view, filters)
153 .pipe(function (load) { return load[0]; })
154 .then(this.on_loaded);
157 this.$element.on('click', '.oe_vs_unfold_drawer', function () {
158 self.$element.toggleClass('oe_searchview_open_drawer');
161 return $.when(p, this.ready);
164 this.$element.show();
167 this.$element.hide();
171 * Sets up thingie where all the mess is put?
173 setup_stuff_drawer: function () {
175 $('<div class="oe_vs_unfold_drawer">').appendTo(this.$element.find('.VS-search-box'));
176 var $drawer = $('<div class="oe_searchview_drawer">').appendTo(this.$element);
177 var $filters = $('<div class="oe_searchview_filters">').appendTo($drawer);
179 var running_count = 0;
180 // get total filters count
181 var is_group = function (i) { return i instanceof openerp.web.search.FilterGroup; };
182 var filters_count = _(this.controls).chain()
185 .map(function (i) { return i.filters.length; })
189 var col1 = [], col2 = _(this.controls).map(function (inputs, group) {
190 var filters = _(inputs).filter(is_group);
192 name: group === 'null' ? _t("Filters") : group,
194 length: _(filters).chain().map(function (i) {
195 return i.filters.length; }).sum().value()
199 while (col2.length) {
200 // col1 + group should be smaller than col2 + group
201 if ((running_count + col2[0].length) <= (filters_count - running_count)) {
202 running_count += col2[0].length;
203 col1.push(col2.shift());
209 // Create a Custom Filter FilterGroup for each custom filter read from
210 // the db, add all of this as a group in the smallest column
211 [].push.call(col1.length <= col2.length ? col1 : col2, {
212 name: _t("Custom Filters"),
213 filters: _.map(this.custom_filters, function (filter) {
214 // FIXME: handling of ``disabled`` being set
215 var f = new openerp.web.search.Filter({attrs: {
217 context: filter.context,
218 domain: filter.domain
220 return new openerp.web.search.FilterGroup([f], self);
226 this.render_column(col1, $('<div>').appendTo($filters)),
227 this.render_column(col2, $('<div>').appendTo($filters)),
228 (new openerp.web.search.Advanced(this).appendTo($drawer)));
230 render_column: function (column, $el) {
231 return $.when.apply(null, _(column).map(function (group) {
232 $('<h3>').text(group.name).appendTo($el);
233 return $.when.apply(null,
234 _(group.filters).invoke('appendTo', $el));
238 * Sets up search view's view-wide auto-completion widget
240 setup_global_completion: function () {
241 // Prevent keydown from within a facet's input from reaching the
242 // auto-completion widget and opening the completion list
243 this.$element.on('keydown', '.search_facet input', function (e) {
244 e.stopImmediatePropagation();
247 this.$element.autocomplete({
248 source: this.proxy('complete_global_search'),
249 select: this.proxy('select_completion'),
250 focus: function (e) { e.preventDefault(); },
254 }).data('autocomplete')._renderItem = function (ul, item) {
255 // item of completion list
256 var $item = $( "<li></li>" )
257 .data( "item.autocomplete", item )
260 if (item.value !== undefined) {
261 // regular completion item
264 ? $('<a>').html(item.label)
265 : $('<a>').text(item.value));
267 return $item.text(item.category)
269 borderTop: '1px solid #cccccc',
280 * Provide auto-completion result for req.term (an array to `resp`)
282 * @param {Object} req request to complete
283 * @param {String} req.term searched term to complete
284 * @param {Function} resp response callback
286 complete_global_search: function (req, resp) {
287 $.when.apply(null, _(this.inputs).chain()
288 .invoke('complete', req.term)
289 .value()).then(function () {
290 resp(_(_(arguments).compact()).flatten(true));
295 * Action to perform in case of selection: create a facet (model)
296 * and add it to the search collection
298 * @param {Object} e selection event, preventDefault to avoid setting value on object
299 * @param {Object} ui selection information
300 * @param {Object} ui.item selected completion item
302 select_completion: function (e, ui) {
304 this.vs.searchQuery.add(new VS.model.SearchFacet(_.extend(
305 {app: this.vs}, ui.item)));
306 this.vs.searchBox.searchEvent({});
310 * Builds the right SearchFacet view based on the facet object to render
311 * (e.g. readonly facets for filters)
313 * @param {Object} options
314 * @param {VS.model.SearchFacet} options.model facet object to render
316 make_visualsearch_facet: function (options) {
317 if (options.model.get('field') instanceof openerp.web.search.FilterGroup) {
318 return new openerp.web.search.FilterGroupFacet(options);
320 return new VS.ui.SearchFacet(options);
323 * Proxies searches on a SearchInput to the search view's global completion
325 * Also disables SearchInput.autocomplete#_move so search view's
326 * autocomplete can get the corresponding events, or something.
330 make_visualsearch_input: function (options) {
331 var self = this, input = new VS.ui.SearchInput(options);
332 input.setupAutocomplete = function () {
333 _.extend(this.box.autocomplete({
336 search: function () {
337 self.$element.autocomplete('search', input.box.val());
340 }).data('autocomplete'), {
341 _move: function () {},
342 close: function () { self.$element.autocomplete('close'); }
349 * Builds a list of widget rows (each row is an array of widgets)
351 * @param {Array} items a list of nodes to convert to widgets
352 * @param {Object} fields a mapping of field names to (ORM) field attributes
353 * @param {String} [group_name] name of the group to put the new controls in
355 make_widgets: function (items, fields, group_name) {
356 group_name = group_name || null;
357 if (!(group_name in this.controls)) {
358 this.controls[group_name] = [];
360 var self = this, group = this.controls[group_name];
362 _.each(items, function (item) {
363 if (filters.length && item.tag !== 'filter') {
364 group.push(new openerp.web.search.FilterGroup(filters, this));
369 case 'separator': case 'newline':
372 filters.push(new openerp.web.search.Filter(item, this));
375 self.make_widgets(item.children, fields, item.attrs.string);
378 group.push(this.make_field(item, fields[item['attrs'].name]));
380 self.make_widgets(item.children, fields, group_name);
385 if (filters.length) {
386 group.push(new openerp.web.search.FilterGroup(filters, this));
390 * Creates a field for the provided field descriptor item (which comes
391 * from fields_view_get)
393 * @param {Object} item fields_view_get node for the field
394 * @param {Object} field fields_get result for the field
395 * @returns openerp.web.search.Field
397 make_field: function (item, field) {
399 return new (openerp.web.search.fields.get_any(
400 [item.attrs.widget, field.type]))
403 if (! e instanceof openerp.web.KeyNotFound) {
406 // KeyNotFound means unknown field type
407 console.group('Unknown field type ' + field.type);
408 console.error('View node', item);
409 console.info('View field', field);
410 console.info('In view', this);
415 on_loaded: function(data) {
417 this.fields_view = data.fields_view;
418 if (data.fields_view.type !== 'search' ||
419 data.fields_view.arch.tag !== 'search') {
420 throw new Error(_.str.sprintf(
421 "Got non-search view after asking for a search view: type %s, arch root %s",
422 data.fields_view.type, data.fields_view.arch.tag));
426 data.fields_view['arch'].children,
427 data.fields_view.fields);
431 this.setup_stuff_drawer(),
432 $.when.apply(null, _(this.inputs).invoke('facet_for_defaults', this.defaults))
433 .then(function () { self.vs.searchQuery.reset(_(arguments).compact()); }))
434 .then(function () { self.ready.resolve(); })
437 * Handle event when the user make a selection in the filters management select box.
439 on_filters_management: function(e) {
441 var select = this.$element.find(".oe_search-view-filters-management");
442 var val = select.val();
444 case 'advanced_filter':
445 this.extended_search.on_activate();
447 case 'add_to_dashboard':
448 this.on_add_to_dashboard();
450 case 'manage_filters':
452 res_model: 'ir.filters',
453 views: [[false, 'list'], [false, 'form']],
454 type: 'ir.actions.act_window',
455 context: {"search_default_user_id": this.session.uid,
456 "search_default_model_id": this.dataset.model},
462 var data = this.build_search_data();
463 var context = new openerp.web.CompoundContext();
464 _.each(data.contexts, function(x) {
467 var domain = new openerp.web.CompoundDomain();
468 _.each(data.domains, function(x) {
471 var groupbys = _.pluck(data.groupbys, "group_by").join();
472 context.add({"group_by": groupbys});
473 var dial_html = QWeb.render("SearchView.managed-filters.add");
474 var $dial = $(dial_html);
475 openerp.web.dialog($dial, {
477 title: _t("Filter Entry"),
479 {text: _t("Cancel"), click: function() {
480 $(this).dialog("close");
482 {text: _t("OK"), click: function() {
483 $(this).dialog("close");
484 var name = $(this).find("input").val();
485 self.rpc('/web/searchview/save_filter', {
486 model: self.dataset.model,
487 context_to_save: context,
491 self.reload_managed_filters();
500 if (val.slice(0, 4) == "get:") {
502 val = parseInt(val, 10);
503 var filter = this.managed_filters[val];
504 this.do_clear(false).then(_.bind(function() {
505 select.val('get:' + val);
508 var group_by = filter.context.group_by;
511 group_by instanceof Array ? group_by : group_by.split(','),
512 function (el) { return { group_by: el }; });
515 domains: [filter.domain],
516 contexts: [filter.context],
525 on_add_to_dashboard: function() {
526 this.$element.find(".oe_search-view-filters-management")[0].selectedIndex = 0;
528 menu = openerp.webclient.menu,
529 $dialog = $(QWeb.render("SearchView.add_to_dashboard", {
530 dashboards : menu.data.data.children,
531 selected_menu_id : menu.$element.find('a.active').data('menu')
533 $dialog.find('input').val(this.fields_view.name);
534 openerp.web.dialog($dialog, {
536 title: _t("Add to Dashboard"),
538 {text: _t("Cancel"), click: function() {
539 $(this).dialog("close");
541 {text: _t("OK"), click: function() {
542 $(this).dialog("close");
543 var menu_id = $(this).find("select").val(),
544 title = $(this).find("input").val(),
545 data = self.build_search_data(),
546 context = new openerp.web.CompoundContext(),
547 domain = new openerp.web.CompoundDomain();
548 _.each(data.contexts, function(x) {
551 _.each(data.domains, function(x) {
554 self.rpc('/web/searchview/add_to_dashboard', {
556 action_id: self.getParent().action.id,
557 context_to_save: context,
559 view_mode: self.getParent().active_view,
563 self.do_warn("Could not add filter to dashboard");
565 self.do_notify("Filter added to dashboard", '');
573 * Performs the search view collection of widget data.
575 * If the collection went well (all fields are valid), then triggers
576 * :js:func:`openerp.web.SearchView.on_search`.
578 * If at least one field failed its validation, triggers
579 * :js:func:`openerp.web.SearchView.on_invalid` instead.
581 * @param e jQuery event object coming from the "Search" button
583 do_search: function () {
584 var domains = [], contexts = [], groupbys = [], errors = [];
586 this.vs.searchQuery.each(function (facet) {
587 var field = facet.get('field');
589 var domain = field.get_domain(facet);
591 domains.push(domain);
593 var context = field.get_context(facet);
595 contexts.push(context);
596 groupbys.push(context);
599 if (e instanceof openerp.web.search.Invalid) {
607 if (!_.isEmpty(errors)) {
608 this.on_invalid(errors);
611 return this.on_search(domains, contexts, groupbys);
614 * Triggered after the SearchView has collected all relevant domains and
617 * It is provided with an Array of domains and an Array of contexts, which
618 * may or may not be evaluated (each item can be either a valid domain or
619 * context, or a string to evaluate in order in the sequence)
621 * It is also passed an array of contexts used for group_by (they are in
622 * the correct order for group_by evaluation, which contexts may not be)
625 * @param {Array} domains an array of literal domains or domain references
626 * @param {Array} contexts an array of literal contexts or context refs
627 * @param {Array} groupbys ordered contexts which may or may not have group_by keys
629 on_search: function (domains, contexts, groupbys) {
632 * Triggered after a validation error in the SearchView fields.
634 * Error objects have three keys:
635 * * ``field`` is the name of the invalid field
636 * * ``value`` is the invalid value
637 * * ``message`` is the (in)validation message provided by the field
640 * @param {Array} errors a never-empty array of error objects
642 on_invalid: function (errors) {
643 this.do_notify(_t("Invalid Search"), _t("triggered from search view"));
648 openerp.web.search = {};
650 openerp.web.search.FilterGroupFacet = VS.ui.SearchFacet.extend({
652 'click': 'selectFacet'
653 }, VS.ui.SearchFacet.prototype.events),
655 render: function () {
656 this.setMode('not', 'editing');
657 this.setMode('not', 'selected');
659 var value = this.model.get('value');
660 this.$el.html(QWeb.render('SearchView.filters.facet', {
663 // virtual input so SearchFacet code has something to play with
664 this.box = $('<input>').val(value);
668 enableEdit: function () {
671 keydown: function (e) {
672 var key = VS.app.hotkeys.key(e);
673 if (key !== 'right') {
674 return VS.ui.SearchFacet.prototype.keydown.call(this, e);
677 this.deselectFacet();
678 this.options.app.searchBox.focusNextFacet(this, 1);
682 * Registry of search fields, called by :js:class:`openerp.web.SearchView` to
683 * find and instantiate its field widgets.
685 openerp.web.search.fields = new openerp.web.Registry({
686 'char': 'openerp.web.search.CharField',
687 'text': 'openerp.web.search.CharField',
688 'boolean': 'openerp.web.search.BooleanField',
689 'integer': 'openerp.web.search.IntegerField',
690 'id': 'openerp.web.search.IntegerField',
691 'float': 'openerp.web.search.FloatField',
692 'selection': 'openerp.web.search.SelectionField',
693 'datetime': 'openerp.web.search.DateTimeField',
694 'date': 'openerp.web.search.DateField',
695 'many2one': 'openerp.web.search.ManyToOneField',
696 'many2many': 'openerp.web.search.CharField',
697 'one2many': 'openerp.web.search.CharField'
699 openerp.web.search.Invalid = openerp.web.Class.extend( /** @lends openerp.web.search.Invalid# */{
701 * Exception thrown by search widgets when they hold invalid values,
702 * which they can not return when asked.
704 * @constructs openerp.web.search.Invalid
705 * @extends openerp.web.Class
707 * @param field the name of the field holding an invalid value
708 * @param value the invalid value
709 * @param message validation failure message
711 init: function (field, value, message) {
714 this.message = message;
716 toString: function () {
717 return _.str.sprintf(
718 _t("Incorrect value for field %(fieldname)s: [%(value)s] is %(message)s"),
719 {fieldname: this.field, value: this.value, message: this.message}
723 openerp.web.search.Widget = openerp.web.OldWidget.extend( /** @lends openerp.web.search.Widget# */{
726 * Root class of all search widgets
728 * @constructs openerp.web.search.Widget
729 * @extends openerp.web.OldWidget
731 * @param view the ancestor view of this widget
733 init: function (view) {
738 openerp.web.search.add_expand_listener = function($root) {
739 $root.find('a.searchview_group_string').click(function (e) {
740 $root.toggleClass('folded expanded');
745 openerp.web.search.Group = openerp.web.search.Widget.extend({
746 template: 'SearchView.group',
747 init: function (view_section, view, fields) {
749 this.attrs = view_section.attrs;
750 this.lines = view.make_widgets(
751 view_section.children, fields);
755 openerp.web.search.Input = openerp.web.search.Widget.extend( /** @lends openerp.web.search.Input# */{
757 * @constructs openerp.web.search.Input
758 * @extends openerp.web.search.Widget
762 init: function (view) {
764 this.view.inputs.push(this);
765 this.style = undefined;
768 * Fetch auto-completion values for the widget.
770 * The completion values should be an array of objects with keys category,
771 * label, value prefixed with an object with keys type=section and label
773 * @param {String} value value to complete
774 * @returns {jQuery.Deferred<null|Array>}
776 complete: function (value) {
780 * Returns a VS.model.SearchFacet instance for the provided defaults if
781 * they apply to this widget, or null if they don't.
783 * This default implementation will try calling
784 * :js:func:`openerp.web.search.Input#facet_for` if the widget's name
785 * matches the input key
787 * @param {Object} defaults
788 * @returns {jQuery.Deferred<null|Object>}
790 facet_for_defaults: function (defaults) {
792 !(this.attrs.name in defaults && defaults[this.attrs.name])) {
795 return this.facet_for(defaults[this.attrs.name]);
797 get_context: function () {
799 "get_context not implemented for widget " + this.attrs.type);
801 get_domain: function () {
803 "get_domain not implemented for widget " + this.attrs.type);
805 load_attrs: function (attrs) {
806 if (attrs.modifiers) {
807 attrs.modifiers = JSON.parse(attrs.modifiers);
808 attrs.invisible = attrs.modifiers.invisible || false;
809 if (attrs.invisible) {
810 this.style = 'display: none;'
816 openerp.web.search.FilterGroup = openerp.web.search.Input.extend(/** @lends openerp.web.search.FilterGroup# */{
817 template: 'SearchView.filters',
819 * Inclusive group of filters, creates a continuous "button" with clickable
820 * sections (the normal display for filters is to be a self-contained button)
822 * @constructs openerp.web.search.FilterGroup
823 * @extends openerp.web.search.Input
825 * @param {Array<openerp.web.search.Filter>} filters elements of the group
826 * @param {openerp.web.SearchView} view view in which the filters are contained
828 init: function (filters, view) {
830 this.filters = filters;
833 this.$element.on('click', 'li', this.proxy('toggle_filter'));
836 facet_for_defaults: function (defaults) {
837 var fs = _(this.filters).filter(function (f) {
838 return f.attrs && f.attrs.name && !!defaults[f.attrs.name];
840 if (_.isEmpty(fs)) { return $.when(null); }
841 return $.when(new VS.model.SearchFacet({
843 value: _(fs).map(function (f) {
844 return f.attrs.string || f.attrs.name }).join(' | '),
851 * Fetches contexts for all enabled filters in the group
853 * @param {VS.model.SearchFacet} facet
854 * @return {*} combined contexts of the enabled filters in this group
856 get_context: function (facet) {
857 var contexts = _(facet.get('json')).chain()
858 .map(function (filter) { return filter.attrs.context; })
862 if (!contexts.length) { return; }
863 if (contexts.length === 1) { return contexts[0]; }
864 return _.extend(new openerp.web.CompoundContext, {
869 * Handles domains-fetching for all the filters within it: groups them.
871 * @param {VS.model.SearchFacet} facet
872 * @return {*} combined domains of the enabled filters in this group
874 get_domain: function (facet) {
875 var domains = _(facet.get('json')).chain()
876 .map(function (filter) { return filter.attrs.domain; })
880 if (!domains.length) { return; }
881 if (domains.length === 1) { return domains[0]; }
882 for (var i=domains.length; --i;) {
883 domains.unshift(['|']);
885 return _.extend(new openerp.web.CompoundDomain(), {
889 toggle_filter: function (e) {
890 this.toggle(this.filters[$(e.target).index()]);
892 toggle: function (filter) {
893 // FIXME: oh god, my eyes, they hurt
895 var facet = this.view.vs.searchQuery.detect(function (f) {
896 return f.get('field') === self; });
898 fs = facet.get('json');
900 if (_.include(fs, filter)) {
901 fs = _.without(fs, filter);
905 if (_(fs).isEmpty()) {
906 this.view.vs.searchQuery.remove(facet, {trigger_search: true});
910 value: _(fs).map(function (f) {
911 return f.attrs.string || f.attrs.name }).join(' | ')
919 this.view.vs.searchQuery.add({
921 value: _(fs).map(function (f) {
922 return f.attrs.string || f.attrs.name }).join(' | '),
929 openerp.web.search.Filter = openerp.web.search.Input.extend(/** @lends openerp.web.search.Filter# */{
930 template: 'SearchView.filter',
932 * Implementation of the OpenERP filters (button with a context and/or
933 * a domain sent as-is to the search view)
935 * Filters are only attributes holder, the actual work (compositing
936 * domains and contexts, converting between facets and filters) is
937 * performed by the filter group.
939 * @constructs openerp.web.search.Filter
940 * @extends openerp.web.search.Input
945 init: function (node, view) {
947 this.load_attrs(node.attrs);
949 facet_for: function () { return $.when(null); },
950 get_context: function () { },
951 get_domain: function () { }
953 openerp.web.search.Field = openerp.web.search.Input.extend( /** @lends openerp.web.search.Field# */ {
954 template: 'SearchView.field',
955 default_operator: '=',
957 * @constructs openerp.web.search.Field
958 * @extends openerp.web.search.Input
960 * @param view_section
964 init: function (view_section, field, view) {
966 this.load_attrs(_.extend({}, field, view_section.attrs));
968 facet_for: function (value) {
969 return $.when(new VS.model.SearchFacet({
970 category: this.attrs.string || this.attrs.name,
971 value: String(value),
977 get_value: function (facet) {
978 return facet.value();
980 get_context: function (facet) {
981 var val = this.get_value(facet);
982 // A field needs a value to be "active", and a context to send when
984 var has_value = (val !== null && val !== '');
985 var context = this.attrs.context;
986 if (!(has_value && context)) {
989 return new openerp.web.CompoundContext(context)
990 .set_eval_context({self: val});
993 * Function creating the returned domain for the field, override this
994 * methods in children if you only need to customize the field's domain
995 * without more complex alterations or tests (and without the need to
996 * change override the handling of filter_domain)
998 * @param {String} name the field's name
999 * @param {String} operator the field's operator (either attribute-specified or default operator for the field
1000 * @param {Number|String} value parsed value for the field
1001 * @returns {Array<Array>} domain to include in the resulting search
1003 make_domain: function (name, operator, facet) {
1004 return [[name, operator, this.get_value(facet)]];
1006 get_domain: function (facet) {
1007 var val = this.get_value(facet);
1008 if (val === null || val === '') {
1012 var domain = this.attrs['filter_domain'];
1014 return this.make_domain(
1016 this.attrs.operator || this.default_operator,
1019 return new openerp.web.CompoundDomain(domain)
1020 .set_eval_context({self: val});
1024 * Implementation of the ``char`` OpenERP field type:
1026 * * Default operator is ``ilike`` rather than ``=``
1028 * * The Javascript and the HTML values are identical (strings)
1031 * @extends openerp.web.search.Field
1033 openerp.web.search.CharField = openerp.web.search.Field.extend( /** @lends openerp.web.search.CharField# */ {
1034 default_operator: 'ilike',
1035 complete: function (value) {
1036 if (_.isEmpty(value)) { return $.when(null); }
1037 var label = _.str.sprintf(_.str.escapeHTML(
1038 _t("Search %(field)s for: %(value)s")), {
1039 field: '<em>' + this.attrs.string + '</em>',
1040 value: '<strong>' + _.str.escapeHTML(value) + '</strong>'});
1042 category: this.attrs.string,
1049 openerp.web.search.NumberField = openerp.web.search.Field.extend(/** @lends openerp.web.search.NumberField# */{
1050 get_value: function () {
1051 if (!this.$element.val()) {
1054 var val = this.parse(this.$element.val()),
1055 check = Number(this.$element.val());
1056 if (isNaN(val) || val !== check) {
1057 this.$element.addClass('error');
1058 throw new openerp.web.search.Invalid(
1059 this.attrs.name, this.$element.val(), this.error_message);
1061 this.$element.removeClass('error');
1067 * @extends openerp.web.search.NumberField
1069 openerp.web.search.IntegerField = openerp.web.search.NumberField.extend(/** @lends openerp.web.search.IntegerField# */{
1070 error_message: _t("not a valid integer"),
1071 parse: function (value) {
1073 return openerp.web.parse_value(value, {'widget': 'integer'});
1081 * @extends openerp.web.search.NumberField
1083 openerp.web.search.FloatField = openerp.web.search.NumberField.extend(/** @lends openerp.web.search.FloatField# */{
1084 error_message: _t("not a valid number"),
1085 parse: function (value) {
1087 return openerp.web.parse_value(value, {'widget': 'float'});
1095 * @extends openerp.web.search.Field
1097 openerp.web.search.SelectionField = openerp.web.search.Field.extend(/** @lends openerp.web.search.SelectionField# */{
1098 // This implementation is a basic <select> field, but it may have to be
1099 // altered to be more in line with the GTK client, which uses a combo box
1100 // (~ jquery.autocomplete):
1101 // * If an option was selected in the list, behave as currently
1102 // * If something which is not in the list was entered (via the text input),
1103 // the default domain should become (`ilike` string_value) but **any
1104 // ``context`` or ``filter_domain`` becomes falsy, idem if ``@operator``
1105 // is specified. So at least get_domain needs to be quite a bit
1106 // overridden (if there's no @value and there is no filter_domain and
1107 // there is no @operator, return [[name, 'ilike', str_val]]
1108 template: 'SearchView.field.selection',
1110 this._super.apply(this, arguments);
1111 // prepend empty option if there is no empty option in the selection list
1112 this.prepend_empty = !_(this.attrs.selection).detect(function (item) {
1116 complete: function (needle) {
1118 var results = _(this.attrs.selection).chain()
1119 .filter(function (sel) {
1120 var value = sel[0], label = sel[1];
1121 if (!value) { return false; }
1122 return label.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
1124 .map(function (sel) {
1126 category: self.attrs.string,
1132 if (_.isEmpty(results)) { return $.when(null); }
1133 return $.when.apply(null, [{
1134 category: this.attrs.string
1135 }].concat(results));
1137 facet_for: function (value) {
1138 var match = _(this.attrs.selection).detect(function (sel) {
1139 return sel[0] === value;
1141 if (!match) { return $.when(null); }
1142 return $.when(new VS.model.SearchFacet({
1143 category: this.attrs.string,
1150 get_value: function (facet) {
1151 return facet.get('json');
1154 openerp.web.search.BooleanField = openerp.web.search.SelectionField.extend(/** @lends openerp.web.search.BooleanField# */{
1156 * @constructs openerp.web.search.BooleanField
1157 * @extends openerp.web.search.BooleanField
1160 this._super.apply(this, arguments);
1161 this.attrs.selection = [
1162 ['true', _t("Yes")],
1166 get_value: function (facet) {
1167 switch (this._super(facet)) {
1168 case 'false': return false;
1169 case 'true': return true;
1170 default: return null;
1176 * @extends openerp.web.search.DateField
1178 openerp.web.search.DateField = openerp.web.search.Field.extend(/** @lends openerp.web.search.DateField# */{
1179 get_value: function (facet) {
1180 return openerp.web.date_to_str(facet.get('json'));
1182 complete: function (needle) {
1183 var d = Date.parse(needle);
1184 if (!d) { return $.when(null); }
1185 var value = openerp.web.format_value(d, this.attrs);
1186 var label = _.str.sprintf(_.str.escapeHTML(
1187 _t("Search %(field)s at: %(value)s")), {
1188 field: '<em>' + this.attrs.string + '</em>',
1189 value: '<strong>' + value + '</strong>'});
1191 category: this.attrs.string,
1200 * Implementation of the ``datetime`` openerp field type:
1202 * * Uses the same widget as the ``date`` field type (a simple date)
1204 * * Builds a slighly more complex, it's a datetime range (includes time)
1205 * spanning the whole day selected by the date widget
1208 * @extends openerp.web.DateField
1210 openerp.web.search.DateTimeField = openerp.web.search.DateField.extend(/** @lends openerp.web.search.DateTimeField# */{
1211 get_value: function (facet) {
1212 return openerp.web.datetime_to_str(facet.get('json'));
1215 openerp.web.search.ManyToOneField = openerp.web.search.CharField.extend({
1216 init: function (view_section, field, view) {
1217 this._super(view_section, field, view);
1218 this.model = new openerp.web.Model(this.attrs.relation);
1220 complete: function (needle) {
1223 // FIXME: "concurrent" searches (multiple requests, mis-ordered responses)
1224 return this.model.call('name_search', [], {
1228 }).pipe(function (results) {
1229 if (_.isEmpty(results)) { return null; }
1230 return [{category: self.attrs.string}].concat(
1231 _(results).map(function (result) {
1233 category: self.attrs.string,
1241 facet_for: function (value) {
1243 if (value instanceof Array) {
1244 return $.when(new VS.model.SearchFacet({
1245 category: this.attrs.string,
1252 return this.model.call('name_get', [value], {}).pipe(function (names) {
1253 return new VS.model.SearchFacet({
1254 category: self.attrs.string,
1262 make_domain: function (name, operator, facet) {
1263 // ``json`` -> actual auto-completed id
1264 if (facet.get('json')) {
1265 return [[name, '=', facet.get('json')]];
1268 return this._super(name, operator, facet);
1272 openerp.web.search.Advanced = openerp.web.search.Input.extend({
1273 template: 'SearchView.advanced',
1274 start: function () {
1276 this.propositions = [];
1278 .on('keypress keydown keyup', function (e) { e.stopPropagation(); })
1279 .on('click', 'h4', function () {
1280 self.$element.toggleClass('oe_opened');
1281 }).on('click', 'button.oe_add_condition', function () {
1282 self.append_proposition();
1283 }).on('submit', 'form', function (e) {
1285 self.commit_search();
1289 this.rpc("/web/searchview/fields_get", {model: this.view.model}, function(data) {
1290 self.fields = _.extend({
1291 id: { string: 'ID', type: 'id' }
1293 })).then(function () {
1294 self.append_proposition();
1297 append_proposition: function () {
1298 return (new openerp.web.search.ExtendedSearchProposition(this, this.fields))
1299 .appendTo(this.$element.find('ul'));
1301 commit_search: function () {
1303 // Get domain sections from all propositions
1304 var children = this.getChildren(),
1305 domain = _.invoke(children, 'get_proposition');
1306 var filters = _(domain).map(function (section) {
1307 return new openerp.web.search.Filter({attrs: {
1308 string: _.str.sprintf('%s(%s)%s',
1309 section[0], section[1], section[2]),
1313 // Create Filter (& FilterGroup around it) with that domain
1314 var f = new openerp.web.search.FilterGroup(filters, this.view);
1315 // add group to query
1316 this.view.vs.searchQuery.add({
1318 value: _(filters).map(function (f) {
1319 return f.attrs.string || f.attrs.name }).join(' | '),
1324 // remove all propositions
1325 _.invoke(children, 'destroy');
1326 // add new empty proposition
1327 this.append_proposition();
1328 // TODO: API on searchview
1329 this.view.$element.removeClass('oe_searchview_open_drawer');
1333 openerp.web.search.ExtendedSearchProposition = openerp.web.OldWidget.extend(/** @lends openerp.web.search.ExtendedSearchProposition# */{
1334 template: 'SearchView.extended_search.proposition',
1336 * @constructs openerp.web.search.ExtendedSearchProposition
1337 * @extends openerp.web.OldWidget
1342 init: function (parent, fields) {
1343 this._super(parent);
1344 this.fields = _(fields).chain()
1345 .map(function(val, key) { return _.extend({}, val, {'name': key}); })
1346 .sortBy(function(field) {return field.string;})
1348 this.attrs = {_: _, fields: this.fields, selected: null};
1351 start: function () {
1352 this.select_field(this.fields.length > 0 ? this.fields[0] : null);
1354 this.$element.find(".searchview_extended_prop_field").change(function() {
1357 this.$element.find('.searchview_extended_delete_prop').click(function () {
1361 changed: function() {
1362 var nval = this.$element.find(".searchview_extended_prop_field").val();
1363 if(this.attrs.selected == null || nval != this.attrs.selected.name) {
1364 this.select_field(_.detect(this.fields, function(x) {return x.name == nval;}));
1368 * Selects the provided field object
1370 * @param field a field descriptor object (as returned by fields_get, augmented by the field name)
1372 select_field: function(field) {
1374 if(this.attrs.selected != null) {
1375 this.value.destroy();
1377 this.$element.find('.searchview_extended_prop_op').html('');
1379 this.attrs.selected = field;
1384 var type = field.type;
1386 openerp.web.search.custom_filters.get_object(type);
1388 if (! e instanceof openerp.web.KeyNotFound) {
1392 console.log('Unknow field type ' + e.key);
1394 this.value = new (openerp.web.search.custom_filters.get_object(type))
1396 if(this.value.set_field) {
1397 this.value.set_field(field);
1399 _.each(this.value.operators, function(operator) {
1400 $('<option>', {value: operator.value})
1401 .text(String(operator.text))
1402 .appendTo(self.$element.find('.searchview_extended_prop_op'));
1404 this.$element.find('.searchview_extended_prop_value').html(
1405 this.value.render({}));
1409 get_proposition: function() {
1410 if ( this.attrs.selected == null)
1412 var field = this.attrs.selected.name;
1413 var op = this.$element.find('.searchview_extended_prop_op').val();
1414 var value = this.value.get_value();
1415 return [field, op, value];
1419 openerp.web.search.ExtendedSearchProposition.Field = openerp.web.OldWidget.extend({
1420 start: function () {
1421 this.$element = $("#" + this.element_id);
1424 openerp.web.search.ExtendedSearchProposition.Char = openerp.web.search.ExtendedSearchProposition.Field.extend({
1425 template: 'SearchView.extended_search.proposition.char',
1427 {value: "ilike", text: _lt("contains")},
1428 {value: "not ilike", text: _lt("doesn't contain")},
1429 {value: "=", text: _lt("is equal to")},
1430 {value: "!=", text: _lt("is not equal to")}
1432 get_value: function() {
1433 return this.$element.val();
1436 openerp.web.search.ExtendedSearchProposition.DateTime = openerp.web.search.ExtendedSearchProposition.Field.extend({
1437 template: 'SearchView.extended_search.proposition.empty',
1439 {value: "=", text: _lt("is equal to")},
1440 {value: "!=", text: _lt("is not equal to")},
1441 {value: ">", text: _lt("greater than")},
1442 {value: "<", text: _lt("less than")},
1443 {value: ">=", text: _lt("greater or equal than")},
1444 {value: "<=", text: _lt("less or equal than")}
1446 get_value: function() {
1447 return this.datewidget.get_value();
1451 this.datewidget = new openerp.web.DateTimeWidget(this);
1452 this.datewidget.prependTo(this.$element);
1455 openerp.web.search.ExtendedSearchProposition.Date = openerp.web.search.ExtendedSearchProposition.Field.extend({
1456 template: 'SearchView.extended_search.proposition.empty',
1458 {value: "=", text: _lt("is equal to")},
1459 {value: "!=", text: _lt("is not equal to")},
1460 {value: ">", text: _lt("greater than")},
1461 {value: "<", text: _lt("less than")},
1462 {value: ">=", text: _lt("greater or equal than")},
1463 {value: "<=", text: _lt("less or equal than")}
1465 get_value: function() {
1466 return this.datewidget.get_value();
1470 this.datewidget = new openerp.web.DateWidget(this);
1471 this.datewidget.prependTo(this.$element);
1474 openerp.web.search.ExtendedSearchProposition.Integer = openerp.web.search.ExtendedSearchProposition.Field.extend({
1475 template: 'SearchView.extended_search.proposition.integer',
1477 {value: "=", text: _lt("is equal to")},
1478 {value: "!=", text: _lt("is not equal to")},
1479 {value: ">", text: _lt("greater than")},
1480 {value: "<", text: _lt("less than")},
1481 {value: ">=", text: _lt("greater or equal than")},
1482 {value: "<=", text: _lt("less or equal than")}
1484 get_value: function() {
1486 return openerp.web.parse_value(this.$element.val(), {'widget': 'integer'});
1492 openerp.web.search.ExtendedSearchProposition.Id = openerp.web.search.ExtendedSearchProposition.Integer.extend({
1493 operators: [{value: "=", text: _lt("is")}]
1495 openerp.web.search.ExtendedSearchProposition.Float = openerp.web.search.ExtendedSearchProposition.Field.extend({
1496 template: 'SearchView.extended_search.proposition.float',
1498 {value: "=", text: _lt("is equal to")},
1499 {value: "!=", text: _lt("is not equal to")},
1500 {value: ">", text: _lt("greater than")},
1501 {value: "<", text: _lt("less than")},
1502 {value: ">=", text: _lt("greater or equal than")},
1503 {value: "<=", text: _lt("less or equal than")}
1505 get_value: function() {
1507 return openerp.web.parse_value(this.$element.val(), {'widget': 'float'});
1513 openerp.web.search.ExtendedSearchProposition.Selection = openerp.web.search.ExtendedSearchProposition.Field.extend({
1514 template: 'SearchView.extended_search.proposition.selection',
1516 {value: "=", text: _lt("is")},
1517 {value: "!=", text: _lt("is not")}
1519 set_field: function(field) {
1522 get_value: function() {
1523 return this.$element.val();
1526 openerp.web.search.ExtendedSearchProposition.Boolean = openerp.web.search.ExtendedSearchProposition.Field.extend({
1527 template: 'SearchView.extended_search.proposition.boolean',
1529 {value: "=", text: _lt("is true")},
1530 {value: "!=", text: _lt("is false")}
1532 get_value: function() {
1537 openerp.web.search.custom_filters = new openerp.web.Registry({
1538 'char': 'openerp.web.search.ExtendedSearchProposition.Char',
1539 'text': 'openerp.web.search.ExtendedSearchProposition.Char',
1540 'one2many': 'openerp.web.search.ExtendedSearchProposition.Char',
1541 'many2one': 'openerp.web.search.ExtendedSearchProposition.Char',
1542 'many2many': 'openerp.web.search.ExtendedSearchProposition.Char',
1544 'datetime': 'openerp.web.search.ExtendedSearchProposition.DateTime',
1545 'date': 'openerp.web.search.ExtendedSearchProposition.Date',
1546 'integer': 'openerp.web.search.ExtendedSearchProposition.Integer',
1547 'float': 'openerp.web.search.ExtendedSearchProposition.Float',
1548 'boolean': 'openerp.web.search.ExtendedSearchProposition.Boolean',
1549 'selection': 'openerp.web.search.ExtendedSearchProposition.Selection',
1551 'id': 'openerp.web.search.ExtendedSearchProposition.Id'
1556 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: