[FIX] correctly take in account default group_by (from action context)
[odoo/odoo.git] / addons / web / static / src / js / views.js
1 /*---------------------------------------------------------
2  * OpenERP web library
3  *---------------------------------------------------------*/
4
5 openerp.web.views = function(session) {
6
7 var _t = session.web._t;
8
9 /**
10  * Registry for all the client actions key: tag value: widget
11  */
12 session.web.client_actions = new session.web.Registry();
13
14 /**
15  * Registry for all the main views
16  */
17 session.web.views = new session.web.Registry();
18
19 session.web.ActionManager = session.web.Widget.extend({
20     identifier_prefix: "actionmanager",
21     init: function(parent) {
22         this._super(parent);
23         this.inner_viewmanager = null;
24         this.dialog = null;
25         this.dialog_viewmanager = null;
26         this.client_widget = null;
27     },
28     render: function() {
29         return "<div id='"+this.element_id+"'></div>";
30     },
31     dialog_stop: function () {
32         if (this.dialog) {
33             this.dialog_viewmanager.stop();
34             this.dialog_viewmanager = null;
35             this.dialog.stop();
36             this.dialog = null;
37         }
38     },
39     content_stop: function () {
40         if (this.inner_viewmanager) {
41             this.inner_viewmanager.stop();
42             this.inner_viewmanager = null;
43         }
44         if (this.client_widget) {
45             this.client_widget.stop();
46             this.client_widget = null;
47         }
48     },
49     url_update: function(action) {
50         var url = {};
51         if(action.id)
52             url.action_id = action.id;
53         // this.url = {
54         //     "model": action.res_model,
55         //     "domain": action.domain,
56         // };
57         // action.res_model
58         // action.domain
59         // action.context
60         // after
61         // action.views
62         // action.res_id
63         // mode
64         // menu
65         this.do_url_set_hash(url);
66     },
67     do_url_set_hash: function(url) {
68     },
69     on_url_hashchange: function(url) {
70         var self = this;
71         if(url && url.action_id) {
72             self.rpc("/web/action/load", { action_id: url.action_id }, function(result) {
73                     self.do_action(result.result);
74                 });
75         }
76     },
77     do_action: function(action, on_close) {
78         if (!action.type) {
79             console.error("No type for action", action);
80             return;
81         }
82         var type = action.type.replace(/\./g,'_');
83         var popup = action.target === 'new';
84         action.flags = _.extend({
85             views_switcher : !popup,
86             search_view : !popup,
87             action_buttons : !popup,
88             sidebar : !popup,
89             pager : !popup
90         }, action.flags || {});
91         if (!(type in this)) {
92             console.error("Action manager can't handle action of type " + action.type, action);
93             return;
94         }
95         return this[type](action, on_close);
96     },
97     null_action: function() {
98         this.dialog_stop();
99         this.content_stop();
100     },
101     ir_actions_act_window: function (action, on_close) {
102         if (_(['base.module.upgrade', 'base.setup.installer'])
103                 .contains(action.res_model)) {
104             var old_close = on_close;
105             on_close = function () {
106                 session.webclient.do_reload();
107                 if (old_close) { old_close(); }
108             };
109         }
110         if (action.target === 'new') {
111             if (this.dialog == null) {
112                 this.dialog = new session.web.Dialog(this, { title: action.name, width: '80%' });
113                 if(on_close)
114                     this.dialog.on_close.add(on_close);
115                 this.dialog.start();
116             } else {
117                 this.dialog_viewmanager.stop();
118             }
119             this.dialog_viewmanager = new session.web.ViewManagerAction(this, action);
120             this.dialog_viewmanager.appendTo(this.dialog.$element);
121             this.dialog.open();
122         } else  {
123             this.dialog_stop();
124             this.content_stop();
125             this.inner_viewmanager = new session.web.ViewManagerAction(this, action);
126             this.inner_viewmanager.appendTo(this.$element);
127             this.url_update(action);
128         }
129         /* new window code
130             this.rpc("/web/session/save_session_action", { the_action : action}, function(key) {
131                 var url = window.location.protocol + "//" + window.location.host + window.location.pathname + "?" + jQuery.param({ s_action : "" + key });
132                 window.open(url,'_blank');
133             });
134         */
135     },
136     ir_actions_act_window_close: function (action, on_closed) {
137         if (!this.dialog && on_closed) {
138             on_closed();
139         }
140         this.dialog_stop();
141     },
142     ir_actions_server: function (action, on_closed) {
143         var self = this;
144         this.rpc('/web/action/run', {
145             action_id: action.id,
146             context: action.context || {}
147         }).then(function (action) {
148             self.do_action(action, on_closed)
149         });
150     },
151     ir_actions_client: function (action) {
152         this.content_stop();
153         var ClientWidget = session.web.client_actions.get_object(action.tag);
154         (this.client_widget = new ClientWidget(this, action.params)).appendTo(this);
155     },
156     ir_actions_report_xml: function(action, on_closed) {
157         var self = this;
158         $.blockUI();
159         self.rpc("/web/session/eval_domain_and_context", {
160             contexts: [action.context],
161             domains: []
162         }).then(function(res) {
163             action = _.clone(action);
164             action.context = res.context;
165             self.session.get_file({
166                 url: '/web/report',
167                 data: {action: JSON.stringify(action)},
168                 complete: $.unblockUI,
169                 success: function(){
170                     if (!self.dialog && on_closed) {
171                         on_closed();
172                     }
173                     self.dialog_stop();
174                 }
175             })
176         });
177     },
178     ir_actions_act_url: function (action) {
179         window.open(action.url, action.target === 'self' ? '_self' : '_blank');
180     },
181     ir_ui_menu: function (action) {
182         this.widget_parent.do_action(action);
183     }
184 });
185
186 session.web.ViewManager =  session.web.Widget.extend(/** @lends session.web.ViewManager# */{
187     identifier_prefix: "viewmanager",
188     template: "ViewManager",
189     /**
190      * @constructs session.web.ViewManager
191      * @extends session.web.Widget
192      *
193      * @param parent
194      * @param dataset
195      * @param views
196      */
197     init: function(parent, dataset, views) {
198         this._super(parent);
199         this.model = dataset ? dataset.model : undefined;
200         this.dataset = dataset;
201         this.searchview = null;
202         this.active_view = null;
203         this.views_src = _.map(views, function(x) {return x instanceof Array? {view_id: x[0], view_type: x[1]} : x;});
204         this.views = {};
205         this.flags = this.flags || {};
206         this.registry = session.web.views;
207         this.views_history = [];
208     },
209     render: function() {
210         return session.web.qweb.render(this.template, {
211             self: this,
212             prefix: this.element_id,
213             views: this.views_src});
214     },
215     /**
216      * @returns {jQuery.Deferred} initial view loading promise
217      */
218     start: function() {
219         this._super();
220         var self = this;
221         this.$element.find('.oe_vm_switch button').click(function() {
222             self.on_mode_switch($(this).data('view-type'));
223         });
224         var views_ids = {};
225         _.each(this.views_src, function(view) {
226             self.views[view.view_type] = $.extend({}, view, {
227                 deferred : $.Deferred(),
228                 controller : null,
229                 options : _.extend({
230                     sidebar_id : self.element_id + '_sidebar_' + view.view_type,
231                     action : self.action,
232                     action_views_ids : views_ids
233                 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
234             });
235             views_ids[view.view_type] = view.view_id;
236         });
237         if (this.flags.views_switcher === false) {
238             this.$element.find('.oe_vm_switch').hide();
239         }
240         // If no default view defined, switch to the first one in sequence
241         var default_view = this.flags.default_view || this.views_src[0].view_type;
242         return this.on_mode_switch(default_view);
243     },
244     /**
245      * Asks the view manager to switch visualization mode.
246      *
247      * @param {String} view_type type of view to display
248      * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
249      * @returns {jQuery.Deferred} new view loading promise
250      */
251     on_mode_switch: function(view_type, no_store) {
252         var self = this,
253             view = this.views[view_type],
254             view_promise;
255         if(!view)
256             return $.Deferred().reject();
257
258         if (!no_store) {
259             this.views_history.push(view_type);
260         }
261         this.active_view = view_type;
262
263         if (!view.controller) {
264             // Lazy loading of views
265             var controllerclass = this.registry.get_object(view_type);
266             var controller = new controllerclass(this, this.dataset, view.view_id, view.options);
267             if (view.embedded_view) {
268                 controller.set_embedded_view(view.embedded_view);
269             }
270             controller.do_switch_view.add_last(this.on_mode_switch);
271             controller.do_prev_view.add_last(this.on_prev_view);
272             var container = $("#" + this.element_id + '_view_' + view_type);
273             view_promise = controller.appendTo(container);
274             this.views[view_type].controller = controller;
275             this.views[view_type].deferred.resolve();
276             $.when(view_promise).then(function() {
277                 self.on_controller_inited(view_type, controller);
278                 if (self.searchview && view.controller.searchable !== false) {
279                     self.searchview.ready.then(self.searchview.do_search);
280                 }
281             });
282         } else if (this.searchview && view.controller.searchable !== false) {
283             this.searchview.ready.then(this.searchview.do_search);
284         }
285
286         if (this.searchview) {
287             this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
288         }
289
290         this.$element
291             .find('.oe_vm_switch button').removeAttr('disabled')
292             .filter('[data-view-type="' + view_type + '"]')
293             .attr('disabled', true);
294
295         for (var view_name in this.views) {
296             if (!this.views.hasOwnProperty(view_name)) { continue; }
297             if (this.views[view_name].controller) {
298                 if (view_name === view_type) {
299                     $.when(view_promise).then(this.views[view_name].controller.do_show);
300                 } else {
301                     this.views[view_name].controller.do_hide();
302                 }
303             }
304         }
305         $.when(view_promise).then(function () {
306             self.$element.find('.oe_view_title_text:first').text(
307                     self.display_title());
308         });
309         return view_promise;
310     },
311     /**
312      * Returns to the view preceding the caller view in this manager's
313      * navigation history (the navigation history is appended to via
314      * on_mode_switch)
315      *
316      * @param {Boolean} [created=false] returning from a creation
317      * @returns {$.Deferred} switching end signal
318      */
319     on_prev_view: function (created) {
320         var current_view = this.views_history.pop();
321         var previous_view = this.views_history[this.views_history.length - 1];
322         // APR special case: "If creation mode from list (and only from a list),
323         // after saving, go to page view (don't come back in list)"
324         if (created && current_view === 'form' && previous_view === 'list') {
325             return this.on_mode_switch('page');
326         }
327         return this.on_mode_switch(previous_view, true);
328     },
329     /**
330      * Sets up the current viewmanager's search view.
331      *
332      * @param {Number|false} view_id the view to use or false for a default one
333      * @returns {jQuery.Deferred} search view startup deferred
334      */
335     setup_search_view: function(view_id, search_defaults) {
336         var self = this;
337         if (this.searchview) {
338             this.searchview.stop();
339         }
340         this.searchview = new session.web.SearchView(
341                 this, this.dataset,
342                 view_id, search_defaults, this.flags.search_view === false);
343
344         this.searchview.on_search.add(this.do_searchview_search);
345         return this.searchview.appendTo($("#" + this.element_id + "_search"));
346     },
347     do_searchview_search: function(domains, contexts, groupbys) {
348         var self = this,
349             controller = this.views[this.active_view].controller,
350             action_context = this.action.context || {};
351         this.rpc('/web/session/eval_domain_and_context', {
352             domains: [this.action.domain || []].concat(domains || []),
353             contexts: [action_context].concat(contexts || []),
354             group_by_seq: groupbys || []
355         }, function (results) {
356             self.dataset.context = results.context;
357             self.dataset.domain = results.domain;
358             var groupby = results.group_by.length
359                         ? results.group_by
360                         : action_context.group_by;
361             controller.do_search(results.domain, results.context, groupby || []);
362         });
363     },
364     /**
365      * Event launched when a controller has been inited.
366      *
367      * @param {String} view_type type of view
368      * @param {String} view the inited controller
369      */
370     on_controller_inited: function(view_type, view) {
371     },
372     /**
373      * Called when one of the view want to execute an action
374      */
375     on_action: function(action) {
376     },
377     on_create: function() {
378     },
379     on_remove: function() {
380     },
381     on_edit: function() {
382     },
383     /**
384      * Called by children view after executing an action
385      */
386     on_action_executed: function () {},
387     display_title: function () {
388         var view = this.views[this.active_view];
389         if (view) {
390             // ick
391             return view.controller.fields_view.arch.attrs.string;
392         }
393         return '';
394     }
395 });
396
397 session.web.ViewManagerAction = session.web.ViewManager.extend(/** @lends oepnerp.web.ViewManagerAction# */{
398     template:"ViewManagerAction",
399     /**
400      * @constructs session.web.ViewManagerAction
401      * @extends session.web.ViewManager
402      *
403      * @param {session.web.ActionManager} parent parent object/widget
404      * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
405      */
406     init: function(parent, action) {
407         // dataset initialization will take the session from ``this``, so if we
408         // do not have it yet (and we don't, because we've not called our own
409         // ``_super()``) rpc requests will blow up.
410         this._super(parent, null, action.views);
411         this.session = parent.session;
412         this.action = action;
413         var dataset = new session.web.DataSetSearch(this, action.res_model, action.context, action.domain);
414         if (action.res_id) {
415             dataset.ids.push(action.res_id);
416             dataset.index = 0;
417         }
418         this.dataset = dataset;
419         this.flags = this.action.flags || {};
420         if (action.res_model == 'board.board' && action.view_mode === 'form') {
421             // Special case for Dashboards
422             _.extend(this.flags, {
423                 views_switcher : false,
424                 display_title : false,
425                 search_view : false,
426                 pager : false,
427                 sidebar : false,
428                 action_buttons : false
429             });
430         }
431
432         // setup storage for session-wise menu hiding
433         if (this.session.hidden_menutips) {
434             return;
435         }
436         this.session.hidden_menutips = {}
437     },
438     /**
439      * Initializes the ViewManagerAction: sets up the searchview (if the
440      * searchview is enabled in the manager's action flags), calls into the
441      * parent to initialize the primary view and (if the VMA has a searchview)
442      * launches an initial search after both views are done rendering.
443      */
444     start: function() {
445         var self = this,
446             searchview_loaded,
447             search_defaults = {};
448         _.each(this.action.context, function (value, key) {
449             var match = /^search_default_(.*)$/.exec(key);
450             if (match) {
451                 search_defaults[match[1]] = value;
452             }
453         });
454         // init search view
455         var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
456
457         searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
458
459         var main_view_loaded = this._super();
460
461         var manager_ready = $.when(searchview_loaded, main_view_loaded);
462
463         this.$element.find('.oe_get_xml_view').click(function () {
464             var view = self.views[self.active_view].controller,
465                 view_id = view.fields_view.view_id;
466             if (view_id) {
467                 view.on_sidebar_edit_resource('ir.ui.view', view_id);
468             }
469         });
470         if (this.action.help && !this.flags.low_profile) {
471             var Users = new session.web.DataSet(self, 'res.users'),
472                 $tips = this.$element.find('.oe_view_manager_menu_tips');
473             $tips.delegate('blockquote button', 'click', function() {
474                 var $this = $(this);
475                 //noinspection FallthroughInSwitchStatementJS
476                 switch ($this.attr('name')) {
477                 case 'disable':
478                     Users.write(self.session.uid, {menu_tips:false});
479                 case 'hide':
480                     $this.closest('blockquote').hide();
481                     self.session.hidden_menutips[self.action.id] = true;
482                 }
483             });
484             if (!(self.action.id in self.session.hidden_menutips)) {
485                 Users.read_ids([this.session.uid], ['menu_tips'], function(users) {
486                     var user = users[0];
487                     if (!(user && user.id === self.session.uid)) {
488                         return;
489                     }
490                     $tips.find('blockquote').toggle(user.menu_tips);
491                 });
492             }
493         }
494
495         var $res_logs = this.$element.find('.oe-view-manager-logs:first');
496         $res_logs.delegate('a.oe-more-logs', 'click', function () {
497             $res_logs.removeClass('oe-folded');
498             return false;
499         }).delegate('a.oe-remove-everything', 'click', function () {
500             $res_logs.removeClass('oe-has-more')
501                      .find('ul').empty();
502             return false;
503         });
504
505         return manager_ready;
506     },
507     on_mode_switch: function (view_type, no_store) {
508         var self = this;
509
510         return $.when(this._super(view_type, no_store)).then(function () {
511             self.shortcut_check(self.views[view_type]);
512
513             self.$element.find('.oe-view-manager-logs:first')
514                 .addClass('oe-folded').removeClass('oe-has-more')
515                 .find('ul').empty();
516
517             var controller = self.views[self.active_view].controller,
518                 fvg = controller.fields_view,
519                 view_id = (fvg && fvg.view_id) || '--';
520             self.$element.find('.oe_get_xml_view span').text(view_id);
521             if (!self.action.name && fvg) {
522                 self.$element.find('.oe_view_title_text').text(fvg.arch.attrs.string || fvg.name);
523             }
524
525             var $title = self.$element.find('.oe_view_title_text'),
526                 $search_prefix = $title.find('span.oe_searchable_view');
527             if (controller.searchable !== false) {
528                 if (!$search_prefix.length) {
529                     $title.prepend('<span class="oe_searchable_view">' + _t("Search: ") + '</span>');
530                 }
531             } else {
532                 $search_prefix.remove();
533             }
534         });
535     },
536     shortcut_check : function(view) {
537         var self = this;
538         var grandparent = this.widget_parent && this.widget_parent.widget_parent;
539         // display shortcuts if on the first view for the action
540         var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
541         if (!(grandparent instanceof session.web.WebClient) ||
542             !(view.view_type === this.views_src[0].view_type
543                 && view.view_id === this.views_src[0].view_id)) {
544             $shortcut_toggle.hide();
545             return;
546         }
547         $shortcut_toggle.removeClass('oe-shortcut-remove').show();
548         if (_(this.session.shortcuts).detect(function (shortcut) {
549                     return shortcut.res_id === self.session.active_id; })) {
550             $shortcut_toggle.addClass("oe-shortcut-remove");
551         }
552         this.shortcut_add_remove();
553     },
554     shortcut_add_remove: function() {
555         var self = this;
556         var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
557         $shortcut_toggle
558             .unbind("click")
559             .click(function() {
560                 if ($shortcut_toggle.hasClass("oe-shortcut-remove")) {
561                     $(self.session.shortcuts.binding).trigger('remove-current');
562                     $shortcut_toggle.removeClass("oe-shortcut-remove");
563                 } else {
564                     $(self.session.shortcuts.binding).trigger('add', {
565                         'user_id': self.session.uid,
566                         'res_id': self.session.active_id,
567                         'resource': 'ir.ui.menu',
568                         'name': self.action.name
569                     });
570                     $shortcut_toggle.addClass("oe-shortcut-remove");
571                 }
572             });
573     },
574     /**
575      * Intercept do_action resolution from children views
576      */
577     on_action_executed: function () {
578         return new session.web.DataSet(this, 'res.log')
579                 .call('get', [], this.do_display_log);
580     },
581     /**
582      * @param {Array<Object>} log_records
583      */
584     do_display_log: function (log_records) {
585         var self = this,
586             cutoff = 3,
587             $logs = this.$element.find('.oe-view-manager-logs:first')
588                     .addClass('oe-folded'),
589             $logs_list = $logs.find('ul').empty();
590         $logs.toggleClass('oe-has-more', log_records.length > cutoff);
591         _(log_records.reverse()).each(function (record) {
592             $(_.str.sprintf('<li><a href="#">%s</a></li>', record.name))
593                 .appendTo($logs_list)
594                 .delegate('a', 'click', function (e) {
595                     self.do_action({
596                         type: 'ir.actions.act_window',
597                         res_model: record.res_model,
598                         res_id: record.res_id,
599                         // TODO: need to have an evaluated context here somehow
600                         //context: record.context,
601                         views: [[false, 'form']]
602                     });
603                     return false;
604                 });
605         });
606     },
607     display_title: function () {
608         return this.action.name;
609     }
610 });
611
612 session.web.Sidebar = session.web.Widget.extend({
613     init: function(parent, element_id) {
614         this._super(parent, element_id);
615         this.items = {};
616         this.sections = {};
617     },
618     start: function() {
619         this._super(this);
620         var self = this;
621         this.$element.html(session.web.qweb.render('Sidebar'));
622         this.$element.find(".toggle-sidebar").click(function(e) {
623             self.do_toggle();
624         });
625     },
626     add_default_sections: function() {
627         var self = this,
628             view = this.widget_parent,
629             view_manager = view.widget_parent,
630             action = view_manager.action;
631         if (this.session.uid === 1) {
632             this.add_section(_t('Customize'), 'customize');
633             this.add_items('customize', [
634                 {
635                     label: _t("Manage Views"),
636                     callback: view.on_sidebar_manage_views,
637                     title: _t("Manage views of the current object")
638                 }, {
639                     label: _t("Edit Workflow"),
640                     callback: view.on_sidebar_edit_workflow,
641                     title: _t("Manage views of the current object"),
642                     classname: 'oe_hide oe_sidebar_edit_workflow'
643                 }, {
644                     label: _t("Customize Object"),
645                     callback: view.on_sidebar_customize_object,
646                     title: _t("Manage views of the current object")
647                 }, {
648                     label: _t("Translate"),
649                     callback: view.on_sidebar_translate,
650                     title: _t("Technical translation")
651                 }
652             ]);
653         }
654
655         this.add_section(_t('Other Options'), 'other');
656         this.add_items('other', [
657             {
658                 label: _t("Import"),
659                 callback: view.on_sidebar_import
660             }, {
661                 label: _t("Export"),
662                 callback: view.on_sidebar_export
663             }, {
664                 label: _t("View Log"),
665                 callback: view.on_sidebar_view_log,
666                 classname: 'oe_hide oe_sidebar_view_log'
667             }
668         ]);
669
670         if (session.connection.debug) {
671             this.add_section("Debug", 'debug');
672             if (action && action.id) {
673                 this.add_items('debug', [{
674                     label: "Edit Action",
675                     callback: function() {
676                         view.on_sidebar_edit_resource(action.type, action.id);
677                     }
678                 }]);
679             }
680             if (view_manager.searchview && view_manager.searchview.view_id) {
681                 this.add_items('debug', [{
682                     label: "Edit SearchView",
683                     callback: function() {
684                         view.on_sidebar_edit_resource('ir.ui.view', view_manager.searchview.view_id);
685                     }
686                 }]);
687             }
688         }
689     },
690
691     add_toolbar: function(toolbar) {
692         var self = this;
693         _.each([['print', _t("Reports")], ['action', _t("Actions")], ['relate', _t("Links")]], function(type) {
694             var items = toolbar[type[0]];
695             if (items.length) {
696                 for (var i = 0; i < items.length; i++) {
697                     items[i] = {
698                         label: items[i]['name'],
699                         action: items[i],
700                         classname: 'oe_sidebar_' + type[0]
701                     }
702                 }
703                 self.add_section(type[1], type[0]);
704                 self.add_items(type[0], items);
705             }
706         });
707     },
708
709     add_section: function(name, code) {
710         if(!code) code = _.str.underscored(name);
711         var $section = this.sections[code];
712
713         if(!$section) {
714             var section_id = _.uniqueId(this.element_id + '_section_' + code + '_');
715             $section = $(session.web.qweb.render("Sidebar.section", {
716                 section_id: section_id,
717                 name: name,
718                 classname: 'oe_sidebar_' + code
719             }));
720             $section.appendTo(this.$element.find('div.sidebar-actions'));
721             this.sections[code] = $section;
722         }
723         return $section;
724     },
725
726     add_items: function(section_code, items) {
727         // An item is a dictonary : {
728         //    label: label to be displayed for the link,
729         //    action: action to be launch when the link is clicked,
730         //    callback: a function to be executed when the link is clicked,
731         //    classname: optional dom class name for the line,
732         //    title: optional title for the link
733         // }
734         // Note: The item should have one action or/and a callback
735         //
736
737         var self = this,
738             $section = this.add_section(_.str.titleize(section_code.replace('_', ' ')), section_code),
739             section_id = $section.attr('id');
740
741         if (items) {
742             for (var i = 0; i < items.length; i++) {
743                 items[i].element_id = _.uniqueId(section_id + '_item_');
744                 this.items[items[i].element_id] = items[i];
745             }
746
747             var $items = $(session.web.qweb.render("Sidebar.section.items", {items: items}));
748
749             $items.find('a.oe_sidebar_action_a').click(function() {
750                 var item = self.items[$(this).attr('id')];
751                 if (item.callback) {
752                     item.callback.apply(self, [item]);
753                 }
754                 if (item.action) {
755                     self.on_item_action_clicked(item);
756                 }
757                 return false;
758             });
759
760             var $ul = $section.find('ul');
761             if(!$ul.length) {
762                 $ul = $('<ul/>').appendTo($section);
763             }
764             $items.appendTo($ul);
765         }
766     },
767     on_item_action_clicked: function(item) {
768         var self = this;
769         self.widget_parent.sidebar_context().then(function (context) {
770             var ids = self.widget_parent.get_selected_ids();
771             if (ids.length == 0) {
772                 //TODO: make prettier warning?
773                 $("<div />").text(_t("You must choose at least one record.")).dialog({
774                     title: _t("Warning"),
775                     modal: true
776                 });
777                 return false;
778             }
779             var additional_context = _.extend({
780                 active_id: ids[0],
781                 active_ids: ids,
782                 active_model: self.widget_parent.dataset.model
783             }, context);
784             self.rpc("/web/action/load", {
785                 action_id: item.action.id,
786                 context: additional_context
787             }, function(result) {
788                 result.result.context = _.extend(result.result.context || {},
789                     additional_context);
790                 result.result.flags = result.result.flags || {};
791                 result.result.flags.new_window = true;
792                 self.do_action(result.result);
793             });
794         });
795     },
796     do_fold: function() {
797         this.$element.addClass('closed-sidebar').removeClass('open-sidebar');
798     },
799     do_unfold: function() {
800         this.$element.addClass('open-sidebar').removeClass('closed-sidebar');
801     },
802     do_toggle: function() {
803         this.$element.toggleClass('open-sidebar closed-sidebar');
804     }
805 });
806
807 session.web.TranslateDialog = session.web.Dialog.extend({
808     dialog_title: _t("Translations"),
809     init: function(view) {
810         // TODO fme: should add the language to fields_view_get because between the fields view get
811         // and the moment the user opens the translation dialog, the user language could have been changed
812         this.view_language = view.session.user_context.lang;
813         this['on_button' + _t("Save")] = this.on_button_Save;
814         this['on_button' + _t("Close")] = this.on_button_Close;
815         this._super(view, {
816             width: '80%',
817             height: '80%'
818         });
819         this.view = view;
820         this.view_type = view.fields_view.type || '';
821         this.$fields_form = null;
822         this.$view_form = null;
823         this.$sidebar_form = null;
824         this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
825         this.languages = null;
826         this.languages_loaded = $.Deferred();
827         (new session.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
828             [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }, this.on_languages_loaded);
829     },
830     start: function() {
831         var self = this;
832         this._super();
833         $.when(this.languages_loaded).then(function() {
834             self.$element.html(session.web.qweb.render('TranslateDialog', { widget: self }));
835             self.$fields_form = self.$element.find('.oe_translation_form');
836             self.$fields_form.find('.oe_trad_field').change(function() {
837                 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
838             });
839         });
840         return this;
841     },
842     on_languages_loaded: function(langs) {
843         this.languages = langs;
844         this.languages_loaded.resolve();
845     },
846     do_load_fields_values: function(callback) {
847         var self = this,
848             deffered = [];
849         this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
850         _.each(self.languages, function(lg) {
851             var deff = $.Deferred();
852             deffered.push(deff);
853             var callback = function(values) {
854                 _.each(self.translatable_fields_keys, function(f) {
855                     self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
856                 });
857                 deff.resolve();
858             };
859             if (lg.code === self.view_language) {
860                 var values = {};
861                 _.each(self.translatable_fields_keys, function(field) {
862                     values[field] = self.view.fields[field].get_value();
863                 });
864                 callback([values]);
865             } else {
866                 self.rpc('/web/dataset/get', {
867                     model: self.view.dataset.model,
868                     ids: [self.view.datarecord.id],
869                     fields: self.translatable_fields_keys,
870                     context: self.view.dataset.get_context({
871                         'lang': lg.code
872                     })}, callback);
873             }
874         });
875         $.when.apply(null, deffered).then(callback);
876     },
877     open: function(field) {
878         var self = this,
879             sup = this._super;
880         $.when(this.languages_loaded).then(function() {
881             if (self.view.translatable_fields && self.view.translatable_fields.length) {
882                 self.do_load_fields_values(function() {
883                     sup.call(self);
884                     if (field) {
885                         var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
886                         self.$element.scrollTo($field_input);
887                         $field_input.focus();
888                     }
889                 });
890             } else {
891                 sup.call(self);
892             }
893         });
894     },
895     on_button_Save: function() {
896         var trads = {},
897             self = this;
898         self.$fields_form.find('.oe_trad_field.touched').each(function() {
899             var field = $(this).attr('name').split('-');
900             if (!trads[field[0]]) {
901                 trads[field[0]] = {};
902             }
903             trads[field[0]][field[1]] = $(this).val();
904         });
905         _.each(trads, function(data, code) {
906             if (code === self.view_language) {
907                 _.each(data, function(value, field) {
908                     self.view.fields[field].set_value(value);
909                 });
910             } else {
911                 self.view.dataset.write(self.view.datarecord.id, data, { 'lang': code });
912             }
913         });
914         this.close();
915     },
916     on_button_Close: function() {
917         this.close();
918     }
919 });
920
921 session.web.View = session.web.Widget.extend(/** @lends session.web.View# */{
922     template: "EmptyComponent",
923     set_default_options: function(options) {
924         this.options = options || {};
925         _.defaults(this.options, {
926             // All possible views options should be defaulted here
927             sidebar_id: null,
928             sidebar: true,
929             action: null,
930             action_views_ids: {}
931         });
932     },
933     open_translate_dialog: function(field) {
934         if (!this.translate_dialog) {
935             this.translate_dialog = new session.web.TranslateDialog(this).start();
936         }
937         this.translate_dialog.open(field);
938     },
939     /**
940      * Fetches and executes the action identified by ``action_data``.
941      *
942      * @param {Object} action_data the action descriptor data
943      * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
944      * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
945      * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
946      * @param {Object} [action_data.context=null] additional action context, to add to the current context
947      * @param {session.web.DataSet} dataset a dataset object used to communicate with the server
948      * @param {Object} [record_id] the identifier of the object on which the action is to be applied
949      * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
950      */
951     do_execute_action: function (action_data, dataset, record_id, on_closed) {
952         var self = this;
953         var result_handler = function () {
954             if (on_closed) { on_closed.apply(null, arguments); }
955             if (self.widget_parent && self.widget_parent.on_action_executed) {
956                 return self.widget_parent.on_action_executed.apply(null, arguments);
957             }
958         };
959         var context = new session.web.CompoundContext(dataset.get_context(), action_data.context || {});
960
961         var handler = function (r) {
962             var action = r.result;
963             if (action && action.constructor == Object) {
964                 var ncontext = new session.web.CompoundContext(context);
965                 if (record_id) {
966                     ncontext.add({
967                         active_id: record_id,
968                         active_ids: [record_id],
969                         active_model: dataset.model
970                     });
971                 }
972                 ncontext.add(action.context || {});
973                 return self.rpc('/web/session/eval_domain_and_context', {
974                     contexts: [ncontext],
975                     domains: []
976                 }).pipe(function (results) {
977                     action.context = results.context;
978                     /* niv: previously we were overriding once more with action_data.context,
979                      * I assumed this was not a correct behavior and removed it
980                      */
981                     return self.do_action(action, result_handler);
982                 }, null);
983             } else {
984                 return result_handler();
985             }
986         };
987
988         if (action_data.special) {
989             return handler({result: {"type":"ir.actions.act_window_close"}});
990         } else if (action_data.type=="object") {
991             var args = [[record_id]], additional_args = [];
992             if (action_data.args) {
993                 try {
994                     // Warning: quotes and double quotes problem due to json and xml clash
995                     // Maybe we should force escaping in xml or do a better parse of the args array
996                     additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
997                     args = args.concat(additional_args);
998                 } catch(e) {
999                     console.error("Could not JSON.parse arguments", action_data.args);
1000                 }
1001             }
1002             args.push(context);
1003             return dataset.call_button(action_data.name, args, handler);
1004         } else if (action_data.type=="action") {
1005             return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1006         } else  {
1007             return dataset.exec_workflow(record_id, action_data.name, handler);
1008         }
1009     },
1010     /**
1011      * Directly set a view to use instead of calling fields_view_get. This method must
1012      * be called before start(). When an embedded view is set, underlying implementations
1013      * of session.web.View must use the provided view instead of any other one.
1014      *
1015      * @param embedded_view A view.
1016      */
1017     set_embedded_view: function(embedded_view) {
1018         this.embedded_view = embedded_view;
1019         this.options.sidebar = false;
1020     },
1021     /**
1022      * Switches to a specific view type
1023      *
1024      * @param {String} view view type to switch to
1025      */
1026     do_switch_view: function(view) { },
1027     /**
1028      * Cancels the switch to the current view, switches to the previous one
1029      */
1030     do_prev_view: function () { },
1031     do_search: function(view) {
1032     },
1033
1034     set_common_sidebar_sections: function(sidebar) {
1035         sidebar.add_default_sections();
1036     },
1037     on_sidebar_manage_views: function() {
1038         if (this.fields_view && this.fields_view.arch) {
1039             var view_editor = new session.web.ViewEditor(this, this.$element, this.dataset, this.fields_view.arch);
1040             view_editor.start();
1041         } else {
1042             this.do_warn("Manage Views", "Could not find current view declaration");
1043         }
1044     },
1045     on_sidebar_edit_workflow: function() {
1046         console.log('Todo');
1047     },
1048     on_sidebar_customize_object: function() {
1049         var self = this;
1050         this.rpc('/web/dataset/search_read', {
1051             model: 'ir.model',
1052             fields: ['id'],
1053             domain: [['model', '=', self.dataset.model]]
1054         }, function (result) {
1055             self.on_sidebar_edit_resource('ir.model', result.ids[0]);
1056         });
1057     },
1058     on_sidebar_import: function() {
1059         var import_view = new session.web.DataImport(this, this.dataset);
1060         import_view.start();
1061     },
1062     on_sidebar_export: function() {
1063         var export_view = new session.web.DataExport(this, this.dataset);
1064         export_view.start();
1065     },
1066     on_sidebar_translate: function() {
1067         return this.do_action({
1068             res_model : 'ir.translation',
1069             domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1070             views: [[false, 'list'], [false, 'form']],
1071             type : 'ir.actions.act_window',
1072             view_type : "list",
1073             view_mode : "list"
1074         });
1075     },
1076     on_sidebar_edit_resource: function(model, id, domain) {
1077         var action = {
1078             res_model : model,
1079             type : 'ir.actions.act_window',
1080             view_type : 'form',
1081             view_mode : 'form',
1082             target : 'new',
1083             flags : {
1084                 action_buttons : true
1085             }
1086         }
1087         if (id) {
1088             action.res_id = id,
1089             action.views = [[false, 'form']];
1090         } else if (domain) {
1091             action.views = [[false, 'list'], [false, 'form']];
1092             action.domain = domain;
1093             action.flags.views_switcher = true;
1094         }
1095         this.do_action(action);
1096     },
1097     on_sidebar_view_log: function() {
1098     },
1099     sidebar_context: function () {
1100         return $.Deferred().resolve({}).promise();
1101     }
1102 });
1103
1104 session.web.json_node_to_xml = function(node, human_readable, indent) {
1105     // For debugging purpose, this function will convert a json node back to xml
1106     // Maybe usefull for xml view editor
1107     indent = indent || 0;
1108     var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1109         r = sindent + '<' + node.tag,
1110         cr = human_readable ? '\n' : '';
1111
1112     if (typeof(node) === 'string') {
1113         return sindent + node;
1114     } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1115         throw("Node a json node");
1116     }
1117     for (var attr in node.attrs) {
1118         var vattr = node.attrs[attr];
1119         if (typeof(vattr) !== 'string') {
1120             // domains, ...
1121             vattr = JSON.stringify(vattr);
1122         }
1123         vattr = vattr.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
1124         if (human_readable) {
1125             vattr = vattr.replace(/&quot;/g, "'");
1126         }
1127         r += ' ' + attr + '="' + vattr + '"';
1128     }
1129     if (node.children && node.children.length) {
1130         r += '>' + cr;
1131         var childs = [];
1132         for (var i = 0, ii = node.children.length; i < ii; i++) {
1133             childs.push(session.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1134         }
1135         r += childs.join(cr);
1136         r += cr + sindent + '</' + node.tag + '>';
1137         return r;
1138     } else {
1139         return r + '/>';
1140     }
1141 }
1142
1143 };
1144
1145 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: