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