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