b70217a1021498ed13f6534b5b95d8ac595b3502
[odoo/odoo.git] / addons / web_dashboard / static / src / js / dashboard.js
1 openerp.web_dashboard = function(openerp) {
2 var QWeb = openerp.web.qweb;
3
4 if (!openerp.web_dashboard) {
5     /** @namespace */
6     openerp.web_dashboard = {};
7 }
8
9 openerp.web.form.DashBoard = openerp.web.form.Widget.extend({
10     init: function(view, node) {
11         this._super(view, node);
12         this.template = 'DashBoard';
13         this.actions_attrs = {};
14         this.action_managers = [];
15     },
16     start: function() {
17         var self = this;
18         this._super.apply(this, arguments);
19
20         this.$element.find('.oe-dashboard-column').sortable({
21             connectWith: '.oe-dashboard-column',
22             handle: '.oe-dashboard-action-header',
23             scroll: false
24         }).disableSelection().bind('sortstop', self.do_save_dashboard);
25
26         // Events
27         this.$element.find('.oe-dashboard-link-reset').click(this.on_reset);
28         this.$element.find('.oe-dashboard-link-change_layout').click(this.on_change_layout);
29
30         this.$element.delegate('.oe-dashboard-column .oe-dashboard-fold', 'click', this.on_fold_action);
31         this.$element.delegate('.oe-dashboard-column .ui-icon-closethick', 'click', this.on_close_action);
32
33         this.actions_attrs = {};
34         // Init actions
35         _.each(this.node.children, function(column, column_index) {
36             _.each(column.children, function(action, action_index) {
37                 delete(action.attrs.width);
38                 delete(action.attrs.height);
39                 delete(action.attrs.colspan);
40                 self.actions_attrs[action.attrs.name] = action.attrs;
41                 self.rpc('/web/action/load', {
42                     action_id: parseInt(action.attrs.name, 10)
43                 }, function(result) {
44                     self.on_load_action(result, column_index + '_' + action_index);
45                 });
46             });
47         });
48     },
49     on_reset: function() {
50         this.rpc('/web/view/undo_custom', {
51             view_id: this.view.fields_view.view_id,
52             reset: true
53         }, this.do_reload);
54     },
55     on_change_layout: function() {
56         var self = this;
57         var qdict = {
58             current_layout : this.$element.find('.oe-dashboard').attr('data-layout')
59         };
60         var $dialog = $('<div>').dialog({
61                             modal: true,
62                             title: 'Edit Layout',
63                             width: 'auto',
64                             height: 'auto'
65                         }).html(QWeb.render('DashBoard.layouts', qdict));
66         $dialog.find('li').click(function() {
67             var layout = $(this).attr('data-layout');
68             $dialog.dialog('destroy');
69             self.do_change_layout(layout);
70         });
71     },
72     do_change_layout: function(new_layout) {
73         var $dashboard = this.$element.find('.oe-dashboard');
74         var current_layout = $dashboard.attr('data-layout');
75         if (current_layout != new_layout) {
76             var clayout = current_layout.split('-').length,
77                 nlayout = new_layout.split('-').length,
78                 column_diff = clayout - nlayout;
79             if (column_diff > 0) {
80                 var $last_column = $();
81                 $dashboard.find('.oe-dashboard-column').each(function(k, v) {
82                     if (k >= nlayout) {
83                         $(v).find('.oe-dashboard-action').appendTo($last_column);
84                     } else {
85                         $last_column = $(v);
86                     }
87                 });
88             }
89             $dashboard.toggleClass('oe-dashboard-layout_' + current_layout + ' oe-dashboard-layout_' + new_layout);
90             $dashboard.attr('data-layout', new_layout);
91             this.do_save_dashboard();
92         }
93     },
94     on_fold_action: function(e) {
95         var $e = $(e.currentTarget),
96             $action = $e.parents('.oe-dashboard-action:first'),
97             id = parseInt($action.attr('data-id'), 10);
98         if ($e.is('.ui-icon-minusthick')) {
99             this.actions_attrs[id].fold = '1';
100         } else {
101             delete(this.actions_attrs[id].fold);
102         }
103         $e.toggleClass('ui-icon-minusthick ui-icon-plusthick');
104         $action.find('.oe-dashboard-action-content').toggle();
105         this.do_save_dashboard();
106     },
107     on_close_action: function(e) {
108         if (confirm("Are you sure you want to remove this item ?")) {
109             $(e.currentTarget).parents('.oe-dashboard-action:first').remove();
110             this.do_save_dashboard();
111         }
112     },
113     do_save_dashboard: function() {
114         var self = this;
115         var board = {
116                 form_title : this.view.fields_view.arch.attrs.string,
117                 style : this.$element.find('.oe-dashboard').attr('data-layout'),
118                 columns : []
119             };
120         this.$element.find('.oe-dashboard-column').each(function() {
121             var actions = [];
122             $(this).find('.oe-dashboard-action').each(function() {
123                 var action_id = $(this).attr('data-id'),
124                     new_attrs = _.clone(self.actions_attrs[action_id]);
125                 if (new_attrs.domain) {
126                     new_attrs.domain = new_attrs.domain_string;
127                     delete(new_attrs.domain_string);
128                 }
129                 if (new_attrs.context) {
130                     new_attrs.context = new_attrs.context_string;
131                     delete(new_attrs.context_string);
132                 }
133                 actions.push(new_attrs);
134             });
135             board.columns.push(actions);
136         });
137         var arch = QWeb.render('DashBoard.xml', board);
138         this.rpc('/web/view/add_custom', {
139             view_id: this.view.fields_view.view_id,
140             arch: arch
141         }, function() {
142             self.$element.find('.oe-dashboard-link-reset').show();
143         });
144     },
145     on_load_action: function(result, index) {
146         var self = this,
147             action = result.result,
148             action_attrs = this.actions_attrs[action.id],
149             view_mode = action_attrs.view_mode;
150
151         if (action_attrs.context) {
152             action.context = action_attrs.context;
153         }
154         if (action_attrs.domain) {
155             action.domain = action_attrs.domain;
156         }
157         var action_orig = _.extend({ flags : {} }, action);
158
159         if (view_mode && view_mode != action.view_mode) {
160             var action_view_mode = action.view_mode.split(',');
161             action.views = _.map(view_mode.split(','), function(mode) {
162                 if (_.indexOf(action_view_mode, mode) < 0) {
163                     return [false, mode == 'tree' ? 'list': mode];
164                 } else {
165                     mode = mode === 'tree' ? 'list' : mode;
166                     return _.find(action.views, function(view) {
167                         return view[1] == mode;
168                     });
169                 }
170             });
171         }
172
173         action.flags = {
174             search_view : false,
175             sidebar : false,
176             views_switcher : false,
177             action_buttons : false,
178             pager: false,
179             low_profile: true,
180             display_title: false,
181             list: {
182                 selectable: false
183             }
184         };
185         var am = new openerp.web.ActionManager(this),
186             // FIXME: ideally the dashboard view shall be refactored like kanban.
187             $action = $('#' + this.view.element_id + '_action_' + index);
188         this.action_managers.push(am);
189         am.appendTo($action);
190         am.do_action(action);
191         am.do_action = function(action) {
192             self.do_action(action);
193         }
194         if (action_attrs.creatable && action_attrs.creatable !== 'false') {
195             var action_id = parseInt(action_attrs.creatable, 10);
196             $action.parent().find('button.oe_dashboard_button_create').click(function() {
197                 if (isNaN(action_id)) {
198                     action_orig.flags.default_view = 'form';
199                     self.do_action(action_orig);
200                 } else {
201                     self.rpc('/web/action/load', {
202                         action_id: action_id
203                     }, function(result) {
204                         result.result.flags = result.result.flags || {};
205                         result.result.flags.default_view = 'form';
206                         self.do_action(result.result);
207                     });
208                 }
209             });
210         }
211         if (am.inner_viewmanager) {
212             am.inner_viewmanager.on_mode_switch.add(function(mode) {
213                 var new_views = [];
214                 _.each(action_orig.views, function(view) {
215                     new_views[view[1] === mode ? 'unshift' : 'push'](view);
216                 });
217                 if (!new_views.length || new_views[0][1] !== mode) {
218                     new_views.unshift([false, mode]);
219                 }
220                 action_orig.views = new_views;
221                 action_orig.res_id = am.inner_viewmanager.dataset.ids[am.inner_viewmanager.dataset.index];
222                 self.do_action(action_orig);
223             });
224         }
225     },
226     render: function() {
227         // We should start with three columns available
228         for (var i = this.node.children.length; i < 3; i++) {
229             this.node.children.push({
230                 tag: 'column',
231                 attrs: {},
232                 children: []
233             });
234         }
235         return QWeb.render(this.template, this);
236     },
237     do_reload: function() {
238         var view_manager = this.view.widget_parent,
239             action_manager = view_manager.widget_parent;
240         this.view.stop();
241         action_manager.do_action(view_manager.action);
242     }
243 });
244 openerp.web.form.DashBoardLegacy = openerp.web.form.DashBoard.extend({
245     render: function() {
246         if (this.node.tag == 'hpaned') {
247             this.node.attrs.style = '2-1';
248         } else if (this.node.tag == 'vpaned') {
249             this.node.attrs.style = '1';
250         }
251         this.node.tag = 'board';
252         _.each(this.node.children, function(child) {
253             if (child.tag.indexOf('child') == 0) {
254                 child.tag = 'column';
255                 var actions = [], first_child = child.children[0];
256                 if (first_child && first_child.tag == 'vpaned') {
257                     _.each(first_child.children, function(subchild) {
258                         actions.push.apply(actions, subchild.children);
259                     });
260                     child.children = actions;
261                 }
262             }
263         });
264         return this._super(this, arguments);
265     }
266 });
267
268 openerp.web.form.widgets.add('hpaned', 'openerp.web.form.DashBoardLegacy');
269 openerp.web.form.widgets.add('vpaned', 'openerp.web.form.DashBoardLegacy');
270 openerp.web.form.widgets.add('board', 'openerp.web.form.DashBoard');
271
272 /*
273  * ConfigOverview
274  * This client action designed to be used as a dashboard widget display
275  * ir.actions.todo in a fancy way
276  */
277 openerp.web.client_actions.add( 'board.config.overview', 'openerp.web_dashboard.ConfigOverview');
278 openerp.web_dashboard.ConfigOverview = openerp.web.View.extend({
279     template: 'ConfigOverview',
280     init: function (parent) {
281         this._super(parent);
282         this.user = _.extend(new openerp.web.DataSet(this, 'res.users'), {
283             index: 0,
284             ids: [this.session.uid]
285         });
286         this.dataset = new openerp.web.DataSetSearch(this, 'ir.actions.todo');
287     },
288     start: function () {
289         this._super();
290         var self = this;
291         return this.user.read_index(['groups_id']).pipe(function (record) {
292             var todos_filter = [
293                 ['type', '!=', 'automatic'],
294                 '|', ['groups_id', '=', false],
295                      ['groups_id', 'in', record['groups_id']]];
296             return $.when(
297                 self.dataset.read_slice(['state', 'action_id', 'category_id'],{
298                         domain: todos_filter }),
299                 self.dataset.call('progress').pipe(
300                         function (arg) { return arg; }, null))
301         }, null).then(this.on_records_loaded);
302
303     },
304     on_records_loaded: function (records, progress) {
305         var grouped_todos = _(records).chain()
306             .map(function (record) {
307                 return {
308                     id: record.id,
309                     name: record.action_id[1],
310                     done: record.state !== 'open',
311                     to_do: record.state === 'open',
312                     category: record['category_id'][1] || "Uncategorized"
313                 }
314             })
315             .groupBy(function (record) {return record.category})
316             .value();
317         this.$element.html(QWeb.render('ConfigOverview.content', {
318             completion: 100 * progress.done / progress.total,
319             groups: grouped_todos
320         }));
321         var $progress = this.$element.find('div.oe-config-progress-bar');
322         $progress.progressbar({value: $progress.data('completion')});
323
324         var self = this;
325         this.$element.find('dl')
326             .delegate('input', 'click', function (e) {
327                 // switch todo status
328                 e.stopImmediatePropagation();
329                 var new_state = this.checked ? 'done' : 'open',
330                       todo_id = parseInt($(this).val(), 10);
331                 self.dataset.write(todo_id, {state: new_state}, {}, function () {
332                     self.start();
333                 });
334             })
335             .delegate('li:not(.oe-done)', 'click', function () {
336                 self.widget_parent.widget_parent.widget_parent.do_execute_action({
337                         type: 'object',
338                         name: 'action_launch'
339                     }, self.dataset,
340                     $(this).data('id'), function () {
341                         // after action popup closed, refresh configuration
342                         // thingie
343                         self.start();
344                     });
345             });
346     }
347 });
348
349 /*
350  * Widgets
351  * This client action designed to be used as a dashboard widget display
352  * the html content of a res_widget given as argument
353  */
354 openerp.web.client_actions.add( 'board.home.widgets', 'openerp.web_dashboard.Widget');
355 openerp.web_dashboard.Widget = openerp.web.View.extend(/** @lends openerp.web_dashboard.Widgets# */{
356     template: 'HomeWidget',
357     /**
358      * Initializes a "HomeWidget" client widget: handles the display of a given
359      * res.widget objects in an OpenERP view (mainly a dashboard).
360      *
361      * @constructs openerp.web_dashboard.Widget
362      * @extends openerp.web.View
363      *
364      * @param {Object} parent
365      * @param {Object} options
366      * @param {Number} options.widget_id
367      */
368     init: function (parent, options) {
369         this._super(parent);
370         this.widget_id = options.widget_id;
371     },
372     start: function () {
373         this._super();
374         return new openerp.web.DataSet(this, 'res.widget').read_ids(
375                 [this.widget_id], ['title'], this.on_widget_loaded);
376     },
377     on_widget_loaded: function (widgets) {
378         var widget = widgets[0];
379         var url = _.str.sprintf(
380             '/web_dashboard/widgets/content?session_id=%s&widget_id=%d',
381             this.session.session_id, widget.id);
382         this.$element.html(QWeb.render('HomeWidget.content', {
383             widget: widget,
384             url: url
385         }));
386     }
387 });
388
389 /*
390  * HomeTiles this client action display either the list of application to
391  * install (if none is installed yet) or a list of root menu items
392  */
393 openerp.web.client_actions.add('default_home', 'session.web_dashboard.ApplicationTiles');
394 openerp.web_dashboard.ApplicationTiles = openerp.web.Widget.extend({
395     template: 'web_dashboard.ApplicationTiles',
396     init: function(parent) {
397         this._super(parent);
398     },
399     start: function() {
400         var self = this;
401         openerp.webclient.menu.do_hide_secondary();
402         var domain = [['application','=',true], ['state','=','installed'], ['name', '!=', 'base']];
403         var ds = new openerp.web.DataSetSearch(this, 'ir.module.module',{},domain);
404         ds.read_slice(['id'], {}, function(result) {
405             if(result.length) {
406                 self.on_installed_database();
407             } else {
408                 self.on_uninstalled_database();
409             }
410         });
411     },
412     on_uninstalled_database: function() {
413         installer = new openerp.web_dashboard.ApplicationInstaller(this);
414         installer.appendTo(this.$element);
415     },
416     on_installed_database: function() {
417         var self = this;
418         var ds = new openerp.web.DataSetSearch(this, 'ir.ui.menu', null, [['parent_id', '=', false]]);
419         var r = ds.read_slice( ['name', 'web_icon_data', 'web_icon_hover_data', 'module'], {}, function (applications) {
420             //// Create a matrix of 3*x applications
421             //var rows = [];
422             //while (applications.length) {
423             //    rows.push(applications.splice(0, 3));
424             //}
425             //var tiles = QWeb.render('ApplicationTiles.content', {rows: rows});
426             var tiles = QWeb.render('ApplicationTiles.content', {applications: applications});
427             $(tiles).appendTo(self.$element).find('.oe_install-module-link').click(function () {
428                 openerp.webclient.menu.on_menu_click(null, $(this).data('menu'))
429             });
430         });
431     }
432 });
433
434 /**
435  * ApplicationInstaller
436  * This client action  display a list of applications to install.
437  */
438 openerp.web.client_actions.add( 'board.application.installer', 'openerp.web_dashboard.ApplicationInstaller');
439 openerp.web_dashboard.ApplicationInstaller = openerp.web.Widget.extend({
440     template: 'web_dashboard.ApplicationInstaller',
441     start: function () {
442         // TODO menu hide
443         var r = this._super();
444         this.action_manager = new openerp.web.ActionManager(this);
445         this.action_manager.appendTo(this.$element.find('.oe_installer'));
446         this.action_manager.do_action({
447             type: 'ir.actions.act_window',
448             res_model: 'ir.module.module',
449             domain: [['application','=',true]],
450             views: [[false, 'kanban']],
451             flags: {
452                 display_title:false,
453                 search_view: false,
454                 views_switcher: false,
455                 action_buttons: false,
456                 sidebar: false,
457                 pager: false
458             }
459         });
460         return r;
461     },
462     stop: function() {
463         this.action_manager.stop();
464         return this._super();
465     }
466 });
467
468
469 };