aedbe0f26b3178b0a423bc043928ed6376820292
[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({}, 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.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.dataset = new openerp.web.DataSetSearch(
283                 this, 'ir.actions.todo');
284         this.dataset.domain = [['type', '!=', 'automatic']];
285     },
286     start: function () {
287         this._super();
288         $.when(this.dataset.read_slice(['state', 'action_id', 'category_id']),
289                this.dataset.call('progress'))
290             .then(this.on_records_loaded);
291     },
292     on_records_loaded: function (read_response, progress_response) {
293         var records = read_response,
294            progress = progress_response[0];
295
296         var grouped_todos = _(records).chain()
297             .map(function (record) {
298                 return {
299                     id: record.id,
300                     name: record.action_id[1],
301                     done: record.state !== 'open',
302                     to_do: record.state === 'open',
303                     category: record['category_id'][1] || "Uncategorized"
304                 }
305             })
306             .groupBy(function (record) {return record.category})
307             .value();
308         this.$element.html(QWeb.render('ConfigOverview.content', {
309             completion: 100 * progress.done / progress.total,
310             groups: grouped_todos
311         }));
312         var $progress = this.$element.find('div.oe-config-progress-bar');
313         $progress.progressbar({value: $progress.data('completion')});
314
315         var self = this;
316         this.$element.find('dl')
317             .delegate('input', 'click', function (e) {
318                 // switch todo status
319                 e.stopImmediatePropagation();
320                 var new_state = this.checked ? 'done' : 'open',
321                       todo_id = parseInt($(this).val(), 10);
322                 self.dataset.write(todo_id, {state: new_state}, {}, function () {
323                     self.start();
324                 });
325             })
326             .delegate('li:not(.oe-done)', 'click', function () {
327                 self.widget_parent.widget_parent.widget_parent.do_execute_action({
328                         type: 'object',
329                         name: 'action_launch'
330                     }, self.dataset,
331                     $(this).data('id'), function () {
332                         // after action popup closed, refresh configuration
333                         // thingie
334                         self.start();
335                     });
336             });
337     }
338 });
339
340 /*
341  * Widgets
342  * This client action designed to be used as a dashboard widget display
343  * the html content of a res_widget given as argument
344  */
345 openerp.web.client_actions.add( 'board.home.widgets', 'openerp.web_dashboard.Widget');
346 openerp.web_dashboard.Widget = openerp.web.View.extend(/** @lends openerp.web_dashboard.Widgets# */{
347     template: 'HomeWidget',
348     /**
349      * Initializes a "HomeWidget" client widget: handles the display of a given
350      * res.widget objects in an OpenERP view (mainly a dashboard).
351      *
352      * @constructs openerp.web_dashboard.Widget
353      * @extends openerp.web.View
354      *
355      * @param {Object} parent
356      * @param {Object} options
357      * @param {Number} options.widget_id
358      */
359     init: function (parent, options) {
360         this._super(parent);
361         this.widget_id = options.widget_id;
362     },
363     start: function () {
364         this._super();
365         return new openerp.web.DataSet(this, 'res.widget').read_ids(
366                 [this.widget_id], ['title'], this.on_widget_loaded);
367     },
368     on_widget_loaded: function (widgets) {
369         var widget = widgets[0];
370         var url = _.str.sprintf(
371             '/web_dashboard/widgets/content?session_id=%s&widget_id=%d',
372             this.session.session_id, widget.id);
373         this.$element.html(QWeb.render('HomeWidget.content', {
374             widget: widget,
375             url: url
376         }));
377     }
378 });
379
380 /*
381  * HomeTiles this client action display either the list of application to
382  * install (if none is installed yet) or a list of root menu items
383  */
384 openerp.web.client_actions.add('default_home', 'session.web_dashboard.ApplicationTiles');
385 openerp.web_dashboard.ApplicationTiles = openerp.web.Widget.extend({
386     template: 'web_dashboard.ApplicationTiles',
387     init: function(parent) {
388         this._super(parent);
389     },
390     start: function() {
391         var self = this;
392         var domain = [['application','=',true], ['state','=','installed'], ['name', '!=', 'base']];
393         var ds = new openerp.web.DataSetSearch(this, 'ir.module.module',{},domain);
394         ds.read_slice(['id'], {}, function(result) {
395             if(result.length) {
396                 self.on_installed_database();
397             } else {
398                 self.on_uninstalled_database();
399             }
400         });
401     },
402     on_uninstalled_database: function() {
403         installer = new openerp.web_dashboard.ApplicationInstaller(this);
404         installer.appendTo(this.$element);
405     },
406     on_installed_database: function() {
407         var self = this;
408         var ds = new openerp.web.DataSetSearch(this, 'ir.ui.menu', null, [['parent_id', '=', false]]);
409         var r = ds.read_slice( ['name', 'web_icon_data', 'web_icon_hover_data', 'module'], {}, function (applications) {
410             //// Create a matrix of 3*x applications
411             //var rows = [];
412             //while (applications.length) {
413             //    rows.push(applications.splice(0, 3));
414             //}
415             //var tiles = QWeb.render('ApplicationTiles.content', {rows: rows});
416             var tiles = QWeb.render('ApplicationTiles.content', {applications: applications});
417             $(tiles).appendTo(self.$element).find('.oe_install-module-link').click(function () {
418                 openerp.webclient.menu.on_menu_click(null, $(this).data('menu'))
419             });
420         });
421     }
422 });
423
424 /**
425  * ApplicationInstaller
426  * This client action  display a list of applications to install.
427  */
428 openerp.web.client_actions.add( 'board.application.installer', 'openerp.web_dashboard.ApplicationInstaller');
429 openerp.web_dashboard.ApplicationInstaller = openerp.web.Widget.extend({
430     template: 'web_dashboard.ApplicationInstaller',
431     start: function () {
432         var r = this._super();
433         //$('.secondary_menu', this.$element.closest('.openerp')).hide();
434         this.action_manager = new openerp.web.ActionManager(this);
435         this.action_manager.appendTo(this.$element.find('.oe_installer'));
436         this.action_manager.do_action({
437             type: 'ir.actions.act_window',
438             res_model: 'ir.module.module',
439             domain: [['application','=',true]],
440             views: [[false, 'kanban']],
441             flags: {
442                 display_title:false,
443                 search_view: false,
444                 views_switcher: false,
445                 action_buttons: false,
446                 sidebar: false,
447                 pager: false
448             }
449         });
450         return r;
451     },
452     stop: function() {
453         this.action_manager.stop();
454         return this._super();
455     }
456 });
457
458
459 };