[IMP] apply current advanced search when pressing [Return] while altering the search
[odoo/odoo.git] / addons / web / static / src / js / search.js
1 openerp.web.search = function(openerp) {
2 var QWeb = openerp.web.qweb,
3       _t =  openerp.web._t,
4      _lt = openerp.web._lt;
5 _.mixin({
6     sum: function (obj) { return _.reduce(obj, function (a, b) { return a + b; }, 0); }
7 });
8
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)({
14       app   : this.app,
15       model : facet,
16       order : position
17     });
18
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);
23
24     view.calculateSize();
25     _.defer(_.bind(view.calculateSize, view));
26
27     return 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)")) {
31     throw new Error(
32         "Trying to replace wrong version of VS.ui.SearchBox#renderFacet. "
33         + "Please fix replacement.");
34 }
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);
39   };
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)")) {
42     throw new Error(
43         "Trying to replace wrong version of VS.ui.SearchBox#renderSearchInput. "
44         + "Please fix replacement.");
45 }
46 var SearchBox_searchEvent = function (e) {
47     var query = null;
48     this.renderFacets();
49     this.focusSearch(e);
50     this.app.options.callbacks.search(query, this.app.searchQuery);
51   };
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)')) {
55     throw new Error(
56         "Trying to replace wrong version of VS.ui.SearchBox#searchEvent. "
57         + "Please fix replacement.");
58 }
59 _.extend(VS.ui.SearchBox.prototype, {
60     renderFacet: SearchBox_renderFacet,
61     renderSearchInput: SearchBox_renderSearchInput,
62     searchEvent: SearchBox_searchEvent
63 });
64 _.extend(VS.model.SearchFacet.prototype, {
65     value: function () {
66         if (this.has('json')) {
67             return this.get('json');
68         }
69         return this.get('value');
70     }
71 });
72
73 openerp.web.SearchView = openerp.web.Widget.extend(/** @lends openerp.web.SearchView# */{
74     template: "SearchView",
75     /**
76      * @constructs openerp.web.SearchView
77      * @extends openerp.web.OldWidget
78      *
79      * @param parent
80      * @param element_id
81      * @param dataset
82      * @param view_id
83      * @param defaults
84      */
85     init: function(parent, dataset, view_id, defaults, hidden) {
86         this._super(parent);
87         this.dataset = dataset;
88         this.model = dataset.model;
89         this.view_id = view_id;
90
91         this.defaults = defaults || {};
92         this.has_defaults = !_.isEmpty(this.defaults);
93
94         this.inputs = [];
95         this.controls = {};
96
97         this.hidden = !!hidden;
98         this.headless = this.hidden && !this.has_defaults;
99
100         this.filter_data = {};
101
102         this.ready = $.Deferred();
103     },
104     start: function() {
105         var self = this;
106         var p = this._super();
107
108         this.setup_global_completion();
109         this.vs = VS.init({
110             container: this.$element,
111             query: '',
112             callbacks: {
113                 make_facet: this.proxy('make_visualsearch_facet'),
114                 make_input: this.proxy('make_visualsearch_input'),
115                 search: function (query, searchCollection) {
116                     self.do_search();
117                 },
118                 facetMatches: function (callback) {
119                 },
120                 valueMatches : function(facet, searchTerm, callback) {
121                 }
122             }
123         });
124
125         var search = function () { self.vs.searchBox.searchEvent({}); };
126         // searchQuery operations
127         this.vs.searchQuery
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']) {
133                     search();
134                 }
135             });
136
137         if (this.hidden) {
138             this.$element.hide();
139         }
140         if (this.headless) {
141             this.ready.resolve();
142         } else {
143             var load_view = this.rpc("/web/searchview/load", {
144                 model: this.model,
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', {
149                 model: this.model
150             }).then(function (filters) { self.custom_filters = filters; });
151
152             $.when(load_view, filters)
153                 .pipe(function (load) { return load[0]; })
154                 .then(this.on_loaded);
155         }
156
157         this.$element.on('click', '.oe_vs_unfold_drawer', function () {
158             self.$element.toggleClass('oe_searchview_open_drawer');
159         });
160
161         return $.when(p, this.ready);
162     },
163     show: function () {
164         this.$element.show();
165     },
166     hide: function () {
167         this.$element.hide();
168     },
169
170     /**
171      * Sets up thingie where all the mess is put?
172      */
173     setup_stuff_drawer: function () {
174         var self = this;
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);
178
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()
183             .flatten()
184             .filter(is_group)
185             .map(function (i) { return i.filters.length; })
186             .sum()
187             .value();
188
189         var col1 = [], col2 = _(this.controls).map(function (inputs, group) {
190             var filters = _(inputs).filter(is_group);
191             return {
192                 name: group === 'null' ? _t("Filters") : group,
193                 filters: filters,
194                 length: _(filters).chain().map(function (i) {
195                     return i.filters.length; }).sum().value()
196             };
197         });
198
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());
204             } else {
205                 break;
206             }
207         }
208
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: {
216                     string: filter.name,
217                     context: filter.context,
218                     domain: filter.domain
219                 }}, self);
220                 return new openerp.web.search.FilterGroup([f], self);
221             }),
222             length: 3
223         });
224
225         return $.when(
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)));
229     },
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));
235         }));
236     },
237     /**
238      * Sets up search view's view-wide auto-completion widget
239      */
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();
245         });
246
247         this.$element.autocomplete({
248             source: this.proxy('complete_global_search'),
249             select: this.proxy('select_completion'),
250             focus: function (e) { e.preventDefault(); },
251             html: true,
252             minLength: 0,
253             delay: 0
254         }).data('autocomplete')._renderItem = function (ul, item) {
255             // item of completion list
256             var $item = $( "<li></li>" )
257                 .data( "item.autocomplete", item )
258                 .appendTo( ul );
259
260             if (item.value !== undefined) {
261                 // regular completion item
262                 return $item.append(
263                     (item.label)
264                         ? $('<a>').html(item.label)
265                         : $('<a>').text(item.value));
266             }
267             return $item.text(item.category)
268                 .css({
269                     borderTop: '1px solid #cccccc',
270                     margin: 0,
271                     padding: 0,
272                     zoom: 1,
273                     'float': 'left',
274                     clear: 'left',
275                     width: '100%'
276                 });
277         }
278     },
279     /**
280      * Provide auto-completion result for req.term (an array to `resp`)
281      *
282      * @param {Object} req request to complete
283      * @param {String} req.term searched term to complete
284      * @param {Function} resp response callback
285      */
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));
291         });
292     },
293
294     /**
295      * Action to perform in case of selection: create a facet (model)
296      * and add it to the search collection
297      *
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
301      */
302     select_completion: function (e, ui) {
303         e.preventDefault();
304         this.vs.searchQuery.add(new VS.model.SearchFacet(_.extend(
305             {app: this.vs}, ui.item)));
306         this.vs.searchBox.searchEvent({});
307     },
308
309     /**
310      * Builds the right SearchFacet view based on the facet object to render
311      * (e.g. readonly facets for filters)
312      *
313      * @param {Object} options
314      * @param {VS.model.SearchFacet} options.model facet object to render
315      */
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);
319         }
320         return new VS.ui.SearchFacet(options);
321     },
322     /**
323      * Proxies searches on a SearchInput to the search view's global completion
324      *
325      * Also disables SearchInput.autocomplete#_move so search view's
326      * autocomplete can get the corresponding events, or something.
327      *
328      * @param options
329      */
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({
334                 minLength: 1,
335                 delay: 0,
336                 search: function () {
337                     self.$element.autocomplete('search', input.box.val());
338                     return false;
339                 }
340             }).data('autocomplete'), {
341                 _move: function () {},
342                 close: function () { self.$element.autocomplete('close'); }
343             });
344         };
345         return input;
346     },
347
348     /**
349      * Builds a list of widget rows (each row is an array of widgets)
350      *
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
354      */
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] = [];
359         }
360         var self = this, group = this.controls[group_name];
361         var filters = [];
362         _.each(items, function (item) {
363             if (filters.length && item.tag !== 'filter') {
364                 group.push(new openerp.web.search.FilterGroup(filters, this));
365                 filters = [];
366             }
367
368             switch (item.tag) {
369             case 'separator': case 'newline':
370                 break;
371             case 'filter':
372                 filters.push(new openerp.web.search.Filter(item, this));
373                 break;
374             case 'group':
375                 self.make_widgets(item.children, fields, item.attrs.string);
376                 break;
377             case 'field':
378                 group.push(this.make_field(item, fields[item['attrs'].name]));
379                 // filters
380                 self.make_widgets(item.children, fields, group_name);
381                 break;
382             }
383         }, this);
384
385         if (filters.length) {
386             group.push(new openerp.web.search.FilterGroup(filters, this));
387         }
388     },
389     /**
390      * Creates a field for the provided field descriptor item (which comes
391      * from fields_view_get)
392      *
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
396      */
397     make_field: function (item, field) {
398         try {
399             return new (openerp.web.search.fields.get_any(
400                     [item.attrs.widget, field.type]))
401                 (item, field, this);
402         } catch (e) {
403             if (! e instanceof openerp.web.KeyNotFound) {
404                 throw e;
405             }
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);
411             console.groupEnd();
412             return null;
413         }
414     },
415     on_loaded: function(data) {
416         var self = this;
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));
423         }
424
425         this.make_widgets(
426             data.fields_view['arch'].children,
427             data.fields_view.fields);
428
429         // load defaults
430         return $.when(
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(); })
435     },
436     /**
437      * Handle event when the user make a selection in the filters management select box.
438      */
439     on_filters_management: function(e) {
440         var self = this;
441         var select = this.$element.find(".oe_search-view-filters-management");
442         var val = select.val();
443         switch(val) {
444         case 'advanced_filter':
445             this.extended_search.on_activate();
446             break;
447         case 'add_to_dashboard':
448             this.on_add_to_dashboard();
449             break;
450         case 'manage_filters':
451             this.do_action({
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},
457                 target: "current",
458                 limit : 80
459             });
460             break;
461         case 'save_filter':
462             var data = this.build_search_data();
463             var context = new openerp.web.CompoundContext();
464             _.each(data.contexts, function(x) {
465                 context.add(x);
466             });
467             var domain = new openerp.web.CompoundDomain();
468             _.each(data.domains, function(x) {
469                 domain.add(x);
470             });
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, {
476                 modal: true,
477                 title: _t("Filter Entry"),
478                 buttons: [
479                     {text: _t("Cancel"), click: function() {
480                         $(this).dialog("close");
481                     }},
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,
488                             domain: domain,
489                             name: name
490                         }).then(function() {
491                             self.reload_managed_filters();
492                         });
493                     }}
494                 ]
495             });
496             break;
497         case '':
498             this.do_clear();
499         }
500         if (val.slice(0, 4) == "get:") {
501             val = val.slice(4);
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);
506
507                 var groupbys = [];
508                 var group_by = filter.context.group_by;
509                 if (group_by) {
510                     groupbys = _.map(
511                         group_by instanceof Array ? group_by : group_by.split(','),
512                         function (el) { return { group_by: el }; });
513                 }
514                 this.filter_data = {
515                     domains: [filter.domain],
516                     contexts: [filter.context],
517                     groupbys: groupbys
518                 };
519                 this.do_search();
520             }, this));
521         } else {
522             select.val('');
523         }
524     },
525     on_add_to_dashboard: function() {
526         this.$element.find(".oe_search-view-filters-management")[0].selectedIndex = 0;
527         var self = this,
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')
532             }));
533         $dialog.find('input').val(this.fields_view.name);
534         openerp.web.dialog($dialog, {
535             modal: true,
536             title: _t("Add to Dashboard"),
537             buttons: [
538                 {text: _t("Cancel"), click: function() {
539                     $(this).dialog("close");
540                 }},
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) {
549                         context.add(x);
550                     });
551                     _.each(data.domains, function(x) {
552                            domain.add(x);
553                     });
554                     self.rpc('/web/searchview/add_to_dashboard', {
555                         menu_id: menu_id,
556                         action_id: self.getParent().action.id,
557                         context_to_save: context,
558                         domain: domain,
559                         view_mode: self.getParent().active_view,
560                         name: title
561                     }, function(r) {
562                         if (r === false) {
563                             self.do_warn("Could not add filter to dashboard");
564                         } else {
565                             self.do_notify("Filter added to dashboard", '');
566                         }
567                     });
568                 }}
569             ]
570         });
571     },
572     /**
573      * Performs the search view collection of widget data.
574      *
575      * If the collection went well (all fields are valid), then triggers
576      * :js:func:`openerp.web.SearchView.on_search`.
577      *
578      * If at least one field failed its validation, triggers
579      * :js:func:`openerp.web.SearchView.on_invalid` instead.
580      *
581      * @param e jQuery event object coming from the "Search" button
582      */
583     do_search: function () {
584         var domains = [], contexts = [], groupbys = [], errors = [];
585
586         this.vs.searchQuery.each(function (facet) {
587             var field = facet.get('field');
588             try {
589                 var domain = field.get_domain(facet);
590                 if (domain) {
591                     domains.push(domain);
592                 }
593                 var context = field.get_context(facet);
594                 if (context) {
595                     contexts.push(context);
596                     groupbys.push(context);
597                 }
598             } catch (e) {
599                 if (e instanceof openerp.web.search.Invalid) {
600                     errors.push(e);
601                 } else {
602                     throw e;
603                 }
604             }
605         });
606
607         if (!_.isEmpty(errors)) {
608             this.on_invalid(errors);
609             return;
610         }
611         return this.on_search(domains, contexts, groupbys);
612     },
613     /**
614      * Triggered after the SearchView has collected all relevant domains and
615      * contexts.
616      *
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)
620      *
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)
623      *
624      * @event
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
628      */
629     on_search: function (domains, contexts, groupbys) {
630     },
631     /**
632      * Triggered after a validation error in the SearchView fields.
633      *
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
638      *
639      * @event
640      * @param {Array} errors a never-empty array of error objects
641      */
642     on_invalid: function (errors) {
643         this.do_notify(_t("Invalid Search"), _t("triggered from search view"));
644     }
645 });
646
647 /** @namespace */
648 openerp.web.search = {};
649
650 openerp.web.search.FilterGroupFacet = VS.ui.SearchFacet.extend({
651     events: _.extend({
652         'click': 'selectFacet'
653     }, VS.ui.SearchFacet.prototype.events),
654
655     render: function () {
656         this.setMode('not', 'editing');
657         this.setMode('not', 'selected');
658
659         var value = this.model.get('value');
660         this.$el.html(QWeb.render('SearchView.filters.facet', {
661             facet: this.model
662         }));
663         // virtual input so SearchFacet code has something to play with
664         this.box = $('<input>').val(value);
665
666         return this;
667     },
668     enableEdit: function () {
669         this.selectFacet()
670     },
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);
675         }
676         e.preventDefault();
677         this.deselectFacet();
678         this.options.app.searchBox.focusNextFacet(this, 1);
679     }
680 });
681 /**
682  * Registry of search fields, called by :js:class:`openerp.web.SearchView` to
683  * find and instantiate its field widgets.
684  */
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'
698 });
699 openerp.web.search.Invalid = openerp.web.Class.extend( /** @lends openerp.web.search.Invalid# */{
700     /**
701      * Exception thrown by search widgets when they hold invalid values,
702      * which they can not return when asked.
703      *
704      * @constructs openerp.web.search.Invalid
705      * @extends openerp.web.Class
706      *
707      * @param field the name of the field holding an invalid value
708      * @param value the invalid value
709      * @param message validation failure message
710      */
711     init: function (field, value, message) {
712         this.field = field;
713         this.value = value;
714         this.message = message;
715     },
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}
720         );
721     }
722 });
723 openerp.web.search.Widget = openerp.web.OldWidget.extend( /** @lends openerp.web.search.Widget# */{
724     template: null,
725     /**
726      * Root class of all search widgets
727      *
728      * @constructs openerp.web.search.Widget
729      * @extends openerp.web.OldWidget
730      *
731      * @param view the ancestor view of this widget
732      */
733     init: function (view) {
734         this._super(view);
735         this.view = view;
736     }
737 });
738 openerp.web.search.add_expand_listener = function($root) {
739     $root.find('a.searchview_group_string').click(function (e) {
740         $root.toggleClass('folded expanded');
741         e.stopPropagation();
742         e.preventDefault();
743     });
744 };
745 openerp.web.search.Group = openerp.web.search.Widget.extend({
746     template: 'SearchView.group',
747     init: function (view_section, view, fields) {
748         this._super(view);
749         this.attrs = view_section.attrs;
750         this.lines = view.make_widgets(
751             view_section.children, fields);
752     }
753 });
754
755 openerp.web.search.Input = openerp.web.search.Widget.extend( /** @lends openerp.web.search.Input# */{
756     /**
757      * @constructs openerp.web.search.Input
758      * @extends openerp.web.search.Widget
759      *
760      * @param view
761      */
762     init: function (view) {
763         this._super(view);
764         this.view.inputs.push(this);
765         this.style = undefined;
766     },
767     /**
768      * Fetch auto-completion values for the widget.
769      *
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
772      *
773      * @param {String} value value to complete
774      * @returns {jQuery.Deferred<null|Array>}
775      */
776     complete: function (value) {
777         return $.when(null)
778     },
779     /**
780      * Returns a VS.model.SearchFacet instance for the provided defaults if
781      * they apply to this widget, or null if they don't.
782      *
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
786      *
787      * @param {Object} defaults
788      * @returns {jQuery.Deferred<null|Object>}
789      */
790     facet_for_defaults: function (defaults) {
791         if (!this.attrs ||
792             !(this.attrs.name in defaults && defaults[this.attrs.name])) {
793             return $.when(null);
794         }
795         return this.facet_for(defaults[this.attrs.name]);
796     },
797     get_context: function () {
798         throw new Error(
799             "get_context not implemented for widget " + this.attrs.type);
800     },
801     get_domain: function () {
802         throw new Error(
803             "get_domain not implemented for widget " + this.attrs.type);
804     },
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;'
811             }
812         }
813         this.attrs = attrs;
814     }
815 });
816 openerp.web.search.FilterGroup = openerp.web.search.Input.extend(/** @lends openerp.web.search.FilterGroup# */{
817     template: 'SearchView.filters',
818     /**
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)
821      *
822      * @constructs openerp.web.search.FilterGroup
823      * @extends openerp.web.search.Input
824      *
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
827      */
828     init: function (filters, view) {
829         this._super(view);
830         this.filters = filters;
831     },
832     start: function () {
833         this.$element.on('click', 'li', this.proxy('toggle_filter'));
834         return $.when(null);
835     },
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];
839         });
840         if (_.isEmpty(fs)) { return $.when(null); }
841         return $.when(new VS.model.SearchFacet({
842             category: 'q',
843             value: _(fs).map(function (f) {
844                 return f.attrs.string || f.attrs.name }).join(' | '),
845             json: fs,
846             field: this,
847             app: this.view.vs
848         }));
849     },
850     /**
851      * Fetches contexts for all enabled filters in the group
852      *
853      * @param {VS.model.SearchFacet} facet
854      * @return {*} combined contexts of the enabled filters in this group
855      */
856     get_context: function (facet) {
857         var contexts = _(facet.get('json')).chain()
858             .map(function (filter) { return filter.attrs.context; })
859             .reject(_.isEmpty)
860             .value();
861
862         if (!contexts.length) { return; }
863         if (contexts.length === 1) { return contexts[0]; }
864         return _.extend(new openerp.web.CompoundContext, {
865             __contexts: contexts
866         });
867     },
868     /**
869      * Handles domains-fetching for all the filters within it: groups them.
870      *
871      * @param {VS.model.SearchFacet} facet
872      * @return {*} combined domains of the enabled filters in this group
873      */
874     get_domain: function (facet) {
875         var domains = _(facet.get('json')).chain()
876             .map(function (filter) { return filter.attrs.domain; })
877             .reject(_.isEmpty)
878             .value();
879
880         if (!domains.length) { return; }
881         if (domains.length === 1) { return domains[0]; }
882         for (var i=domains.length; --i;) {
883             domains.unshift(['|']);
884         }
885         return _.extend(new openerp.web.CompoundDomain(), {
886             __domains: domains
887         });
888     },
889     toggle_filter: function (e) {
890         this.toggle(this.filters[$(e.target).index()]);
891     },
892     toggle: function (filter) {
893         // FIXME: oh god, my eyes, they hurt
894         var self = this, fs;
895         var facet = this.view.vs.searchQuery.detect(function (f) {
896             return f.get('field') === self; });
897         if (facet) {
898             fs = facet.get('json');
899
900             if (_.include(fs, filter)) {
901                 fs = _.without(fs, filter);
902             } else {
903                 fs.push(filter);
904             }
905             if (_(fs).isEmpty()) {
906                 this.view.vs.searchQuery.remove(facet, {trigger_search: true});
907             } else {
908                 facet.set({
909                     json: fs,
910                     value: _(fs).map(function (f) {
911                         return f.attrs.string || f.attrs.name }).join(' | ')
912                 });
913             }
914             return;
915         } else {
916             fs = [filter];
917         }
918
919         this.view.vs.searchQuery.add({
920             category: 'q',
921             value: _(fs).map(function (f) {
922                 return f.attrs.string || f.attrs.name }).join(' | '),
923             json: fs,
924             field: this,
925             app: this.view.vs
926         });
927     }
928 });
929 openerp.web.search.Filter = openerp.web.search.Input.extend(/** @lends openerp.web.search.Filter# */{
930     template: 'SearchView.filter',
931     /**
932      * Implementation of the OpenERP filters (button with a context and/or
933      * a domain sent as-is to the search view)
934      *
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.
938      *
939      * @constructs openerp.web.search.Filter
940      * @extends openerp.web.search.Input
941      *
942      * @param node
943      * @param view
944      */
945     init: function (node, view) {
946         this._super(view);
947         this.load_attrs(node.attrs);
948     },
949     facet_for: function () { return $.when(null); },
950     get_context: function () { },
951     get_domain: function () { }
952 });
953 openerp.web.search.Field = openerp.web.search.Input.extend( /** @lends openerp.web.search.Field# */ {
954     template: 'SearchView.field',
955     default_operator: '=',
956     /**
957      * @constructs openerp.web.search.Field
958      * @extends openerp.web.search.Input
959      *
960      * @param view_section
961      * @param field
962      * @param view
963      */
964     init: function (view_section, field, view) {
965         this._super(view);
966         this.load_attrs(_.extend({}, field, view_section.attrs));
967     },
968     facet_for: function (value) {
969         return $.when(new VS.model.SearchFacet({
970             category: this.attrs.string || this.attrs.name,
971             value: String(value),
972             json: value,
973             field: this,
974             app: this.view.vs
975         }));
976     },
977     get_value: function (facet) {
978         return facet.value();
979     },
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
983         // active
984         var has_value = (val !== null && val !== '');
985         var context = this.attrs.context;
986         if (!(has_value && context)) {
987             return;
988         }
989         return new openerp.web.CompoundContext(context)
990                 .set_eval_context({self: val});
991     },
992     /**
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)
997      *
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
1002      */
1003     make_domain: function (name, operator, facet) {
1004         return [[name, operator, this.get_value(facet)]];
1005     },
1006     get_domain: function (facet) {
1007         var val = this.get_value(facet);
1008         if (val === null || val === '') {
1009             return;
1010         }
1011
1012         var domain = this.attrs['filter_domain'];
1013         if (!domain) {
1014             return this.make_domain(
1015                 this.attrs.name,
1016                 this.attrs.operator || this.default_operator,
1017                 facet);
1018         }
1019         return new openerp.web.CompoundDomain(domain)
1020                 .set_eval_context({self: val});
1021     }
1022 });
1023 /**
1024  * Implementation of the ``char`` OpenERP field type:
1025  *
1026  * * Default operator is ``ilike`` rather than ``=``
1027  *
1028  * * The Javascript and the HTML values are identical (strings)
1029  *
1030  * @class
1031  * @extends openerp.web.search.Field
1032  */
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>'});
1041         return $.when([{
1042             category: this.attrs.string,
1043             label: label,
1044             value: value,
1045             field: this
1046         }]);
1047     }
1048 });
1049 openerp.web.search.NumberField = openerp.web.search.Field.extend(/** @lends openerp.web.search.NumberField# */{
1050     get_value: function () {
1051         if (!this.$element.val()) {
1052             return null;
1053         }
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);
1060         }
1061         this.$element.removeClass('error');
1062         return val;
1063     }
1064 });
1065 /**
1066  * @class
1067  * @extends openerp.web.search.NumberField
1068  */
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) {
1072         try {
1073             return openerp.web.parse_value(value, {'widget': 'integer'});
1074         } catch (e) {
1075             return NaN;
1076         }
1077     }
1078 });
1079 /**
1080  * @class
1081  * @extends openerp.web.search.NumberField
1082  */
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) {
1086         try {
1087             return openerp.web.parse_value(value, {'widget': 'float'});
1088         } catch (e) {
1089             return NaN;
1090         }
1091     }
1092 });
1093 /**
1094  * @class
1095  * @extends openerp.web.search.Field
1096  */
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',
1109     init: function () {
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) {
1113             return !item[1];
1114         });
1115     },
1116     complete: function (needle) {
1117         var self = this;
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;
1123             })
1124             .map(function (sel) {
1125                 return {
1126                     category: self.attrs.string,
1127                     field: self,
1128                     value: sel[1],
1129                     json: sel[0]
1130                 };
1131             }).value();
1132         if (_.isEmpty(results)) { return $.when(null); }
1133         return $.when.apply(null, [{
1134             category: this.attrs.string
1135         }].concat(results));
1136     },
1137     facet_for: function (value) {
1138         var match = _(this.attrs.selection).detect(function (sel) {
1139             return sel[0] === value;
1140         });
1141         if (!match) { return $.when(null); }
1142         return $.when(new VS.model.SearchFacet({
1143             category: this.attrs.string,
1144             value: match[1],
1145             json: match[0],
1146             field: this,
1147             app: this.view.app
1148         }));
1149     },
1150     get_value: function (facet) {
1151         return facet.get('json');
1152     }
1153 });
1154 openerp.web.search.BooleanField = openerp.web.search.SelectionField.extend(/** @lends openerp.web.search.BooleanField# */{
1155     /**
1156      * @constructs openerp.web.search.BooleanField
1157      * @extends openerp.web.search.BooleanField
1158      */
1159     init: function () {
1160         this._super.apply(this, arguments);
1161         this.attrs.selection = [
1162             ['true', _t("Yes")],
1163             ['false', _t("No")]
1164         ];
1165     },
1166     get_value: function (facet) {
1167         switch (this._super(facet)) {
1168             case 'false': return false;
1169             case 'true': return true;
1170             default: return null;
1171         }
1172     }
1173 });
1174 /**
1175  * @class
1176  * @extends openerp.web.search.DateField
1177  */
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'));
1181     },
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>'});
1190         return $.when([{
1191             category: this.attrs.string,
1192             label: label,
1193             value: value,
1194             json: d,
1195             field: this
1196         }]);
1197     }
1198 });
1199 /**
1200  * Implementation of the ``datetime`` openerp field type:
1201  *
1202  * * Uses the same widget as the ``date`` field type (a simple date)
1203  *
1204  * * Builds a slighly more complex, it's a datetime range (includes time)
1205  *   spanning the whole day selected by the date widget
1206  *
1207  * @class
1208  * @extends openerp.web.DateField
1209  */
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'));
1213     }
1214 });
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);
1219     },
1220     complete: function (needle) {
1221         var self = this;
1222         // TODO: context
1223         // FIXME: "concurrent" searches (multiple requests, mis-ordered responses)
1224         return this.model.call('name_search', [], {
1225             name: needle,
1226             limit: 8,
1227             context: {}
1228         }).pipe(function (results) {
1229             if (_.isEmpty(results)) { return null; }
1230             return [{category: self.attrs.string}].concat(
1231                 _(results).map(function (result) {
1232                     return {
1233                         category: self.attrs.string,
1234                         value: result[1],
1235                         json: result[0],
1236                         field: self
1237                     };
1238                 }));
1239         });
1240     },
1241     facet_for: function (value) {
1242         var self = this;
1243         if (value instanceof Array) {
1244             return $.when(new VS.model.SearchFacet({
1245                 category: this.attrs.string,
1246                 value: value[1],
1247                 json: value[0],
1248                 field: this,
1249                 app: this.view.vs
1250             }));
1251         }
1252         return this.model.call('name_get', [value], {}).pipe(function (names) {
1253                 return new VS.model.SearchFacet({
1254                 category: self.attrs.string,
1255                 value: names[0][1],
1256                 json: names[0][0],
1257                 field: self,
1258                 app: self.view.vs
1259             });
1260         })
1261     },
1262     make_domain: function (name, operator, facet) {
1263         // ``json`` -> actual auto-completed id
1264         if (facet.get('json')) {
1265             return [[name, '=', facet.get('json')]];
1266         }
1267
1268         return this._super(name, operator, facet);
1269     }
1270 });
1271
1272 openerp.web.search.Advanced = openerp.web.search.Input.extend({
1273     template: 'SearchView.advanced',
1274     start: function () {
1275         var self = this;
1276         this.propositions = [];
1277         this.$element
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) {
1284                 e.preventDefault();
1285                 self.commit_search();
1286             });
1287         return $.when(
1288             this._super(),
1289             this.rpc("/web/searchview/fields_get", {model: this.view.model}, function(data) {
1290                 self.fields = _.extend({
1291                     id: { string: 'ID', type: 'id' }
1292                 }, data.fields);
1293         })).then(function () {
1294             self.append_proposition();
1295         });
1296     },
1297     append_proposition: function () {
1298         return (new openerp.web.search.ExtendedSearchProposition(this, this.fields))
1299             .appendTo(this.$element.find('ul'));
1300     },
1301     commit_search: function () {
1302         var self = this;
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]),
1310                 domain: [section]
1311             }}, self.view);
1312         });
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({
1317             category: 'q',
1318             value: _(filters).map(function (f) {
1319                 return f.attrs.string || f.attrs.name }).join(' | '),
1320             json: filters,
1321             field: f,
1322             app: this.view.vs
1323         });
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');
1330     }
1331 });
1332
1333 openerp.web.search.ExtendedSearchProposition = openerp.web.OldWidget.extend(/** @lends openerp.web.search.ExtendedSearchProposition# */{
1334     template: 'SearchView.extended_search.proposition',
1335     /**
1336      * @constructs openerp.web.search.ExtendedSearchProposition
1337      * @extends openerp.web.OldWidget
1338      *
1339      * @param parent
1340      * @param fields
1341      */
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;})
1347             .value();
1348         this.attrs = {_: _, fields: this.fields, selected: null};
1349         this.value = null;
1350     },
1351     start: function () {
1352         this.select_field(this.fields.length > 0 ? this.fields[0] : null);
1353         var _this = this;
1354         this.$element.find(".searchview_extended_prop_field").change(function() {
1355             _this.changed();
1356         });
1357         this.$element.find('.searchview_extended_delete_prop').click(function () {
1358             _this.destroy();
1359         });
1360     },
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;}));
1365         }
1366     },
1367     /**
1368      * Selects the provided field object
1369      *
1370      * @param field a field descriptor object (as returned by fields_get, augmented by the field name)
1371      */
1372     select_field: function(field) {
1373         var self = this;
1374         if(this.attrs.selected != null) {
1375             this.value.destroy();
1376             this.value = null;
1377             this.$element.find('.searchview_extended_prop_op').html('');
1378         }
1379         this.attrs.selected = field;
1380         if(field == null) {
1381             return;
1382         }
1383
1384         var type = field.type;
1385         try {
1386             openerp.web.search.custom_filters.get_object(type);
1387         } catch (e) {
1388             if (! e instanceof openerp.web.KeyNotFound) {
1389                 throw e;
1390             }
1391             type = "char";
1392             console.log('Unknow field type ' + e.key);
1393         }
1394         this.value = new (openerp.web.search.custom_filters.get_object(type))
1395                           (this);
1396         if(this.value.set_field) {
1397             this.value.set_field(field);
1398         }
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'));
1403         });
1404         this.$element.find('.searchview_extended_prop_value').html(
1405             this.value.render({}));
1406         this.value.start();
1407
1408     },
1409     get_proposition: function() {
1410         if ( this.attrs.selected == null)
1411             return 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];
1416     }
1417 });
1418
1419 openerp.web.search.ExtendedSearchProposition.Field = openerp.web.OldWidget.extend({
1420     start: function () {
1421         this.$element = $("#" + this.element_id);
1422     }
1423 });
1424 openerp.web.search.ExtendedSearchProposition.Char = openerp.web.search.ExtendedSearchProposition.Field.extend({
1425     template: 'SearchView.extended_search.proposition.char',
1426     operators: [
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")}
1431     ],
1432     get_value: function() {
1433         return this.$element.val();
1434     }
1435 });
1436 openerp.web.search.ExtendedSearchProposition.DateTime = openerp.web.search.ExtendedSearchProposition.Field.extend({
1437     template: 'SearchView.extended_search.proposition.empty',
1438     operators: [
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")}
1445     ],
1446     get_value: function() {
1447         return this.datewidget.get_value();
1448     },
1449     start: function() {
1450         this._super();
1451         this.datewidget = new openerp.web.DateTimeWidget(this);
1452         this.datewidget.prependTo(this.$element);
1453     }
1454 });
1455 openerp.web.search.ExtendedSearchProposition.Date = openerp.web.search.ExtendedSearchProposition.Field.extend({
1456     template: 'SearchView.extended_search.proposition.empty',
1457     operators: [
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")}
1464     ],
1465     get_value: function() {
1466         return this.datewidget.get_value();
1467     },
1468     start: function() {
1469         this._super();
1470         this.datewidget = new openerp.web.DateWidget(this);
1471         this.datewidget.prependTo(this.$element);
1472     }
1473 });
1474 openerp.web.search.ExtendedSearchProposition.Integer = openerp.web.search.ExtendedSearchProposition.Field.extend({
1475     template: 'SearchView.extended_search.proposition.integer',
1476     operators: [
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")}
1483     ],
1484     get_value: function() {
1485         try {
1486             return openerp.web.parse_value(this.$element.val(), {'widget': 'integer'});
1487         } catch (e) {
1488             return "";
1489         }
1490     }
1491 });
1492 openerp.web.search.ExtendedSearchProposition.Id = openerp.web.search.ExtendedSearchProposition.Integer.extend({
1493     operators: [{value: "=", text: _lt("is")}]
1494 });
1495 openerp.web.search.ExtendedSearchProposition.Float = openerp.web.search.ExtendedSearchProposition.Field.extend({
1496     template: 'SearchView.extended_search.proposition.float',
1497     operators: [
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")}
1504     ],
1505     get_value: function() {
1506         try {
1507             return openerp.web.parse_value(this.$element.val(), {'widget': 'float'});
1508         } catch (e) {
1509             return "";
1510         }
1511     }
1512 });
1513 openerp.web.search.ExtendedSearchProposition.Selection = openerp.web.search.ExtendedSearchProposition.Field.extend({
1514     template: 'SearchView.extended_search.proposition.selection',
1515     operators: [
1516         {value: "=", text: _lt("is")},
1517         {value: "!=", text: _lt("is not")}
1518     ],
1519     set_field: function(field) {
1520         this.field = field;
1521     },
1522     get_value: function() {
1523         return this.$element.val();
1524     }
1525 });
1526 openerp.web.search.ExtendedSearchProposition.Boolean = openerp.web.search.ExtendedSearchProposition.Field.extend({
1527     template: 'SearchView.extended_search.proposition.boolean',
1528     operators: [
1529         {value: "=", text: _lt("is true")},
1530         {value: "!=", text: _lt("is false")}
1531     ],
1532     get_value: function() {
1533         return true;
1534     }
1535 });
1536
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',
1543
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',
1550
1551     'id': 'openerp.web.search.ExtendedSearchProposition.Id'
1552 });
1553
1554 };
1555
1556 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: