[FIX] forces an update when the user switches back to the graph view, to make sure...
[odoo/odoo.git] / addons / web_graph / static / src / js / graph.js
1 /*---------------------------------------------------------
2  * OpenERP web_graph
3  *---------------------------------------------------------*/
4
5 /* jshint undef: false  */
6
7 openerp.web_graph = function (instance) {
8 'use strict';
9
10 var _lt = instance.web._lt;
11 var _t = instance.web._t;
12 var QWeb = instance.web.qweb;
13
14 instance.web.views.add('graph', 'instance.web_graph.GraphView');
15
16 instance.web_graph.GraphView = instance.web.View.extend({
17     display_name: _lt('Graph'),
18     view_type: 'graph',
19
20     init: function(parent, dataset, view_id, options) {
21         this._super(parent);
22         this.dataset = dataset;
23         this.model = new instance.web.Model(dataset.model, {group_by_no_leaf: true});
24         this.search_view = parent.searchview;
25         this.search_view_groupby = [];
26         this.groupby_mode = 'default';  // 'default' or 'manual'
27         this.default_row_groupby = [];
28         this.default_col_groupby = [];
29         this.search_field = {
30             get_context: this.proxy('get_context'),
31             get_domain: function () {},
32             get_groupby: function () { },
33         };
34     },
35
36     get_context: function (facet) {
37         var col_group_by = _.map(facet.values.models, function (model) {
38             return model.attributes.value.attrs.context.col_group_by;
39         });
40         return {col_group_by : col_group_by};
41     },
42
43     start: function () {
44         var options = {enabled:false};
45         this.graph_widget = new openerp.web_graph.Graph(this, this.model, options);
46         this.graph_widget.appendTo(this.$el);
47         this.graph_widget.pivot.on('groupby_changed', this, this.proxy('register_groupby'));
48         return this.load_view();
49     },
50
51     view_loading: function (fields_view_get) {
52         var self = this,
53             arch = fields_view_get.arch,
54             measure = null,
55             stacked = false;
56
57         if (arch.attrs.type === 'bar' || !_.has(arch.attrs, 'type')) {
58             this.graph_widget.mode = 'bar_chart';
59         }
60         if (arch.attrs.stacked === 'True') {
61             stacked = true;
62         }
63
64         _.each(arch.children, function (field) {
65             if (_.has(field.attrs, 'type')) {
66                 switch (field.attrs.type) {
67                     case 'row':
68                         self.default_row_groupby.push(field.attrs.name);
69                         break;
70                     case 'col':
71                         self.default_col_groupby.push(field.attrs.name);
72                         break;
73                     case 'measure':
74                         measure = field.attrs.name;
75                         break;
76                 }
77             } else {  // old style, kept for backward compatibility
78                 if ('operator' in field.attrs) {
79                     measure = (measure) ? measure : field.attrs.name;
80                 } else {
81                     self.default_row_groupby.push(field.attrs.name);
82                 }
83             }
84         });
85         this.graph_widget.config({
86             measure:measure,
87             update:false,
88             bar_ui: (stacked) ? 'stack' : 'group'
89         });
90     },
91
92     do_search: function (domain, context, group_by) {
93         var col_groupby = context.col_group_by || [],
94             options = {domain:domain};
95
96         this.search_view_groupby = group_by;
97
98         if (group_by.length && this.groupby_mode !== 'manual') {
99             if (_.isEqual(col_groupby, [])) {
100                 col_groupby = this.default_col_groupby;
101             }
102         }
103         if (group_by.length || col_groupby.length) {
104             this.groupby_mode = 'manual';
105         }
106         if (!this.graph_widget.enabled) {
107             options.update = false;
108             options.silent = true;
109         }
110
111         if (this.groupby_mode === 'manual') {
112             options.row_groupby = group_by;
113             options.col_groupby = col_groupby;
114         } else {
115             options.row_groupby = _.toArray(this.default_row_groupby);
116             options.col_groupby = _.toArray(this.default_col_groupby);
117         }
118         this.graph_widget.pivot.config(options);
119
120         if (!this.graph_widget.enabled) {
121             this.graph_widget.activate_display();
122             this.ViewManager.on('switch_mode', this, function () {this.graph_widget.pivot.update_data(); });
123         }
124     },
125
126     do_show: function () {
127         this.do_push_state({});
128         return this._super();
129     },
130
131     register_groupby: function() {
132         var self = this,
133             query = this.search_view.query;
134
135         this.groupby_mode = 'manual';
136         if (_.isEqual(this.search_view_groupby, this.graph_widget.pivot.rows.groupby) ||
137             (!_.has(this.search_view, '_s_groupby'))) {
138             return;
139         }
140         var rows = _.map(this.graph_widget.pivot.rows.groupby, function (group) {
141             return make_facet('GroupBy', group);
142         });
143         var cols = _.map(this.graph_widget.pivot.cols.groupby, function (group) {
144             return make_facet('ColGroupBy', group);
145         });
146
147         query.reset(rows.concat(cols));
148
149         function make_facet (category, fields) {
150             var values,
151                 icon,
152                 backbone_field,
153                 cat_name;
154             if (!(fields instanceof Array)) { fields = [fields]; }
155             if (category === 'GroupBy') {
156                 cat_name = 'group_by';
157                 icon = 'w';
158                 backbone_field = self.search_view._s_groupby;
159             } else {
160                 cat_name = 'col_group_by';
161                 icon = 'f';
162                 backbone_field = self.search_field;
163             }
164             values =  _.map(fields, function (field) {
165                 var context = {};
166                 context[cat_name] = field;
167                 return {label: self.graph_widget.fields[field].string, value: {attrs:{domain: [], context: context}}};
168             });
169             return {category:category, values: values, icon:icon, field: backbone_field};
170         }
171     },
172 });
173
174 instance.web_graph.Graph = instance.web.Widget.extend({
175     template: 'GraphWidget',
176
177     events: {
178         'click .graph_mode_selection li' : 'mode_selection',
179         'click .graph_measure_selection li' : 'measure_selection',
180         'click .graph_options_selection li' : 'option_selection',
181         'click .web_graph_click' : 'header_cell_clicked',
182         'click a.field-selection' : 'field_selection',
183     },
184
185     init: function(parent, model, options) {
186         this._super(parent);
187         this.model = model;
188         this.important_fields = [];
189         this.measure_list = [];
190         this.fields = [];
191         this.pivot = new openerp.web_graph.PivotTable(model, []);
192         this.mode = 'pivot';
193         if (_.has(options, 'mode')) { this.mode = mode; }
194         this.enabled = true;
195         if (_.has(options, 'enabled')) { this.enabled = options.enabled; }
196         this.visible_ui = true;
197         this.bar_ui = 'group'; // group or stack
198         this.config(options || {});
199     },
200
201     // hide ui/show, stacked/grouped
202     config: function (options) {
203         if (_.has(options, 'visible_ui')) {
204             this.visible_ui = options.visible_ui;
205         }
206         if (_.has(options, 'bar_ui')) {
207             this.bar_ui = options.bar_ui;
208         }
209         this.pivot.config(options);
210     },
211
212     start: function() {
213         var self = this;
214         this.table = $('<table></table>');
215         this.$('.graph_main_content').append(this.table);
216         // get the most important fields (of the model) by looking at the
217         // groupby filters defined in the search view
218         var options = {model:this.model, view_type: 'search'},
219             deferred1 = instance.web.fields_view_get(options).then(function (search_view) {
220                 var groups = _.select(search_view.arch.children, function (c) {
221                     return (c.tag == 'group') && (c.attrs.string != 'Display');
222                 });
223                 _.each(groups, function(g) {
224                     _.each(g.children, function (g) {
225                         if (g.attrs.context) {
226                             var field_id = py.eval(g.attrs.context).group_by;
227                             self.important_fields.push(field_id);
228                         }
229                     });
230                 });
231             });
232
233         // get the fields descriptions and measure list from the model
234         var deferred2 = this.model.call('fields_get', []).then(function (fs) {
235             self.fields = fs;
236             var temp = _.map(fs, function (field, name) {
237                 return {name:name, type: field.type};
238             });
239             temp = _.filter(temp, function (field) {
240                 return (((field.type === 'integer') || (field.type === 'float')) && (field.name !== 'id'));
241             });
242             self.measure_list = _.map(temp, function (field) {
243                 return field.name;
244             });
245
246             var measure_selection = self.$('.graph_measure_selection');
247             _.each(self.measure_list, function (measure) {
248                 var choice = $('<a></a>').attr('data-choice', measure)
249                                          .attr('href', '#')
250                                          .append(self.fields[measure].string);
251                 measure_selection.append($('<li></li>').append(choice));
252             });
253         });
254
255         return $.when(deferred1, deferred2).then(function () {
256             if (this.enabled) {
257                 this.activate_display();
258             }
259         });
260     },
261
262     activate_display: function () {
263         this.pivot.on('redraw_required', this, this.proxy('display_data'));
264         this.pivot.update_data();
265         this.enabled = true;
266         instance.web.bus.on('click', this, function () {
267             if (this.dropdown) {
268                 this.dropdown.remove();
269                 this.dropdown = null;
270             }
271         });
272     },
273
274     display_data: function () {
275         this.$('.graph_main_content svg').remove();
276         this.$('.graph_main_content div').remove();
277         this.table.empty();
278
279         if (this.visible_ui) {
280             this.$('.graph_header').css('display', 'block');
281         } else {
282             this.$('.graph_header').css('display', 'none');
283         }
284         if (this.pivot.no_data) {
285             this.$('.graph_main_content').append($(QWeb.render('graph_no_data')));
286             // var msg = 'No data available. Try to remove any filter or add some data.';
287             // this.table.append($('<tr><td>' + msg + '</td></tr>'));
288         } else {
289             var table_modes = ['pivot', 'heatmap', 'row_heatmap', 'col_heatmap'];
290             if (_.contains(table_modes, this.mode)) {
291                 this.draw_table();
292             } else {
293                 this.$('.graph_main_content').append($('<div><svg></svg></div>'));
294                 this.svg = this.$('.graph_main_content svg')[0];
295                 this.width = this.$el.width();
296                 this.height = Math.min(Math.max(document.documentElement.clientHeight - 116 - 60, 250), Math.round(0.8*this.$el.width()));
297                 this[this.mode]();
298             }
299         }
300     },
301
302     mode_selection: function (event) {
303         event.preventDefault();
304         var mode = event.target.attributes['data-mode'].nodeValue;
305         this.mode = mode;
306         this.display_data();
307     },
308
309     measure_selection: function (event) {
310         event.preventDefault();
311         var measure = event.target.attributes['data-choice'].nodeValue;
312         var actual_measure = (measure === '__count') ? null : measure;
313         this.pivot.config({measure:actual_measure});
314     },
315
316     option_selection: function (event) {
317         event.preventDefault();
318         switch (event.target.attributes['data-choice'].nodeValue) {
319             case 'swap_axis':
320                 this.pivot.swap_axis();
321                 break;
322             case 'expand_all':
323                 this.pivot.rows.headers = null;
324                 this.pivot.cols.headers = null;
325                 this.pivot.update_data();
326                 break;
327             case 'update_values':
328                 this.pivot.update_data();
329                 break;
330             case 'export_data':
331                 // Export code...  To do...
332                 break;
333         }
334     },
335
336     header_cell_clicked: function (event) {
337         event.preventDefault();
338         event.stopPropagation();
339         var id = event.target.attributes['data-id'].nodeValue,
340             header = this.pivot.get_header(id),
341             self = this;
342
343         if (header.is_expanded) {
344             this.pivot.fold(header);
345         } else {
346             if (header.path.length < header.root.groupby.length) {
347                 var field = header.root.groupby[header.path.length];
348                 this.pivot.expand(id, field);
349             } else {
350                 if (!this.important_fields.length) {
351                     return;
352                 }
353                 var fields = _.map(this.important_fields, function (field) {
354                         return {id: field, value: self.fields[field].string};
355                 });
356                 this.dropdown = $(QWeb.render('field_selection', {fields:fields, header_id:id}));
357                 $(event.target).after(this.dropdown);
358                 this.dropdown.css({position:'absolute',
359                                    left:event.pageX,
360                                    top:event.pageY});
361                 this.$('.field-selection').next('.dropdown-menu').toggle();
362             }
363         }
364     },
365
366     field_selection: function (event) {
367         var id = event.target.attributes['data-id'].nodeValue,
368             field_id = event.target.attributes['data-field-id'].nodeValue;
369         event.preventDefault();
370         this.pivot.expand(id, field_id);
371     },
372
373 /******************************************************************************
374  * Drawing pivot table methods...
375  ******************************************************************************/
376     draw_table: function () {
377         this.pivot.rows.main.title = 'Total';
378         this.pivot.cols.main.title = this.measure_label();
379         this.draw_top_headers();
380         _.each(this.pivot.rows.headers, this.proxy('draw_row'));
381     },
382
383     measure_label: function () {
384         return (this.pivot.measure) ? this.fields[this.pivot.measure].string : 'Quantity';
385     },
386
387     make_border_cell: function (colspan, rowspan) {
388         return $('<td></td>').addClass('graph_border')
389                              .attr('colspan', colspan)
390                              .attr('rowspan', rowspan);
391     },
392
393     make_header_title: function (header) {
394         return $('<span> </span>')
395             .addClass('web_graph_click')
396             .attr('href', '#')
397             .addClass((header.is_expanded) ? 'fa fa-minus-square' : 'fa fa-plus-square')
398             .append((header.title !== undefined) ? header.title : 'Undefined');
399     },
400
401     draw_top_headers: function () {
402         var self = this,
403             pivot = this.pivot,
404             height = _.max(_.map(pivot.cols.headers, function(g) {return g.path.length;})),
405             header_cells = [[this.make_border_cell(1, height)]];
406
407         function set_dim (cols) {
408             _.each(cols.children, set_dim);
409             if (cols.children.length === 0) {
410                 cols.height = height - cols.path.length + 1;
411                 cols.width = 1;
412             } else {
413                 cols.height = 1;
414                 cols.width = _.reduce(cols.children, function (sum,c) { return sum + c.width;}, 0);
415             }
416         }
417
418         function make_col_header (col) {
419             var cell = self.make_border_cell(col.width, col.height);
420             return cell.append(self.make_header_title(col).attr('data-id', col.id));
421         }
422
423         function make_cells (queue, level) {
424             var col = queue[0];
425             queue = _.rest(queue).concat(col.children);
426             if (col.path.length == level) {
427                 _.last(header_cells).push(make_col_header(col));
428             } else {
429                 level +=1;
430                 header_cells.push([make_col_header(col)]);
431             }
432             if (queue.length !== 0) {
433                 make_cells(queue, level);
434             }
435         }
436
437         set_dim(pivot.cols.main);  // add width and height info to columns headers
438         if (pivot.cols.main.children.length === 0) {
439             make_cells(pivot.cols.headers, 0);
440         } else {
441             make_cells(pivot.cols.main.children, 1);
442             header_cells[0].push(self.make_border_cell(1, height).append('Total').css('font-weight', 'bold'));
443         }
444
445         _.each(header_cells, function (cells) {
446             self.table.append($('<tr></tr>').append(cells));
447         });
448     },
449
450     get_measure_type: function () {
451         var measure = this.pivot.measure;
452         return (measure) ? this.fields[measure].type : 'integer';
453     },
454
455     draw_row: function (row) {
456         var self = this,
457             pivot = this.pivot,
458             measure_type = this.get_measure_type(),
459             html_row = $('<tr></tr>'),
460             row_header = this.make_border_cell(1,1)
461                 .append(this.make_header_title(row).attr('data-id', row.id))
462                 .addClass('graph_border');
463
464         for (var i in _.range(row.path.length)) {
465             row_header.prepend($('<span/>', {class:'web_graph_indent'}));
466         }
467
468         html_row.append(row_header);
469
470         _.each(pivot.cols.headers, function (col) {
471             if (col.children.length === 0) {
472                 var value = pivot.get_value(row.id, col.id),
473                     cell = make_cell(value, col);
474                 html_row.append(cell);
475             }
476         });
477
478         if (pivot.cols.main.children.length > 0) {
479             var cell = make_cell(pivot.get_total(row), pivot.cols.main)
480                             .css('font-weight', 'bold');
481             html_row.append(cell);
482         }
483
484         this.table.append(html_row);
485
486         function make_cell (value, col) {
487             var color,
488                 total,
489                 cell = $('<td></td>');
490             if ((self.mode === 'pivot') && (row.is_expanded) && (row.path.length <=2)) {
491                 color = row.path.length * 5 + 240;
492                 cell.css('background-color', $.Color(color, color, color));
493             }
494             if (value === undefined) {
495                 return cell;
496             }
497             cell.append(instance.web.format_value(value, {type: measure_type}));
498             if (self.mode === 'heatmap') {
499                 total = pivot.get_total();
500                 color = Math.floor(50 + 205*(total - value)/total);
501                 cell.css('background-color', $.Color(255, color, color));
502             }
503             if (self.mode === 'row_heatmap') {
504                 total = pivot.get_total(row);
505                 color = Math.floor(50 + 205*(total - value)/total);
506                 cell.css('background-color', $.Color(255, color, color));
507             }
508             if (self.mode === 'col_heatmap') {
509                 total = pivot.get_total(col);
510                 color = Math.floor(50 + 205*(total - value)/total);
511                 cell.css('background-color', $.Color(255, color, color));
512             }
513             return cell;
514         }
515     },
516
517 /******************************************************************************
518  * Drawing charts methods...
519  ******************************************************************************/
520     bar_chart: function () {
521         var self = this,
522             dim_x = this.pivot.rows.groupby.length,
523             dim_y = this.pivot.cols.groupby.length,
524             data;
525
526         // No groupby **************************************************************
527         if ((dim_x === 0) && (dim_y === 0)) {
528             data = [{key: 'Total', values:[{
529                 x: 'Total',
530                 y: this.pivot.get_value(this.pivot.rows.main.id, this.pivot.cols.main.id),
531             }]}];
532         // Only column groupbys ****************************************************
533         } else if ((dim_x === 0) && (dim_y >= 1)){
534             data =  _.map(this.pivot.get_columns_depth(1), function (header) {
535                 return {
536                     key: header.title,
537                     values: [{x:header.root.main.title, y: self.pivot.get_total(header)}]
538                 };
539             });
540         // Just 1 row groupby ******************************************************
541         } else if ((dim_x === 1) && (dim_y === 0))  {
542             data = _.map(this.pivot.rows.main.children, function (pt) {
543                 var value = self.pivot.get_value(pt.id, self.pivot.cols.main.id),
544                     title = (pt.title !== undefined) ? pt.title : 'Undefined';
545                 return {x: title, y: value};
546             });
547             data = [{key: this.measure_label(), values:data}];
548         // 1 row groupby and some col groupbys**************************************
549         } else if ((dim_x === 1) && (dim_y >= 1))  {
550             data = _.map(this.pivot.get_columns_depth(1), function (colhdr) {
551                 var values = _.map(self.pivot.get_rows_depth(1), function (header) {
552                     return {
553                         x: header.title || 'Undefined',
554                         y: self.pivot.get_value(header.id, colhdr.id, 0)
555                     };
556                 });
557                 return {key: colhdr.title || 'Undefined', values: values};
558             });
559         // At least two row groupby*************************************************
560         } else {
561             var keys = _.uniq(_.map(this.pivot.get_rows_depth(2), function (hdr) {
562                 return hdr.title || 'Undefined';
563             }));
564             data = _.map(keys, function (key) {
565                 var values = _.map(self.pivot.get_rows_depth(1), function (hdr) {
566                     var subhdr = _.find(hdr.children, function (child) {
567                         return ((child.title === key) || ((child.title === undefined) && (key === 'Undefined')));
568                     });
569                     return {
570                         x: hdr.title || 'Undefined',
571                         y: (subhdr) ? self.pivot.get_total(subhdr) : 0
572                     };
573                 });
574                 return {key:key, values: values};
575             });
576         }
577
578         nv.addGraph(function () {
579           var chart = nv.models.multiBarChart()
580                 .width(self.width)
581                 .height(self.height)
582                 .stacked(self.bar_ui === 'stack')
583                 .staggerLabels(true);
584
585             if (dim_x === 1 && dim_y === 0) { chart.showControls(false); }
586
587             d3.select(self.svg)
588                 .datum(data)
589                 .attr('width', self.width)
590                 .attr('height', self.height)
591                 .call(chart);
592
593             nv.utils.windowResize(chart.update);
594             return chart;
595         });
596
597     },
598
599     line_chart: function () {
600         var self = this,
601             dim_x = this.pivot.rows.groupby.length,
602             dim_y = this.pivot.cols.groupby.length;
603
604         var data = _.map(this.pivot.get_cols_leaves(), function (col) {
605             var values = _.map(self.pivot.get_rows_depth(dim_x), function (row) {
606                 return {x: row.title, y: self.pivot.get_value(row.id,col.id, 0)};
607             });
608             var title = _.map(col.path, function (p) {
609                 return p || 'Undefined';
610             }).join('/');
611             if (dim_y === 0) {
612                 title = self.measure_label();
613             }
614             return {values: values, key: title};
615         });
616
617         nv.addGraph(function () {
618             var chart = nv.models.lineChart()
619                 .x(function (d,u) { return u; })
620                 .width(self.width)
621                 .height(self.height)
622                 .margin({top: 30, right: 20, bottom: 20, left: 60});
623
624             d3.select(self.svg)
625                 .attr('width', self.width)
626                 .attr('height', self.height)
627                 .datum(data)
628                 .call(chart);
629
630             return chart;
631           });
632     },
633
634     pie_chart: function () {
635         var self = this,
636             dim_x = this.pivot.rows.groupby.length;
637
638         var data = _.map(this.pivot.get_rows_leaves(), function (row) {
639             var title = _.map(row.path, function (p) {
640                 return p || 'Undefined';
641             }).join('/');
642             if (dim_x === 0) {
643                 title = self.measure_label;
644             }
645             return {x: title, y: self.pivot.get_total(row)};
646         });
647
648         nv.addGraph(function () {
649             var chart = nv.models.pieChart()
650                 .color(d3.scale.category10().range())
651                 .width(self.width)
652                 .height(self.height);
653
654             d3.select(self.svg)
655                 .datum(data)
656                 .transition().duration(1200)
657                 .attr('width', self.width)
658                 .attr('height', self.height)
659                 .call(chart);
660
661             nv.utils.windowResize(chart.update);
662             return chart;
663         });
664     },
665
666 });
667
668 };
669
670
671
672
673
674
675
676