[IMP] made a whole-application replace of $element by $el
[odoo/odoo.git] / addons / web / static / src / js / view_list.js
1 openerp.web.list = function (instance) {
2 var _t = instance.web._t,
3    _lt = instance.web._lt;
4 var QWeb = instance.web.qweb;
5 instance.web.views.add('list', 'instance.web.ListView');
6 instance.web.ListView = instance.web.View.extend( /** @lends instance.web.ListView# */ {
7     _template: 'ListView',
8     display_name: _lt('List'),
9     defaults: {
10         // records can be selected one by one
11         'selectable': true,
12         // list rows can be deleted
13         'deletable': false,
14         // whether the column headers should be displayed
15         'header': true,
16         // display addition button, with that label
17         'addable': _lt("Create"),
18         // whether the list view can be sorted, note that once a view has been
19         // sorted it can not be reordered anymore
20         'sortable': true,
21         // whether the view rows can be reordered (via vertical drag & drop)
22         'reorderable': true,
23         'action_buttons': true,
24         // if true, the 'Import', 'Export', etc... buttons will be shown
25         'import_enabled': true,
26     },
27     /**
28      * Core class for list-type displays.
29      *
30      * As a view, needs a number of view-related parameters to be correctly
31      * instantiated, provides options and overridable methods for behavioral
32      * customization.
33      *
34      * See constructor parameters and method documentations for information on
35      * the default behaviors and possible options for the list view.
36      *
37      * @constructs instance.web.ListView
38      * @extends instance.web.View
39      *
40      * @param parent parent object
41      * @param {instance.web.DataSet} dataset the dataset the view should work with
42      * @param {String} view_id the listview's identifier, if any
43      * @param {Object} options A set of options used to configure the view
44      * @param {Boolean} [options.selectable=true] determines whether view rows are selectable (e.g. via a checkbox)
45      * @param {Boolean} [options.header=true] should the list's header be displayed
46      * @param {Boolean} [options.deletable=true] are the list rows deletable
47      * @param {void|String} [options.addable="New"] should the new-record button be displayed, and what should its label be. Use ``null`` to hide the button.
48      * @param {Boolean} [options.sortable=true] is it possible to sort the table by clicking on column headers
49      * @param {Boolean} [options.reorderable=true] is it possible to reorder list rows
50      */
51     init: function(parent, dataset, view_id, options) {
52         var self = this;
53         this._super(parent);
54         this.set_default_options(_.extend({}, this.defaults, options || {}));
55         this.dataset = dataset;
56         this.model = dataset.model;
57         this.view_id = view_id;
58         this.previous_colspan = null;
59         this.colors = null;
60         this.fonts = null;
61
62         this.columns = [];
63
64         this.records = new Collection();
65
66         this.set_groups(new (this.options.GroupsType)(this));
67
68         if (this.dataset instanceof instance.web.DataSetStatic) {
69             this.groups.datagroup = new instance.web.StaticDataGroup(this.dataset);
70         } else {
71             this.groups.datagroup = new instance.web.DataGroup(
72                 this, this.model,
73                 dataset.get_domain(),
74                 dataset.get_context());
75             this.groups.datagroup.sort = this.dataset._sort;
76         }
77
78         this.page = 0;
79         this.records.bind('change', function (event, record, key) {
80             if (!_(self.aggregate_columns).chain()
81                     .pluck('name').contains(key).value()) {
82                 return;
83             }
84             self.compute_aggregates();
85         });
86
87         this.no_leaf = false;
88     },
89     set_default_options: function (options) {
90         this._super(options);
91         _.defaults(this.options, {
92             GroupsType: instance.web.ListView.Groups,
93             ListType: instance.web.ListView.List
94         });
95     },
96
97     /**
98      * Retrieves the view's number of records per page (|| section)
99      *
100      * options > defaults > parent.action.limit > indefinite
101      *
102      * @returns {Number|null}
103      */
104     limit: function () {
105         if (this._limit === undefined) {
106             this._limit = (this.options.limit
107                         || this.defaults.limit
108                         || (this.getParent().action || {}).limit
109                         || 80);
110         }
111         return this._limit;
112     },
113     /**
114      * Set a custom Group construct as the root of the List View.
115      *
116      * @param {instance.web.ListView.Groups} groups
117      */
118     set_groups: function (groups) {
119         var self = this;
120         if (this.groups) {
121             $(this.groups).unbind("selected deleted action row_link");
122             delete this.groups;
123         }
124
125         this.groups = groups;
126         $(this.groups).bind({
127             'selected': function (e, ids, records) {
128                 self.do_select(ids, records);
129             },
130             'deleted': function (e, ids) {
131                 self.do_delete(ids);
132             },
133             'action': function (e, action_name, id, callback) {
134                 self.do_button_action(action_name, id, callback);
135             },
136             'row_link': function (e, id, dataset, view) {
137                 self.do_activate_record(dataset.index, id, dataset, view);
138             }
139         });
140     },
141     /**
142      * View startup method, the default behavior is to set the ``oe_list``
143      * class on its root element and to perform an RPC load call.
144      *
145      * @returns {$.Deferred} loading promise
146      */
147     start: function() {
148         this.$el.addClass('oe_list');
149         return this.reload_view(null, null, true);
150     },
151     /**
152      * Returns the style for the provided record in the current view (from the
153      * ``@colors`` and ``@fonts`` attributes)
154      *
155      * @param {Record} record record for the current row
156      * @returns {String} CSS style declaration
157      */
158     style_for: function (record) {
159         var style= '';
160
161         var context = _.extend({}, record.attributes, {
162             uid: this.session.uid,
163             current_date: new Date().toString('yyyy-MM-dd')
164             // TODO: time, datetime, relativedelta
165         });
166
167         if (this.fonts) {
168             for(var i=0, len=this.fonts.length; i<len; ++i) {
169                 var pair = this.fonts[i],
170                 font = pair[0],
171                 expression = pair[1];
172                 if (py.evaluate(expression, context).toJSON()) {
173                     switch(font) {
174                     case 'bold':
175                         style += 'font-weight: bold;';
176                         break;
177                     case 'italic':
178                         style += 'font-style: italic;';
179                         break;
180                     case 'underline':
181                         style += 'text-decoration: underline;';
182                         break;
183                     }
184                 }
185             }
186         }
187
188         if (!this.colors) { return style; }
189         for(var i=0, len=this.colors.length; i<len; ++i) {
190             var pair = this.colors[i],
191                 color = pair[0],
192                 expression = pair[1];
193             if (py.evaluate(expression, context).toJSON()) {
194                 return style += 'color: ' + color + ';';
195             }
196             // TODO: handle evaluation errors
197         }
198         return style;
199     },
200     /**
201      * Called after loading the list view's description, sets up such things
202      * as the view table's columns, renders the table itself and hooks up the
203      * various table-level and row-level DOM events (action buttons, deletion
204      * buttons, selection of records, [New] button, selection of a given
205      * record, ...)
206      *
207      * Sets up the following:
208      *
209      * * Processes arch and fields to generate a complete field descriptor for each field
210      * * Create the table itself and allocate visible columns
211      * * Hook in the top-level (header) [New|Add] and [Delete] button
212      * * Sets up showing/hiding the top-level [Delete] button based on records being selected or not
213      * * Sets up event handlers for action buttons and per-row deletion button
214      * * Hooks global callback for clicking on a row
215      * * Sets up its sidebar, if any
216      *
217      * @param {Object} data wrapped fields_view_get result
218      * @param {Object} data.fields_view fields_view_get result (processed)
219      * @param {Object} data.fields_view.fields mapping of fields for the current model
220      * @param {Object} data.fields_view.arch current list view descriptor
221      * @param {Boolean} grouped Is the list view grouped
222      */
223     on_loaded: function(data, grouped) {
224         var self = this;
225         this.fields_view = data;
226         this.name = "" + this.fields_view.arch.attrs.string;
227
228         if (this.fields_view.arch.attrs.colors) {
229             this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
230                 .compact()
231                 .map(function(color_pair) {
232                     var pair = color_pair.split(':'),
233                         color = pair[0],
234                         expr = pair[1];
235                     return [color, py.parse(py.tokenize(expr)), expr];
236                 }).value();
237         }
238
239         if (this.fields_view.arch.attrs.fonts) {
240             this.fonts = _(this.fields_view.arch.attrs.fonts.split(';')).chain().compact()
241                 .map(function(font_pair) {
242                     var pair = font_pair.split(':'),
243                         font = pair[0],
244                         expr = pair[1];
245                     return [font, py.parse(py.tokenize(expr)), expr];
246                 }).value();
247         }
248
249         this.setup_columns(this.fields_view.fields, grouped);
250
251         this.$el.html(QWeb.render(this._template, this));
252         this.$el.addClass(this.fields_view.arch.attrs['class']);
253         // Head hook
254         // Selecting records
255         this.$el.find('.oe_list_record_selector').click(function(){
256             self.$el.find('.oe_list_record_selector input').prop('checked',
257                 self.$el.find('.oe_list_record_selector').prop('checked')  || false);
258             var selection = self.groups.get_selection();
259             $(self.groups).trigger(
260                 'selected', [selection.ids, selection.records]);
261         });
262
263         // Sorting columns
264         this.$el.find('thead').delegate('th.oe_sortable[data-id]', 'click', function (e) {
265             e.stopPropagation();
266             var $this = $(this);
267             self.dataset.sort($this.data('id'));
268             if($this.hasClass("sortdown") || $this.hasClass("sortup"))  {
269                 $this.toggleClass("sortdown").toggleClass("sortup");
270             } else {
271                 $this.toggleClass("sortdown");
272             }
273             $this.siblings('.oe_sortable').removeClass("sortup sortdown");
274
275             self.reload_content();
276         });
277
278         // Add button and Import link
279         if (!this.$buttons) {
280             this.$buttons = $(QWeb.render("ListView.buttons", {'widget':self}));
281             if (this.options.$buttons) {
282                 this.$buttons.appendTo(this.options.$buttons);
283             } else {
284                 this.$el.find('.oe_list_buttons').replaceWith(this.$buttons);
285             }
286             this.$buttons.find('.oe_list_add')
287                     .click(this.proxy('do_add_record'))
288                     .prop('disabled', grouped);
289             this.$buttons.on('click', '.oe_list_button_import', function() {
290                 self.on_sidebar_import();
291                 return false;
292             });
293         }
294
295         // Pager
296         if (!this.$pager) {
297             this.$pager = $(QWeb.render("ListView.pager", {'widget':self}));
298             if (this.options.$buttons) {
299                 this.$pager.appendTo(this.options.$pager);
300             } else {
301                 this.$el.find('.oe_list_pager').replaceWith(this.$pager);
302             }
303
304             this.$pager
305                 .on('click', 'a[data-pager-action]', function () {
306                     var $this = $(this);
307                     var max_page = Math.floor(self.dataset.size() / self.limit());
308                     switch ($this.data('pager-action')) {
309                         case 'first':
310                             self.page = 0; break;
311                         case 'last':
312                             self.page = max_page - 1;
313                             break;
314                         case 'next':
315                             self.page += 1; break;
316                         case 'previous':
317                             self.page -= 1; break;
318                     }
319                     if (self.page < 0) {
320                         self.page = max_page;
321                     } else if (self.page > max_page) {
322                         self.page = 0;
323                     }
324                     self.reload_content();
325                 }).find('.oe_list_pager_state')
326                     .click(function (e) {
327                         e.stopPropagation();
328                         var $this = $(this);
329
330                         var $select = $('<select>')
331                             .appendTo($this.empty())
332                             .click(function (e) {e.stopPropagation();})
333                             .append('<option value="80">80</option>' +
334                                     '<option value="100">100</option>' +
335                                     '<option value="200">200</option>' +
336                                     '<option value="500">500</option>' +
337                                     '<option value="NaN">' + _t("Unlimited") + '</option>')
338                             .change(function () {
339                                 var val = parseInt($select.val(), 10);
340                                 self._limit = (isNaN(val) ? null : val);
341                                 self.page = 0;
342                                 self.reload_content();
343                             }).blur(function() {
344                                 $(this).trigger('change');
345                             })
346                             .val(self._limit || 'NaN');
347                     });
348         }
349
350         // Sidebar
351         if (!this.sidebar && this.options.$sidebar) {
352             this.sidebar = new instance.web.Sidebar(this);
353             this.sidebar.appendTo(this.options.$sidebar);
354             this.sidebar.add_items('other', [
355                 { label: _t("Import"), callback: this.on_sidebar_import },
356                 { label: _t("Export"), callback: this.on_sidebar_export },
357                 { label: _t('Delete'), callback: this.do_delete_selected }
358             ]);
359             this.sidebar.add_toolbar(this.fields_view.toolbar);
360             this.sidebar.$el.hide();
361         }
362     },
363     /**
364      * Configures the ListView pager based on the provided dataset's information
365      *
366      * Horrifying side-effect: sets the dataset's data on this.dataset?
367      *
368      * @param {instance.web.DataSet} dataset
369      */
370     configure_pager: function (dataset) {
371         this.dataset.ids = dataset.ids;
372         // Not exactly clean
373         if (dataset._length) {
374             this.dataset._length = dataset._length;
375         }
376
377         var total = dataset.size();
378         var limit = this.limit() || total;
379         this.$pager.toggle(total !== 0);
380         this.$pager.toggleClass('oe_list_pager_single_page', (total <= limit));
381         var spager = '-';
382         if (total) {
383             var range_start = this.page * limit + 1;
384             var range_stop = range_start - 1 + limit;
385             if (range_stop > total) {
386                 range_stop = total;
387             }
388             spager = _.str.sprintf('%d-%d of %d', range_start, range_stop, total);
389         }
390
391         this.$pager.find('.oe_list_pager_state').text(spager);
392     },
393     /**
394      * Sets up the listview's columns: merges view and fields data, move
395      * grouped-by columns to the front of the columns list and make them all
396      * visible.
397      *
398      * @param {Object} fields fields_view_get's fields section
399      * @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
400      */
401     setup_columns: function (fields, grouped) {
402         var registry = instance.web.list.columns;
403         this.columns.splice(0, this.columns.length);
404         this.columns.push.apply(this.columns,
405             _(this.fields_view.arch.children).map(function (field) {
406                 var id = field.attrs.name;
407                 return registry.for_(id, fields[id], field);
408         }));
409         if (grouped) {
410             this.columns.unshift(
411                 new instance.web.list.MetaColumn('_group', _t("Group")));
412         }
413
414         this.visible_columns = _.filter(this.columns, function (column) {
415             return column.invisible !== '1';
416         });
417
418         this.aggregate_columns = _(this.visible_columns).invoke('to_aggregate');
419     },
420     /**
421      * Used to handle a click on a table row, if no other handler caught the
422      * event.
423      *
424      * The default implementation asks the list view's view manager to switch
425      * to a different view (by calling
426      * :js:func:`~instance.web.ViewManager.on_mode_switch`), using the
427      * provided record index (within the current list view's dataset).
428      *
429      * If the index is null, ``switch_to_record`` asks for the creation of a
430      * new record.
431      *
432      * @param {Number|void} index the record index (in the current dataset) to switch to
433      * @param {String} [view="page"] the view type to switch to
434      */
435     select_record:function (index, view) {
436         view = view || index == null ? 'form' : 'form';
437         this.dataset.index = index;
438         _.delay(_.bind(function () {
439             this.do_switch_view(view);
440         }, this));
441     },
442     do_show: function () {
443         this._super();
444         if (this.$buttons) {
445             this.$buttons.show();
446         }
447         if (this.$pager) {
448             this.$pager.show();
449         }
450     },
451     do_hide: function () {
452         if (this.sidebar) {
453             this.sidebar.$el.hide();
454         }
455         if (this.$buttons) {
456             this.$buttons.hide();
457         }
458         if (this.$pager) {
459             this.$pager.hide();
460         }
461         this._super();
462     },
463     /**
464      * Reloads the list view based on the current settings (dataset & al)
465      *
466      * @param {Boolean} [grouped] Should the list be displayed grouped
467      * @param {Object} [context] context to send the server while loading the view
468      */
469     reload_view: function (grouped, context, initial) {
470         var self = this;
471         var callback = function (field_view_get) {
472             self.on_loaded(field_view_get, grouped);
473         };
474         if (this.embedded_view) {
475             return $.Deferred().then(callback).resolve(this.embedded_view);
476         } else {
477             return this.rpc('/web/listview/load', {
478                 model: this.model,
479                 view_id: this.view_id,
480                 view_type: "tree",
481                 context: this.dataset.get_context(context),
482                 toolbar: !!this.options.$sidebar
483             }, callback);
484         }
485     },
486     /**
487      * re-renders the content of the list view
488      *
489      * @returns {$.Deferred} promise to content reloading
490      */
491     reload_content: function () {
492         var self = this;
493         self.$el.find('.oe_list_record_selector').prop('checked', false);
494         this.records.reset();
495         var reloaded = $.Deferred();
496         this.$el.find('.oe_list_content').append(
497             this.groups.render(function () {
498                 if (self.dataset.index == null) {
499                     var has_one = false;
500                     self.records.each(function () { has_one = true; });
501                     if (has_one) {
502                         self.dataset.index = 0;
503                     }
504                 }
505                 self.compute_aggregates();
506                 reloaded.resolve();
507             }));
508         this.do_push_state({
509             page: this.page,
510             limit: this._limit
511         });
512         return reloaded.promise();
513     },
514     reload: function () {
515         return this.reload_content();
516     },
517     reload_record: function (record) {
518         return this.dataset.read_ids(
519             [record.get('id')],
520             _.pluck(_(this.columns).filter(function (r) {
521                     return r.tag === 'field';
522                 }), 'name')
523         ).then(function (records) {
524             _(records[0]).each(function (value, key) {
525                 record.set(key, value, {silent: true});
526             });
527             record.trigger('change', record);
528         });
529     },
530
531     do_load_state: function(state, warm) {
532         var reload = false;
533         if (state.page && this.page !== state.page) {
534             this.page = state.page;
535             reload = true;
536         }
537         if (state.limit) {
538             if (_.isString(state.limit)) {
539                 state.limit = null;
540             }
541             if (state.limit !== this._limit) {
542                 this._limit = state.limit;
543                 reload = true;
544             }
545         }
546         if (reload) {
547             this.reload_content();
548         }
549     },
550     /**
551      * Handler for the result of eval_domain_and_context, actually perform the
552      * searching
553      *
554      * @param {Object} results results of evaluating domain and process for a search
555      */
556     do_search: function (domain, context, group_by) {
557         this.page = 0;
558         this.groups.datagroup = new instance.web.DataGroup(
559             this, this.model, domain, context, group_by);
560         this.groups.datagroup.sort = this.dataset._sort;
561
562         if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
563             group_by = null;
564         }
565         this.no_leaf = !!context['group_by_no_leaf'];
566
567         this.reload_view(!!group_by, context).then(
568             this.proxy('reload_content'));
569     },
570     /**
571      * Handles the signal to delete lines from the records list
572      *
573      * @param {Array} ids the ids of the records to delete
574      */
575     do_delete: function (ids) {
576         if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
577             return;
578         }
579         var self = this;
580         return $.when(this.dataset.unlink(ids)).then(function () {
581             _(ids).each(function (id) {
582                 self.records.remove(self.records.get(id));
583             });
584             self.configure_pager(self.dataset);
585             self.compute_aggregates();
586         });
587     },
588     /**
589      * Handles the signal indicating that a new record has been selected
590      *
591      * @param {Array} ids selected record ids
592      * @param {Array} records selected record values
593      */
594     do_select: function (ids, records) {
595         if (!ids.length) {
596             this.dataset.index = 0;
597             if (this.sidebar) {
598                 this.sidebar.$el.hide();
599             }
600             this.compute_aggregates();
601             return;
602         }
603
604         this.dataset.index = _(this.dataset.ids).indexOf(ids[0]);
605         if (this.sidebar) {
606             this.sidebar.$el.show();
607         }
608
609         this.compute_aggregates(_(records).map(function (record) {
610             return {count: 1, values: record};
611         }));
612     },
613     /**
614      * Handles action button signals on a record
615      *
616      * @param {String} name action name
617      * @param {Object} id id of the record the action should be called on
618      * @param {Function} callback should be called after the action is executed, if non-null
619      */
620     do_button_action: function (name, id, callback) {
621         this.handle_button(name, id, callback);
622     },
623     /**
624      * Base handling of buttons, can be called when overriding do_button_action
625      * in order to bypass parent overrides.
626      *
627      * The callback will be provided with the ``id`` as its parameter, in case
628      * handle_button's caller had to alter the ``id`` (or even create one)
629      * while not being ``callback``'s creator.
630      *
631      * This method should not be overridden.
632      *
633      * @param {String} name action name
634      * @param {Object} id id of the record the action should be called on
635      * @param {Function} callback should be called after the action is executed, if non-null
636      */
637     handle_button: function (name, id, callback) {
638         var action = _.detect(this.columns, function (field) {
639             return field.name === name;
640         });
641         if (!action) { return; }
642         if ('confirm' in action && !window.confirm(action.confirm)) {
643             return;
644         }
645
646         var c = new instance.web.CompoundContext();
647         c.set_eval_context(_.extend({
648             active_id: id,
649             active_ids: [id],
650             active_model: this.dataset.model
651         }, this.records.get(id).toContext()));
652         if (action.context) {
653             c.add(action.context);
654         }
655         action.context = c;
656         this.do_execute_action(
657             action, this.dataset, id, _.bind(callback, null, id));
658     },
659     /**
660      * Handles the activation of a record (clicking on it)
661      *
662      * @param {Number} index index of the record in the dataset
663      * @param {Object} id identifier of the activated record
664      * @param {instance.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
665      */
666     do_activate_record: function (index, id, dataset, view) {
667         this.dataset.ids = dataset.ids;
668         this.select_record(index, view);
669     },
670     /**
671      * Handles signal for the addition of a new record (can be a creation,
672      * can be the addition from a remote source, ...)
673      *
674      * The default implementation is to switch to a new record on the form view
675      */
676     do_add_record: function () {
677         this.select_record(null);
678     },
679     /**
680      * Handles deletion of all selected lines
681      */
682     do_delete_selected: function () {
683         var ids = this.groups.get_selection().ids;
684         if (ids.length) {
685             this.do_delete(this.groups.get_selection().ids);
686         } else {
687             this.do_warn(_t("Warning"), _t("You must select at least one record."));
688         }
689     },
690     /**
691      * Computes the aggregates for the current list view, either on the
692      * records provided or on the records of the internal
693      * :js:class:`~instance.web.ListView.Group`, by calling
694      * :js:func:`~instance.web.ListView.group.get_records`.
695      *
696      * Then displays the aggregates in the table through
697      * :js:method:`~instance.web.ListView.display_aggregates`.
698      *
699      * @param {Array} [records]
700      */
701     compute_aggregates: function (records) {
702         var columns = _(this.aggregate_columns).filter(function (column) {
703             return column['function']; });
704         if (_.isEmpty(columns)) { return; }
705
706         if (_.isEmpty(records)) {
707             records = this.groups.get_records();
708         }
709         records = _(records).compact();
710
711         var count = 0, sums = {};
712         _(columns).each(function (column) {
713             switch (column['function']) {
714                 case 'max':
715                     sums[column.id] = -Infinity;
716                     break;
717                 case 'min':
718                     sums[column.id] = Infinity;
719                     break;
720                 default:
721                     sums[column.id] = 0;
722             }
723         });
724         _(records).each(function (record) {
725             count += record.count || 1;
726             _(columns).each(function (column) {
727                 var field = column.id,
728                     value = record.values[field];
729                 switch (column['function']) {
730                     case 'sum':
731                         sums[field] += value;
732                         break;
733                     case 'avg':
734                         sums[field] += record.count * value;
735                         break;
736                     case 'min':
737                         if (sums[field] > value) {
738                             sums[field] = value;
739                         }
740                         break;
741                     case 'max':
742                         if (sums[field] < value) {
743                             sums[field] = value;
744                         }
745                         break;
746                 }
747             });
748         });
749
750         var aggregates = {};
751         _(columns).each(function (column) {
752             var field = column.id;
753             switch (column['function']) {
754                 case 'avg':
755                     aggregates[field] = {value: sums[field] / count};
756                     break;
757                 default:
758                     aggregates[field] = {value: sums[field]};
759             }
760         });
761
762         this.display_aggregates(aggregates);
763     },
764     display_aggregates: function (aggregation) {
765         var self = this;
766         var $footer_cells = this.$el.find('.oe_list_footer');
767         _(this.aggregate_columns).each(function (column) {
768             if (!column['function']) {
769                 return;
770             }
771
772             $footer_cells.filter(_.str.sprintf('[data-field=%s]', column.id))
773                 .html(column.format(aggregation, { process_modifiers: false }));
774         });
775     },
776     get_selected_ids: function() {
777         var ids = this.groups.get_selection().ids;
778         return ids;
779     },
780     /**
781      * Adds padding columns at the start or end of all table rows (including
782      * field names row)
783      *
784      * @param {Number} count number of columns to add
785      * @param {Object} options
786      * @param {"before"|"after"} [options.position="after"] insertion position for the new columns
787      * @param {Object} [options.except] content row to not pad
788      */
789     pad_columns: function (count, options) {
790         options = options || {};
791         // padding for action/pager header
792         var $first_header = this.$el.find('thead tr:first th');
793         var colspan = $first_header.attr('colspan');
794         if (colspan) {
795             if (!this.previous_colspan) {
796                 this.previous_colspan = colspan;
797             }
798             $first_header.attr('colspan', parseInt(colspan, 10) + count);
799         }
800         // Padding for column titles, footer and data rows
801         var $rows = this.$el
802                 .find('.oe_list_header_columns, tr:not(thead tr)')
803                 .not(options['except']);
804         var newcols = new Array(count+1).join('<td class="oe_list_padding"></td>');
805         if (options.position === 'before') {
806             $rows.prepend(newcols);
807         } else {
808             $rows.append(newcols);
809         }
810     },
811     /**
812      * Removes all padding columns of the table
813      */
814     unpad_columns: function () {
815         this.$el.find('.oe_list_padding').remove();
816         if (this.previous_colspan) {
817             this.$el
818                     .find('thead tr:first th')
819                     .attr('colspan', this.previous_colspan);
820             this.previous_colspan = null;
821         }
822     },
823     no_result: function () {
824         this.$el.find('.oe_view_nocontent').remove();
825         if (this.groups.group_by
826             || !this.options.action
827             || !this.options.action.help) {
828             return;
829         }
830         this.$el.find('table:first').hide();
831         this.$el.prepend(
832             $('<div class="oe_view_nocontent">').html(this.options.action.help)
833         );
834     }
835 });
836 instance.web.ListView.List = instance.web.Class.extend( /** @lends instance.web.ListView.List# */{
837     /**
838      * List display for the ListView, handles basic DOM events and transforms
839      * them in the relevant higher-level events, to which the list view (or
840      * other consumers) can subscribe.
841      *
842      * Events on this object are registered via jQuery.
843      *
844      * Available events:
845      *
846      * `selected`
847      *   Triggered when a row is selected (using check boxes), provides an
848      *   array of ids of all the selected records.
849      * `deleted`
850      *   Triggered when deletion buttons are hit, provide an array of ids of
851      *   all the records being marked for suppression.
852      * `action`
853      *   Triggered when an action button is clicked, provides two parameters:
854      *
855      *   * The name of the action to execute (as a string)
856      *   * The id of the record to execute the action on
857      * `row_link`
858      *   Triggered when a row of the table is clicked, provides the index (in
859      *   the rows array) and id of the selected record to the handle function.
860      *
861      * @constructs instance.web.ListView.List
862      * @extends instance.web.Class
863      * 
864      * @param {Object} opts display options, identical to those of :js:class:`instance.web.ListView`
865      */
866     init: function (group, opts) {
867         var self = this;
868         this.group = group;
869         this.view = group.view;
870         this.session = this.view.session;
871
872         this.options = opts.options;
873         this.columns = opts.columns;
874         this.dataset = opts.dataset;
875         this.records = opts.records;
876
877         this.record_callbacks = {
878             'remove': function (event, record) {
879                 var $row = self.$current.children(
880                     '[data-id=' + record.get('id') + ']');
881                 var index = $row.data('index');
882                 $row.remove();
883             },
884             'reset': function () { return self.on_records_reset(); },
885             'change': function (event, record, attribute, value, old_value) {
886                 var $row;
887                 if (attribute === 'id') {
888                     if (old_value) {
889                         throw new Error("Setting 'id' attribute on existing record "
890                             + JSON.stringify(record.attributes));
891                     }
892                     if (!_.contains(self.dataset.ids, value)) {
893                         // add record to dataset if not already in (added by
894                         // the form view?)
895                         self.dataset.ids.splice(
896                             self.records.indexOf(record), 0, value);
897                     }
898                     // Set id on new record
899                     $row = self.$current.children('[data-id=false]');
900                 } else {
901                     $row = self.$current.children(
902                         '[data-id=' + record.get('id') + ']');
903                 }
904                 $row.replaceWith(self.render_record(record));
905             },
906             'add': function (ev, records, record, index) {
907                 var $new_row = $(self.render_record(record));
908
909                 if (index === 0) {
910                     $new_row.prependTo(self.$current);
911                 } else {
912                     var previous_record = records.at(index-1),
913                         $previous_sibling = self.$current.children(
914                                 '[data-id=' + previous_record.get('id') + ']');
915                     $new_row.insertAfter($previous_sibling);
916                 }
917             }
918         };
919         _(this.record_callbacks).each(function (callback, event) {
920             this.records.bind(event, callback);
921         }, this);
922
923         this.$_element = $('<tbody>')
924             .appendTo(document.body)
925             .delegate('th.oe_list_record_selector', 'click', function (e) {
926                 e.stopPropagation();
927                 var selection = self.get_selection();
928                 $(self).trigger(
929                         'selected', [selection.ids, selection.records]);
930             })
931             .delegate('td.oe_list_record_delete button', 'click', function (e) {
932                 e.stopPropagation();
933                 var $row = $(e.target).closest('tr');
934                 $(self).trigger('deleted', [[self.row_id($row)]]);
935             })
936             .delegate('td.oe_list_field_cell button', 'click', function (e) {
937                 e.stopPropagation();
938                 var $target = $(e.currentTarget),
939                       field = $target.closest('td').data('field'),
940                        $row = $target.closest('tr'),
941                   record_id = self.row_id($row);
942
943                 // note: $.data converts data to number if it's composed only
944                 // of digits, nice when storing actual numbers, not nice when
945                 // storing strings composed only of digits. Force the action
946                 // name to be a string
947                 $(self).trigger('action', [field.toString(), record_id, function (id) {
948                     return self.reload_record(self.records.get(id));
949                 }]);
950             })
951             .delegate('a', 'click', function (e) {
952                 e.stopPropagation();
953             })
954             .delegate('tr', 'click', function (e) {
955                 var row_id = self.row_id(e.currentTarget);
956                 if (row_id) {
957                     e.stopPropagation();
958                     if (!self.dataset.select_id(row_id)) {
959                         throw new Error("Could not find id in dataset");
960                     }
961                     self.row_clicked(e);
962                 }
963             });
964     },
965     row_clicked: function (e, view) {
966         $(this).trigger(
967             'row_link',
968             [this.dataset.ids[this.dataset.index],
969              this.dataset, view]);
970     },
971     render_cell: function (record, column) {
972         var value;
973         if(column.type === 'reference') {
974             value = record.get(column.id);
975             var ref_match;
976             // Ensure that value is in a reference "shape", otherwise we're
977             // going to loop on performing name_get after we've resolved (and
978             // set) a human-readable version. m2o does not have this issue
979             // because the non-human-readable is just a number, where the
980             // human-readable version is a pair
981             if (value && (ref_match = /([\w\.]+),(\d+)/.exec(value))) {
982                 // reference values are in the shape "$model,$id" (as a
983                 // string), we need to split and name_get this pair in order
984                 // to get a correctly displayable value in the field
985                 var model = ref_match[1],
986                     id = parseInt(ref_match[2], 10);
987                 new instance.web.DataSet(this.view, model).name_get([id], function(names) {
988                     if (!names.length) { return; }
989                     record.set(column.id, names[0][1]);
990                 });
991             }
992         } else if (column.type === 'many2one') {
993             value = record.get(column.id);
994             // m2o values are usually name_get formatted, [Number, String]
995             // pairs, but in some cases only the id is provided. In these
996             // cases, we need to perform a name_get call to fetch the actual
997             // displayable value
998             if (typeof value === 'number' || value instanceof Number) {
999                 // fetch the name, set it on the record (in the right field)
1000                 // and let the various registered events handle refreshing the
1001                 // row
1002                 new instance.web.DataSet(this.view, column.relation)
1003                         .name_get([value], function (names) {
1004                     if (!names.length) { return; }
1005                     record.set(column.id, names[0]);
1006                 });
1007             }
1008         }
1009         return column.format(record.toForm().data, {
1010             model: this.dataset.model,
1011             id: record.get('id')
1012         });
1013     },
1014     render: function () {
1015         var self = this;
1016         if (this.$current) {
1017             this.$current.remove();
1018         }
1019         this.$current = this.$_element.clone(true);
1020         this.$current.empty().append(
1021             QWeb.render('ListView.rows', _.extend({
1022                     render_cell: function () {
1023                         return self.render_cell.apply(self, arguments); }
1024                 }, this)));
1025         this.pad_table_to(4);
1026     },
1027     pad_table_to: function (count) {
1028         if (this.records.length >= count ||
1029                 _(this.columns).any(function(column) { return column.meta; })) {
1030             return;
1031         }
1032         var cells = [];
1033         if (this.options.selectable) {
1034             cells.push('<th class="oe_list_record_selector"></td>');
1035         }
1036         _(this.columns).each(function(column) {
1037             if (column.invisible === '1') {
1038                 return;
1039             }
1040             if (column.tag === 'button') {
1041                 cells.push('<td class="oe_button" title="' + column.string + '">&nbsp;</td>');
1042             } else {
1043                 cells.push('<td title="' + column.string + '">&nbsp;</td>');
1044             }
1045         });
1046         if (this.options.deletable) {
1047             cells.push('<td class="oe_list_record_delete"><button type="button" style="visibility: hidden"> </button></td>');
1048         }
1049         cells.unshift('<tr>');
1050         cells.push('</tr>');
1051
1052         var row = cells.join('');
1053         this.$current
1054             .children('tr:not([data-id])').remove().end()
1055             .append(new Array(count - this.records.length + 1).join(row));
1056     },
1057     /**
1058      * Gets the ids of all currently selected records, if any
1059      * @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
1060      */
1061     get_selection: function () {
1062         var result = {ids: [], records: []};
1063         if (!this.options.selectable) {
1064             return result;
1065         }
1066         var records = this.records;
1067         this.$current.find('th.oe_list_record_selector input:checked')
1068                 .closest('tr').each(function () {
1069             var record = records.get($(this).data('id'));
1070             result.ids.push(record.get('id'));
1071             result.records.push(record.attributes);
1072         });
1073         return result;
1074     },
1075     /**
1076      * Returns the identifier of the object displayed in the provided table
1077      * row
1078      *
1079      * @param {Object} row the selected table row
1080      * @returns {Number|String} the identifier of the row's object
1081      */
1082     row_id: function (row) {
1083         return $(row).data('id');
1084     },
1085     /**
1086      * Death signal, cleans up list display
1087      */
1088     on_records_reset: function () {
1089         _(this.record_callbacks).each(function (callback, event) {
1090             this.records.unbind(event, callback);
1091         }, this);
1092         if (!this.$current) { return; }
1093         this.$current.remove();
1094         this.$current = null;
1095         this.$_element.remove();
1096     },
1097     get_records: function () {
1098         return this.records.map(function (record) {
1099             return {count: 1, values: record.attributes};
1100         });
1101     },
1102     /**
1103      * Reloads the provided record by re-reading its content from the server.
1104      *
1105      * @param {Record} record
1106      * @returns {$.Deferred} promise to the finalization of the reloading
1107      */
1108     reload_record: function (record) {
1109         return this.view.reload_record(record);
1110     },
1111     /**
1112      * Renders a list record to HTML
1113      *
1114      * @param {Record} record index of the record to render in ``this.rows``
1115      * @returns {String} QWeb rendering of the selected record
1116      */
1117     render_record: function (record) {
1118         var self = this;
1119         var index = this.records.indexOf(record);
1120         return QWeb.render('ListView.row', {
1121             columns: this.columns,
1122             options: this.options,
1123             record: record,
1124             row_parity: (index % 2 === 0) ? 'even' : 'odd',
1125             view: this.view,
1126             render_cell: function () {
1127                 return self.render_cell.apply(self, arguments); }
1128         });
1129     }
1130 });
1131 instance.web.ListView.Groups = instance.web.Class.extend( /** @lends instance.web.ListView.Groups# */{
1132     passtrough_events: 'action deleted row_link',
1133     /**
1134      * Grouped display for the ListView. Handles basic DOM events and interacts
1135      * with the :js:class:`~instance.web.DataGroup` bound to it.
1136      *
1137      * Provides events similar to those of
1138      * :js:class:`~instance.web.ListView.List`
1139      *
1140      * @constructs instance.web.ListView.Groups
1141      * @extends instance.web.Class
1142      *
1143      * @param {instance.web.ListView} view
1144      * @param {Object} [options]
1145      * @param {Collection} [options.records]
1146      * @param {Object} [options.options]
1147      * @param {Array} [options.columns]
1148      */
1149     init: function (view, options) {
1150         options = options || {};
1151         this.view = view;
1152         this.records = options.records || view.records;
1153         this.options = options.options || view.options;
1154         this.columns = options.columns || view.columns;
1155         this.datagroup = null;
1156
1157         this.$row = null;
1158         this.children = {};
1159
1160         this.page = 0;
1161
1162         var self = this;
1163         this.records.bind('reset', function () {
1164             return self.on_records_reset(); });
1165     },
1166     make_fragment: function () {
1167         return document.createDocumentFragment();
1168     },
1169     /**
1170      * Returns a DOM node after which a new tbody can be inserted, so that it
1171      * follows the provided row.
1172      *
1173      * Necessary to insert the result of a new group or list view within an
1174      * existing groups render, without losing track of the groups's own
1175      * elements
1176      *
1177      * @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
1178      * @returns {HTMLTableSectionElement} element after which a tbody can be inserted
1179      */
1180     point_insertion: function (row) {
1181         var $row = $(row);
1182         var red_letter_tboday = $row.closest('tbody')[0];
1183
1184         var $next_siblings = $row.nextAll();
1185         if ($next_siblings.length) {
1186             var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
1187
1188             $root_kanal.append($next_siblings);
1189             this.elements.splice(
1190                 _.indexOf(this.elements, red_letter_tboday),
1191                 0,
1192                 $root_kanal[0]);
1193         }
1194         return red_letter_tboday;
1195     },
1196     make_paginator: function () {
1197         var self = this;
1198         var $prev = $('<button type="button" data-pager-action="previous">&lt;</button>')
1199             .click(function (e) {
1200                 e.stopPropagation();
1201                 self.page -= 1;
1202
1203                 self.$row.closest('tbody').next()
1204                     .replaceWith(self.render());
1205             });
1206         var $next = $('<button type="button" data-pager-action="next">&gt;</button>')
1207             .click(function (e) {
1208                 e.stopPropagation();
1209                 self.page += 1;
1210
1211                 self.$row.closest('tbody').next()
1212                     .replaceWith(self.render());
1213             });
1214         this.$row.children().last()
1215             .append($prev)
1216             .append('<span class="oe_list_pager_state"></span>')
1217             .append($next);
1218     },
1219     open: function (point_insertion) {
1220         this.render().insertAfter(point_insertion);
1221
1222         var no_subgroups = _(this.datagroup.group_by).isEmpty(),
1223             records_terminated = !this.datagroup.context['group_by_no_leaf'];
1224         if (no_subgroups && records_terminated) {
1225             this.make_paginator();
1226         }
1227     },
1228     close: function () {
1229         this.$row.children().last().empty();
1230         this.records.reset();
1231     },
1232     /**
1233      * Prefixes ``$node`` with floated spaces in order to indent it relative
1234      * to its own left margin/baseline
1235      *
1236      * @param {jQuery} $node jQuery object to indent
1237      * @param {Number} level current nesting level, >= 1
1238      * @returns {jQuery} the indentation node created
1239      */
1240     indent: function ($node, level) {
1241         return $('<span>')
1242                 .css({'float': 'left', 'white-space': 'pre'})
1243                 .text(new Array(level).join('   '))
1244                 .prependTo($node);
1245     },
1246     render_groups: function (datagroups) {
1247         var self = this;
1248         var placeholder = this.make_fragment();
1249         _(datagroups).each(function (group) {
1250             if (self.children[group.value]) {
1251                 self.records.proxy(group.value).reset();
1252                 delete self.children[group.value];
1253             }
1254             var child = self.children[group.value] = new (self.view.options.GroupsType)(self.view, {
1255                 records: self.records.proxy(group.value),
1256                 options: self.options,
1257                 columns: self.columns
1258             });
1259             self.bind_child_events(child);
1260             child.datagroup = group;
1261
1262             var $row = child.$row = $('<tr>');
1263             if (group.openable && group.length) {
1264                 $row.click(function (e) {
1265                     if (!$row.data('open')) {
1266                         $row.data('open', true)
1267                             .find('span.ui-icon')
1268                                 .removeClass('ui-icon-triangle-1-e')
1269                                 .addClass('ui-icon-triangle-1-s');
1270                         child.open(self.point_insertion(e.currentTarget));
1271                     } else {
1272                         $row.removeData('open')
1273                             .find('span.ui-icon')
1274                                 .removeClass('ui-icon-triangle-1-s')
1275                                 .addClass('ui-icon-triangle-1-e');
1276                         child.close();
1277                     }
1278                 });
1279             }
1280             placeholder.appendChild($row[0]);
1281
1282             var $group_column = $('<th class="oe_list_group_name">').appendTo($row);
1283             // Don't fill this if group_by_no_leaf but no group_by
1284             if (group.grouped_on) {
1285                 var row_data = {};
1286                 row_data[group.grouped_on] = group;
1287                 var group_column = _(self.columns).detect(function (column) {
1288                     return column.id === group.grouped_on; });
1289                 if (! group_column) {
1290                     throw new Error(_.str.sprintf(
1291                         _t("Grouping on field '%s' is not possible because that field does not appear in the list view."),
1292                         group.grouped_on));
1293                 }
1294                 var group_label;
1295                 try {
1296                     group_label = group_column.format(row_data, {
1297                         value_if_empty: _t("Undefined"),
1298                         process_modifiers: false
1299                     });
1300                 } catch (e) {
1301                     group_label = row_data[group_column.id].value;
1302                 }
1303                 $group_column.text(_.str.sprintf("%s (%d)",
1304                     group_label, group.length));
1305
1306                 if (group.length && group.openable) {
1307                     // Make openable if not terminal group & group_by_no_leaf
1308                     $group_column.prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
1309                 } else {
1310                     // Kinda-ugly hack: jquery-ui has no "empty" icon, so set
1311                     // wonky background position to ensure nothing is displayed
1312                     // there but the rest of the behavior is ui-icon's
1313                     $group_column.prepend('<span class="ui-icon" style="float: left; background-position: 150px 150px">');
1314                 }
1315             }
1316             self.indent($group_column, group.level);
1317
1318             if (self.options.selectable) {
1319                 $row.append('<td>');
1320             }
1321             _(self.columns).chain()
1322                 .filter(function (column) { return column.invisible !== '1'; })
1323                 .each(function (column) {
1324                     if (column.meta) {
1325                         // do not do anything
1326                     } else if (column.id in group.aggregates) {
1327                         var r = {};
1328                         r[column.id] = {value: group.aggregates[column.id]};
1329                         $('<td class="oe_number">')
1330                             .html(column.format(r, {process_modifiers: false}))
1331                             .appendTo($row);
1332                     } else {
1333                         $row.append('<td>');
1334                     }
1335                 });
1336             if (self.options.deletable) {
1337                 $row.append('<td class="oe_list_group_pagination">');
1338             }
1339         });
1340         return placeholder;
1341     },
1342     bind_child_events: function (child) {
1343         var $this = $(this),
1344              self = this;
1345         $(child).bind('selected', function (e) {
1346             // can have selections spanning multiple links
1347             var selection = self.get_selection();
1348             $this.trigger(e, [selection.ids, selection.records]);
1349         }).bind(this.passtrough_events, function (e) {
1350             // additional positional parameters are provided to trigger as an
1351             // Array, following the event type or event object, but are
1352             // provided to the .bind event handler as *args.
1353             // Convert our *args back into an Array in order to trigger them
1354             // on the group itself, so it can ultimately be forwarded wherever
1355             // it's supposed to go.
1356             var args = Array.prototype.slice.call(arguments, 1);
1357             $this.trigger.call($this, e, args);
1358         });
1359     },
1360     render_dataset: function (dataset) {
1361         var self = this,
1362             list = new (this.view.options.ListType)(this, {
1363                 options: this.options,
1364                 columns: this.columns,
1365                 dataset: dataset,
1366                 records: this.records
1367             });
1368         this.bind_child_events(list);
1369
1370         var view = this.view,
1371            limit = view.limit(),
1372                d = new $.Deferred(),
1373             page = this.datagroup.openable ? this.page : view.page;
1374
1375         var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field"}), 'name');
1376         var options = { offset: page * limit, limit: limit, context: {bin_size: true} };
1377         //TODO xmo: investigate why we need to put the setTimeout
1378         $.async_when().then(function() {dataset.read_slice(fields, options).then(function (records) {
1379             // FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
1380             if (self.records.length) {
1381                 self.records.reset(null, {silent: true});
1382             }
1383             if (!self.datagroup.openable) {
1384                 view.configure_pager(dataset);
1385             } else {
1386                 if (dataset.size() == records.length) {
1387                     // only one page
1388                     self.$row.find('td.oe_list_group_pagination').empty();
1389                 } else {
1390                     var pages = Math.ceil(dataset.size() / limit);
1391                     self.$row
1392                         .find('.oe_list_pager_state')
1393                             .text(_.str.sprintf(_t("%(page)d/%(page_count)d"), {
1394                                 page: page + 1,
1395                                 page_count: pages
1396                             }))
1397                         .end()
1398                         .find('button[data-pager-action=previous]')
1399                             .attr('disabled', page === 0)
1400                         .end()
1401                         .find('button[data-pager-action=next]')
1402                             .attr('disabled', page === pages - 1);
1403                 }
1404             }
1405
1406             self.records.add(records, {silent: true});
1407             list.render();
1408             d.resolve(list);
1409             if (_.isEmpty(records)) {
1410                 view.no_result();
1411             }
1412         });});
1413         return d.promise();
1414     },
1415     setup_resequence_rows: function (list, dataset) {
1416         // drag and drop enabled if list is not sorted and there is a
1417         // visible column with @widget=handle or "sequence" column in the view.
1418         if ((dataset.sort && dataset.sort())
1419             || !_(this.columns).any(function (column) {
1420                     return column.widget === 'handle'
1421                         || column.name === 'sequence'; })) {
1422             return;
1423         }
1424         var sequence_field = _(this.columns).find(function (c) {
1425             return c.widget === 'handle';
1426         });
1427         var seqname = sequence_field ? sequence_field.name : 'sequence';
1428
1429         // ondrop, move relevant record & fix sequences
1430         list.$current.sortable({
1431             axis: 'y',
1432             items: '> tr[data-id]',
1433             helper: 'clone'
1434         });
1435         if (sequence_field) {
1436             list.$current.sortable('option', 'handle', '.oe_list_field_handle');
1437         }
1438         list.$current.sortable('option', {
1439             start: function (e, ui) {
1440                 ui.placeholder.height(ui.item.height());
1441             },
1442             stop: function (event, ui) {
1443                 var to_move = list.records.get(ui.item.data('id')),
1444                     target_id = ui.item.prev().data('id'),
1445                     from_index = list.records.indexOf(to_move),
1446                     target = list.records.get(target_id);
1447                 if (list.records.at(from_index - 1) == target) {
1448                     return;
1449                 }
1450
1451                 list.records.remove(to_move);
1452                 var to = target_id ? list.records.indexOf(target) + 1 : 0;
1453                 list.records.add(to_move, { at: to });
1454
1455                 // resequencing time!
1456                 var record, index = to,
1457                     // if drag to 1st row (to = 0), start sequencing from 0
1458                     // (exclusive lower bound)
1459                     seq = to ? list.records.at(to - 1).get(seqname) : 0;
1460                 while (++seq, record = list.records.at(index++)) {
1461                     // write are independent from one another, so we can just
1462                     // launch them all at the same time and we don't really
1463                     // give a fig about when they're done
1464                     // FIXME: breaks on o2ms (e.g. Accounting > Financial
1465                     //        Accounting > Taxes > Taxes, child tax accounts)
1466                     //        when synchronous (without setTimeout)
1467                     (function (dataset, id, seq) {
1468                         $.async_when().then(function () {
1469                             var attrs = {};
1470                             attrs[seqname] = seq;
1471                             dataset.write(id, attrs);
1472                         });
1473                     }(dataset, record.get('id'), seq));
1474                     record.set(seqname, seq);
1475                 }
1476             }
1477         });
1478     },
1479     render: function (post_render) {
1480         var self = this;
1481         var $el = $('<tbody>');
1482         this.elements = [$el[0]];
1483
1484         this.datagroup.list(
1485             _(this.view.visible_columns).chain()
1486                 .filter(function (column) { return column.tag === 'field' })
1487                 .pluck('name').value(),
1488             function (groups) {
1489                 $el[0].appendChild(
1490                     self.render_groups(groups));
1491                 if (post_render) { post_render(); }
1492             }, function (dataset) {
1493                 self.render_dataset(dataset).then(function (list) {
1494                     self.children[null] = list;
1495                     self.elements =
1496                         [list.$current.replaceAll($el)[0]];
1497                     self.setup_resequence_rows(list, dataset);
1498                     if (post_render) { post_render(); }
1499                 });
1500             });
1501         return $el;
1502     },
1503     /**
1504      * Returns the ids of all selected records for this group, and the records
1505      * themselves
1506      */
1507     get_selection: function () {
1508         var ids = [], records = [];
1509
1510         _(this.children)
1511             .each(function (child) {
1512                 var selection = child.get_selection();
1513                 ids.push.apply(ids, selection.ids);
1514                 records.push.apply(records, selection.records);
1515             });
1516
1517         return {ids: ids, records: records};
1518     },
1519     on_records_reset: function () {
1520         this.children = {};
1521         $(this.elements).remove();
1522     },
1523     get_records: function () {
1524         if (_(this.children).isEmpty()) {
1525             if (!this.datagroup.length) {
1526                 return;
1527             }
1528             return {
1529                 count: this.datagroup.length,
1530                 values: this.datagroup.aggregates
1531             }
1532         }
1533         return _(this.children).chain()
1534             .map(function (child) {
1535                 return child.get_records();
1536             }).flatten().value();
1537     }
1538 });
1539
1540 /**
1541  * @mixin Events
1542  */
1543 var Events = /** @lends Events# */{
1544     /**
1545      * @param {String} event event to listen to on the current object, null for all events
1546      * @param {Function} handler event handler to bind to the relevant event
1547      * @returns this
1548      */
1549     bind: function (event, handler) {
1550         var calls = this['_callbacks'] || (this._callbacks = {});
1551
1552         if (event in calls) {
1553             calls[event].push(handler);
1554         } else {
1555             calls[event] = [handler];
1556         }
1557         return this;
1558     },
1559     /**
1560      * @param {String} event event to unbind on the current object
1561      * @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
1562      * @returns this
1563      */
1564     unbind: function (event, handler) {
1565         var calls = this._callbacks || {};
1566         if (!(event in calls)) { return this; }
1567         if (!handler) {
1568             delete calls[event];
1569         } else {
1570             var handlers = calls[event];
1571             handlers.splice(
1572                 _(handlers).indexOf(handler),
1573                 1);
1574         }
1575         return this;
1576     },
1577     /**
1578      * @param {String} event
1579      * @returns this
1580      */
1581     trigger: function (event) {
1582         var calls;
1583         if (!(calls = this._callbacks)) { return this; }
1584         var callbacks = (calls[event] || []).concat(calls[null] || []);
1585         for(var i=0, length=callbacks.length; i<length; ++i) {
1586             callbacks[i].apply(this, arguments);
1587         }
1588         return this;
1589     }
1590 };
1591 var Record = instance.web.Class.extend(/** @lends Record# */{
1592     /**
1593      * @constructs Record
1594      * @extends instance.web.Class
1595      * 
1596      * @mixes Events
1597      * @param {Object} [data]
1598      */
1599     init: function (data) {
1600         this.attributes = data || {};
1601     },
1602     /**
1603      * @param {String} key
1604      * @returns {Object}
1605      */
1606     get: function (key) {
1607         return this.attributes[key];
1608     },
1609     /**
1610      * @param key
1611      * @param value
1612      * @param {Object} [options]
1613      * @param {Boolean} [options.silent=false]
1614      * @returns {Record}
1615      */
1616     set: function (key, value, options) {
1617         options = options || {};
1618         var old_value = this.attributes[key];
1619         if (old_value === value) {
1620             return this;
1621         }
1622         this.attributes[key] = value;
1623         if (!options.silent) {
1624             this.trigger('change:' + key, this, value, old_value);
1625             this.trigger('change', this, key, value, old_value);
1626         }
1627         return this;
1628     },
1629     /**
1630      * Converts the current record to the format expected by form views:
1631      *
1632      * .. code-block:: javascript
1633      *
1634      *    data: {
1635      *         $fieldname: {
1636      *             value: $value
1637      *         }
1638      *     }
1639      *
1640      *
1641      * @returns {Object} record displayable in a form view
1642      */
1643     toForm: function () {
1644         var form_data = {}, attrs = this.attributes;
1645         for(var k in attrs) {
1646             form_data[k] = {value: attrs[k]};
1647         }
1648
1649         return {data: form_data};
1650     },
1651     /**
1652      * Converts the current record to a format expected by context evaluations
1653      * (identical to record.attributes, except m2o fields are their integer
1654      * value rather than a pair)
1655      */
1656     toContext: function () {
1657         var output = {}, attrs = this.attributes;
1658         for(var k in attrs) {
1659             var val = attrs[k];
1660             if (typeof val !== 'object') {
1661                 output[k] = val;
1662             } else if (val instanceof Array) {
1663                 output[k] = val[0];
1664             } else {
1665                 throw new Error("Can't convert value " + val + " to context");
1666             }
1667         }
1668         return output;
1669     }
1670 });
1671 Record.include(Events);
1672 var Collection = instance.web.Class.extend(/** @lends Collection# */{
1673     /**
1674      * Smarter collections, with events, very strongly inspired by Backbone's.
1675      *
1676      * Using a "dumb" array of records makes synchronization between the
1677      * various serious 
1678      *
1679      * @constructs Collection
1680      * @extends instance.web.Class
1681      * 
1682      * @mixes Events
1683      * @param {Array} [records] records to initialize the collection with
1684      * @param {Object} [options]
1685      */
1686     init: function (records, options) {
1687         options = options || {};
1688         _.bindAll(this, '_onRecordEvent');
1689         this.length = 0;
1690         this.records = [];
1691         this._byId = {};
1692         this._proxies = {};
1693         this._key = options.key;
1694         this._parent = options.parent;
1695
1696         if (records) {
1697             this.add(records);
1698         }
1699     },
1700     /**
1701      * @param {Object|Array} record
1702      * @param {Object} [options]
1703      * @param {Number} [options.at]
1704      * @param {Boolean} [options.silent=false]
1705      * @returns this
1706      */
1707     add: function (record, options) {
1708         options = options || {};
1709         var records = record instanceof Array ? record : [record];
1710
1711         for(var i=0, length=records.length; i<length; ++i) {
1712             var instance_ = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
1713             instance_.bind(null, this._onRecordEvent);
1714             this._byId[instance_.get('id')] = instance_;
1715             if (options.at == undefined) {
1716                 this.records.push(instance_);
1717                 if (!options.silent) {
1718                     this.trigger('add', this, instance_, this.records.length-1);
1719                 }
1720             } else {
1721                 var insertion_index = options.at + i;
1722                 this.records.splice(insertion_index, 0, instance_);
1723                 if (!options.silent) {
1724                     this.trigger('add', this, instance_, insertion_index);
1725                 }
1726             }
1727             this.length++;
1728         }
1729         return this;
1730     },
1731
1732     /**
1733      * Get a record by its index in the collection, can also take a group if
1734      * the collection is not degenerate
1735      *
1736      * @param {Number} index
1737      * @param {String} [group]
1738      * @returns {Record|undefined}
1739      */
1740     at: function (index, group) {
1741         if (group) {
1742             var groups = group.split('.');
1743             return this._proxies[groups[0]].at(index, groups.join('.'));
1744         }
1745         return this.records[index];
1746     },
1747     /**
1748      * Get a record by its database id
1749      *
1750      * @param {Number} id
1751      * @returns {Record|undefined}
1752      */
1753     get: function (id) {
1754         if (!_(this._proxies).isEmpty()) {
1755             var record = null;
1756             _(this._proxies).detect(function (proxy) {
1757                 return record = proxy.get(id);
1758             });
1759             return record;
1760         }
1761         return this._byId[id];
1762     },
1763     /**
1764      * Builds a proxy (insert/retrieve) to a subtree of the collection, by
1765      * the subtree's group
1766      *
1767      * @param {String} section group path section
1768      * @returns {Collection}
1769      */
1770     proxy: function (section) {
1771         return this._proxies[section] = new Collection(null, {
1772             parent: this,
1773             key: section
1774         }).bind(null, this._onRecordEvent);
1775     },
1776     /**
1777      * @param {Array} [records]
1778      * @returns this
1779      */
1780     reset: function (records, options) {
1781         options = options || {};
1782         _(this._proxies).each(function (proxy) {
1783             proxy.reset();
1784         });
1785         this._proxies = {};
1786         _(this.records).invoke('unbind', null, this._onRecordEvent);
1787         this.length = 0;
1788         this.records = [];
1789         this._byId = {};
1790         if (records) {
1791             this.add(records);
1792         }
1793         if (!options.silent) {
1794             this.trigger('reset', this);
1795         }
1796         return this;
1797     },
1798     /**
1799      * Removes the provided record from the collection
1800      *
1801      * @param {Record} record
1802      * @returns this
1803      */
1804     remove: function (record) {
1805         var index = this.indexOf(record);
1806         if (index === -1) {
1807             _(this._proxies).each(function (proxy) {
1808                 proxy.remove(record);
1809             });
1810             return this;
1811         }
1812
1813         record.unbind(null, this._onRecordEvent);
1814         this.records.splice(index, 1);
1815         delete this._byId[record.get('id')];
1816         this.length--;
1817         this.trigger('remove', record, this);
1818         return this;
1819     },
1820
1821     _onRecordEvent: function (event) {
1822         switch(event) {
1823         // don't propagate reset events
1824         case 'reset': return;
1825         case 'change:id':
1826             var record = arguments[1];
1827             var new_value = arguments[2];
1828             var old_value = arguments[3];
1829             // [change:id, record, new_value, old_value]
1830             if (this._byId[old_value] === record) {
1831                 delete this._byId[old_value];
1832                 this._byId[new_value] = record;
1833             }
1834             break;
1835         }
1836         this.trigger.apply(this, arguments);
1837     },
1838
1839     // underscore-type methods
1840     find: function (callback) {
1841         var record;
1842         for(var section in this._proxies) {
1843             if (!this._proxies.hasOwnProperty(section)) {
1844                 continue
1845             }
1846             if ((record = this._proxies[section].find(callback))) {
1847                 return record;
1848             }
1849         }
1850         for(var i=0; i<this.length; ++i) {
1851             record = this.records[i];
1852             if (callback(record)) {
1853                 return record;
1854             }
1855         }
1856     },
1857     each: function (callback) {
1858         for(var section in this._proxies) {
1859             if (this._proxies.hasOwnProperty(section)) {
1860                 this._proxies[section].each(callback);
1861             }
1862         }
1863         for(var i=0; i<this.length; ++i) {
1864             callback(this.records[i]);
1865         }
1866     },
1867     map: function (callback) {
1868         var results = [];
1869         this.each(function (record) {
1870             results.push(callback(record));
1871         });
1872         return results;
1873     },
1874     pluck: function (fieldname) {
1875         return this.map(function (record) {
1876             return record.get(fieldname);
1877         });
1878     },
1879     indexOf: function (record) {
1880         return _(this.records).indexOf(record);
1881     },
1882     succ: function (record, options) {
1883         options = options || {wraparound: false};
1884         var result;
1885         for(var section in this._proxies) {
1886             if (!this._proxies.hasOwnProperty(section)) {
1887                 continue;
1888             }
1889             if ((result = this._proxies[section].succ(record, options))) {
1890                 return result;
1891             }
1892         }
1893         var index = this.indexOf(record);
1894         if (index === -1) { return null; }
1895         var next_index = index + 1;
1896         if (options.wraparound && (next_index === this.length)) {
1897             return this.at(0);
1898         }
1899         return this.at(next_index);
1900     },
1901     pred: function (record, options) {
1902         options = options || {wraparound: false};
1903
1904         var result;
1905         for (var section in this._proxies) {
1906             if (!this._proxies.hasOwnProperty(section)) {
1907                 continue;
1908             }
1909             if ((result = this._proxies[section].pred(record, options))) {
1910                 return result;
1911             }
1912         }
1913
1914         var index = this.indexOf(record);
1915         if (index === -1) { return null; }
1916         var next_index = index - 1;
1917         if (options.wraparound && (next_index === -1)) {
1918             return this.at(this.length - 1);
1919         }
1920         return this.at(next_index);
1921     }
1922 });
1923 Collection.include(Events);
1924 instance.web.list = {
1925     Events: Events,
1926     Record: Record,
1927     Collection: Collection
1928 };
1929 /**
1930  * Registry for column objects used to format table cells (and some other tasks
1931  * e.g. aggregation computations).
1932  *
1933  * Maps a field or button to a Column type via its ``$tag.$widget``,
1934  * ``$tag.$type`` or its ``$tag`` (alone).
1935  *
1936  * This specific registry has a dedicated utility method ``for_`` taking a
1937  * field (from fields_get/fields_view_get.field) and a node (from a view) and
1938  * returning the right object *already instantiated from the data provided*.
1939  *
1940  * @type {instance.web.Registry}
1941  */
1942 instance.web.list.columns = new instance.web.Registry({
1943     'field': 'instance.web.list.Column',
1944     'field.boolean': 'instance.web.list.Boolean',
1945     'field.binary': 'instance.web.list.Binary',
1946     'field.progressbar': 'instance.web.list.ProgressBar',
1947     'field.handle': 'instance.web.list.Handle',
1948     'button': 'instance.web.list.Button',
1949 });
1950 instance.web.list.columns.for_ = function (id, field, node) {
1951     var description = _.extend({tag: node.tag}, field, node.attrs);
1952     var tag = description.tag;
1953     var Type = this.get_any([
1954         tag + '.' + description.widget,
1955         tag + '.'+ description.type,
1956         tag
1957     ]);
1958     return new Type(id, node.tag, description)
1959 };
1960
1961 instance.web.list.Column = instance.web.Class.extend({
1962     init: function (id, tag, attrs) {
1963         _.extend(attrs, {
1964             id: id,
1965             tag: tag
1966         });
1967
1968         this.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
1969         delete attrs.modifiers;
1970         _.extend(this, attrs);
1971
1972         if (this.modifiers['tree_invisible']) {
1973             this.invisible = '1';
1974         } else { delete this.invisible; }
1975     },
1976     modifiers_for: function (fields) {
1977         var out = {};
1978         var domain_computer = instance.web.form.compute_domain;
1979
1980         for (var attr in this.modifiers) {
1981             if (!this.modifiers.hasOwnProperty(attr)) { continue; }
1982             var modifier = this.modifiers[attr];
1983             out[attr] = _.isBoolean(modifier)
1984                 ? modifier
1985                 : domain_computer(modifier, fields);
1986         }
1987
1988         return out;
1989     },
1990     to_aggregate: function () {
1991         if (this.type !== 'integer' && this.type !== 'float') {
1992             return {};
1993         }
1994         var aggregation_func = this['group_operator'] || 'sum';
1995         if (!(aggregation_func in this)) {
1996             return {};
1997         }
1998         var C = function (label, fn) {
1999             this['function'] = fn;
2000             this.label = label;
2001         };
2002         C.prototype = this;
2003         return new C(aggregation_func, this[aggregation_func]);
2004     },
2005     /**
2006      *
2007      * @param row_data record whose values should be displayed in the cell
2008      * @param {Object} [options]
2009      * @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
2010      * @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
2011      * @param {String} [options.model] current record's model
2012      * @param {Number} [options.id] current record's id
2013      * @return {String}
2014      */
2015     format: function (row_data, options) {
2016         options = options || {};
2017         var attrs = {};
2018         if (options.process_modifiers !== false) {
2019             attrs = this.modifiers_for(row_data);
2020         }
2021         if (attrs.invisible) { return ''; }
2022
2023         if (!row_data[this.id]) {
2024             return options.value_if_empty === undefined
2025                     ? ''
2026                     : options.value_if_empty;
2027         }
2028         return this._format(row_data, options);
2029     },
2030     /**
2031      * Method to override in order to provide alternative HTML content for the
2032      * cell. Column._format will simply call ``instance.web.format_value`` and
2033      * escape the output.
2034      *
2035      * The output of ``_format`` will *not* be escaped by ``format``, any
2036      * escaping *must be done* by ``format``.
2037      *
2038      * @private
2039      */
2040     _format: function (row_data, options) {
2041         return _.escape(instance.web.format_value(
2042             row_data[this.id].value, this, options.value_if_empty));
2043     }
2044 });
2045 instance.web.list.MetaColumn = instance.web.list.Column.extend({
2046     meta: true,
2047     init: function (id, string) {
2048         this._super(id, '', {string: string});
2049     }
2050 });
2051 instance.web.list.Button = instance.web.list.Column.extend({
2052     /**
2053      * Return an actual ``<button>`` tag
2054      */
2055     format: function (row_data, options) {
2056         return _.template('<button type="button" title="<%-title%>" <%=additional_attributes%> >' +
2057             '<img src="<%-prefix%>/web/static/src/img/icons/<%-icon%>.png" alt="<%-alt%>"/>' +
2058             '</button>', {
2059                 title: this.string || '',
2060                 additional_attributes: isNaN(row_data["id"].value) && instance.web.BufferedDataSet.virtual_id_regex.test(row_data["id"].value) ?
2061                     'disabled="disabled" class="oe_list_button_disabled"' : '',
2062                 prefix: instance.session.prefix,
2063                 icon: this.icon,
2064                 alt: this.string || ''
2065             });
2066     }
2067 });
2068 instance.web.list.Boolean = instance.web.list.Column.extend({
2069     /**
2070      * Return a potentially disabled checkbox input
2071      *
2072      * @private
2073      */
2074     _format: function (row_data, options) {
2075         return _.str.sprintf('<input type="checkbox" %s disabled="disabled"/>',
2076                  row_data[this.id].value ? 'checked="checked"' : '');
2077     }
2078 });
2079 instance.web.list.Binary = instance.web.list.Column.extend({
2080     /**
2081      * Return a link to the binary data as a file
2082      *
2083      * @private
2084      */
2085     _format: function (row_data, options) {
2086         var text = _t("Download");
2087         var download_url = _.str.sprintf(
2088                 '/web/binary/saveas?session_id=%s&model=%s&field=%s&id=%d',
2089                 instance.session.session_id, options.model, this.id, options.id);
2090         if (this.filename) {
2091             download_url += '&filename_field=' + this.filename;
2092             if (row_data[this.filename]) {
2093                 text = _.str.sprintf(_t("Download \"%s\""), instance.web.format_value(
2094                         row_data[this.filename].value, {type: 'char'}));
2095             }
2096         }
2097         return _.template('<a href="<%-href%>"><%-text%></a> (%<-size%>)', {
2098             text: text,
2099             href: download_url,
2100             size: row_data[this.id].value
2101         });
2102     }
2103 });
2104 instance.web.list.ProgressBar = instance.web.list.Column.extend({
2105     /**
2106      * Return a formatted progress bar display
2107      *
2108      * @private
2109      */
2110     _format: function (row_data, options) {
2111         return _.template(
2112             '<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
2113                 value: _.str.sprintf("%.0f", row_data[this.id].value || 0)
2114             });
2115     }
2116 });
2117 instance.web.list.Handle = instance.web.list.Column.extend({
2118     /**
2119      * Return styling hooks for a drag handle
2120      *
2121      * @private
2122      */
2123     _format: function (row_data, options) {
2124         return '<div class="oe_list_handle">';
2125     }
2126 });
2127 };
2128 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: