[IMP] smarter behavior when unfolding/refolding: check 'unfolding' level and do not...
[odoo/odoo.git] / addons / web_graph / static / src / js / graph.js
1 /*---------------------------------------------------------
2  * OpenERP web_graph
3  *---------------------------------------------------------*/
4
5 /* jshint undef: false  */
6
7
8 openerp.web_graph = function (instance) {
9 'use strict';
10
11 var _lt = instance.web._lt;
12 var _t = instance.web._t;
13 var QWeb = instance.web.qweb;
14
15 instance.web.views.add('graph', 'instance.web_graph.GraphView');
16
17  /**
18   * GraphView view.  It mostly contains two widgets (PivotTable and ChartView)
19   * and some data.
20   */
21 instance.web_graph.GraphView = instance.web.View.extend({
22     template: 'GraphView',
23     display_name: _lt('Graph'),
24     view_type: 'graph',
25     mode: 'pivot',   // pivot => display pivot table, chart => display chart
26
27     events: {
28         'click .graph_mode_selection li' : function (event) {
29             event.preventDefault();
30             var view_mode = event.target.attributes['data-mode'].nodeValue;
31             if (view_mode === 'data') {
32                 this.mode = 'pivot';
33             } else {
34                 this.mode = 'chart';
35                 this.chart_view.set_mode(view_mode);
36             }
37             this.display_data();
38         },
39         'click .graph_clear_groups' : function (event) {
40             this.pivot_table.clear_groups();
41         },
42     },
43
44     view_loading: function (fields_view_get) {
45         var self = this;
46         var model = new instance.web.Model(fields_view_get.model, {group_by_no_leaf: true});
47         var options = {};
48         options.domain = [];
49         options.col_groupby = [];
50
51         // get the default groupbys and measure defined in the field view
52         options.measure = null;
53         options.row_groupby = [];
54         _.each(fields_view_get.arch.children, function (field) {
55             if ('name' in field.attrs) {
56                 if ('operator' in field.attrs) {
57                     options.measure = field.attrs.name;
58                 } else {
59                     options.row_groupby.push(field.attrs.name);
60                 }
61             }
62         });
63
64         // get the most important fields (of the model) by looking at the
65         // groupby filters defined in the search view
66         options.important_fields = [];
67         var load_view = instance.web.fields_view_get({
68             model: model,
69             view_type: 'search',
70         });
71
72         var important_fields_def = $.when(load_view).then(function (search_view) {
73             var groups = _.select(search_view.arch.children, function (c) {
74                 return (c.tag == 'group') && (c.attrs.string != 'Display');
75             });
76
77             _.each(groups, function(g) {
78                 _.each(g.children, function (g) {
79                     if (g.attrs.context) {
80                         var field_id = py.eval(g.attrs.context).group_by;
81                         options.important_fields.push(field_id);
82                     }
83                 });
84             });
85         });
86
87         // get the fields descriptions from the model
88         var field_descr_def = model.call('fields_get', [])
89             .then(function (fields) { options.fields = fields; });
90
91
92         return $.when(important_fields_def, field_descr_def)
93             .then(function () {
94                 self.pivot_table = new PivotTable(model, options);
95                 self.chart_view = new ChartView(model, options);
96             })
97             .then(function () {
98                 return self.pivot_table.appendTo('.graph_main_content');
99             })
100             .then(function() {
101                 return self.chart_view.appendTo('.graph_main_content');
102             });
103     },
104
105     display_data : function () {
106         if (this.mode === 'pivot') {
107             this.chart_view.hide();
108             this.pivot_table.show();
109         } else {
110             this.pivot_table.hide();
111             this.chart_view.show();
112         }
113     },
114
115     do_search: function (domain, context, group_by) {
116         this.domain = new instance.web.CompoundDomain(domain);
117         this.pivot_table.set_domain(domain);
118         this.chart_view.set_domain(domain);
119         this.display_data();
120     },
121
122     do_show: function () {
123         this.do_push_state({});
124         return this._super();
125     },
126
127 });
128
129  /**
130   * BasicDataView widget.  Basic widget to manage show/hide functionality
131   * and to initialize some attributes.  It is inherited by PivotTable 
132   * and ChartView widget.
133   */
134 var BasicDataView = instance.web.Widget.extend({
135
136     need_redraw: false,
137
138     // Input parameters: 
139     //      model: model to display
140     //      fields: dictionary returned by field_get on model (desc of model)
141     //      domain: constraints on model records 
142     //      row_groupby: groubys on rows (so, row headers in the pivot table)
143     //      col_groupby: idem, but on col
144     //      measure: quantity to display. either a field from the model, or 
145     //            null, in which case we use the "count" measure
146     init: function (model, options) {
147         var self = this;
148         this.model = model;
149         this.fields = options.fields;
150         this.domain = options.domain;
151         this.groupby = {
152             row: options.row_groupby,
153             col: options.col_groupby,
154         };
155
156         this.measure = options.measure;
157         this.measure_label = options.measure ? options.fields[options.measure].string : 'Quantity';
158         this.data = [];
159         this.need_redraw = true;
160         this.important_fields = options.important_fields;
161     },
162
163     get_descr: function (field_id) {
164         return this.fields[field_id].string;
165     },
166
167     set_domain: function (domain) {
168         this.domain = domain;
169         this.need_redraw = true;
170     },
171
172     set_row_groupby: function (row_groupby) {
173         this.groupby.row = row_groupby;
174         this.need_redraw = true;
175     },
176
177     set_col_groupby: function (col_groupby) {
178         this.groupby.col = col_groupby;
179         this.need_redraw = true;
180     },
181
182     set_measure: function (measure) {
183         this.measure = measure;
184         this.need_redraw = true;
185     },
186
187     show: function () {
188         if (this.need_redraw) {
189             this.draw();
190             this.need_redraw = false;
191         }
192         this.$el.css('display', 'block');
193     },
194
195     hide: function () {
196         this.$el.css('display', 'none');
197     },
198
199     draw: function() {
200     },
201
202     get_data: function (groupby) {
203         var view_fields = this.groupby.row.concat(this.measure, this.groupby.col);
204         return query_groups(this.model, view_fields, this.domain, groupby);
205     },
206
207 });
208
209  /**
210   * PivotTable widget.  It displays the data in tabular data and allows the
211   * user to drill down and up in the table
212   */
213 var PivotTable = BasicDataView.extend({
214     template: 'pivot_table',
215     rows: [],
216     cols: [],
217     current_row_id : 0,
218
219     events: {
220         'click .graph_border > a' : function (event) {
221             var self = this;
222             event.preventDefault();
223             var row_id = event.target.attributes['data-row-id'].nodeValue;
224
225             var row = this.get_row(row_id);
226             if (row.expanded) {
227                 this.fold_row(row_id);
228             } else {
229                 if (row.path.length < this.groupby.row.length) {
230                     var field_to_expand = this.groupby.row[row.path.length];
231                     this.expand_row(row_id, field_to_expand);
232                 } else {
233                     var already_grouped = self.groupby.row.concat(self.groupby.col);
234                     var possible_groups = _.difference(self.important_fields, already_grouped);
235                     var dropdown_options = {
236                         fields: _.map(possible_groups, function (field) {
237                             return {id: field, value: self.get_descr(field)};
238                         }),
239                         row_id: row_id,
240                     };
241                     this.dropdown = $(QWeb.render('field_selection', dropdown_options));
242                     $(event.target).after(this.dropdown);
243                     $('.field-selection').next('.dropdown-menu').toggle();
244                 }
245             }
246
247     
248         },
249         'click a.field-selection' : function (event) {
250             event.preventDefault();
251             this.dropdown.remove();
252             var row_id = event.target.attributes['data-row-id'].nodeValue;
253             var field_id = event.target.attributes['data-field-id'].nodeValue;
254             this.expand_row(row_id, field_id);
255         },
256     },
257
258     clear_groups: function () {
259         this.groupby.row = [];
260         this.groupby.col = [];
261         this.rows = [];
262         this.cols = [];
263         this.draw();
264     },
265
266     init: function (model, options) {
267         this._super(model, options);
268     },
269
270     generate_id: function () {
271         this.current_row_id += 1;
272         return this.current_row_id - 1;
273     },
274
275     get_row: function (id) {
276         return _.find(this.rows, function(row) {
277             return (row.id == id);
278         });
279     },
280
281     make_cell: function (content, options) {
282         var attrs = ['<td'];
283         if (options && options.is_border) {
284             attrs.push('class="graph_border"');
285         }
286
287         attrs.push('>');
288         if (options && options.indent) {
289             _.each(_.range(options.indent), function () {
290                 attrs.push('<span class="web_graph_indent"></span>');
291             });
292         }
293         if (options && options.foldable) {
294             attrs.push('<a data-row-id="'+ options.row_id + '" href="#" class="icon-plus-sign"> </a>');
295         }
296         return attrs.join(' ') + content + '</td>';
297     },
298
299     make_row: function (data, parent_id) {
300         var has_parent = (parent_id !== undefined);
301         var parent = has_parent ? this.get_row(parent_id) : null;
302         var path;
303         if (has_parent) {
304             path = parent.path.concat(data.attributes.grouped_on);
305         } else if (data.attributes.grouped_on !== undefined) {
306             path = [data.attributes.grouped_on];
307         } else {
308             path = [];
309         }
310
311         var indent_level = has_parent ? parent.path.length : 0;
312         var value = (this.groupby.row.length > 0) ? data.attributes.value[1] : 'Total';
313
314
315         var jquery_row = $('<tr></tr>');
316         var row_id = this.generate_id();
317
318         var header = $(this.make_cell(value, {is_border:true, indent: indent_level, foldable:true, row_id: row_id}));
319         jquery_row.html(header);
320         jquery_row.append(this.make_cell(data.attributes.aggregates[this.measure]));
321
322         var row = {
323             id: row_id,
324             path: path,
325             value: value,
326             expanded: false,
327             parent: parent_id,
328             children: [],
329             html_tr: jquery_row,
330             domain: data.model._domain,
331         };
332         // rows.splice(index of parent if any,0,row);
333         this.rows.push(row);  // to do, insert it properly
334
335         if (this.groupby.row.length === 0) {
336             row.remove_when_expanded = true;
337             row.domain = this.domain;
338         }
339         if (has_parent) {
340             parent.children.push(row.id);
341         }
342         return row;
343     },
344
345     expand_row: function (row_id, field_id) {
346         var self = this;
347         var row = this.get_row(row_id);
348
349         if (row.path.length == this.groupby.row.length) {
350             this.groupby.row.push(field_id);
351         }
352
353         var visible_fields = this.groupby.row.concat(this.groupby.col, this.measure);
354
355         if (row.remove_when_expanded) {
356             this.rows = [];
357         } else {
358             row.expanded = true;
359             row.html_tr.find('.icon-plus-sign')
360                 .removeClass('icon-plus-sign')
361                 .addClass('icon-minus-sign');
362         }
363
364         query_groups(this.model, visible_fields, row.domain, [field_id])
365             .then(function (data) {
366                 _.each(data.reverse(), function (datapt) {
367                     var new_row;
368                     if (row.remove_when_expanded) {
369                         new_row = self.make_row(datapt);
370                         self.$('tr.graph_table_header').after(new_row.html_tr);
371                     } else {
372                         new_row = self.make_row(datapt, row_id);
373                         row.html_tr.after(new_row.html_tr);
374                     }
375                 });
376                 if (row.remove_when_expanded) {
377                     row.html_tr.remove();
378                 }
379         });
380
381     },
382
383     fold_row: function (row_id) {
384         var self = this;
385         var row = this.get_row(row_id);
386
387         _.each(row.children, function (child_row) {
388             self.remove_row(child_row);
389         });
390         row.children = [];
391
392         row.expanded = false;
393         row.html_tr.find('.icon-minus-sign')
394             .removeClass('icon-minus-sign')
395             .addClass('icon-plus-sign');
396
397         var fold_levels = _.map(self.rows, function(g) {return g.path.length;});
398         var new_groupby_length = _.reduce(fold_levels, function (x, y) {
399             return Math.max(x,y);
400         }, 0);
401
402         this.groupby.row.splice(new_groupby_length);
403     },
404
405     remove_row: function (row_id) {
406         var self = this;
407         var row = this.get_row(row_id);
408
409         _.each(row.children, function (child_row) {
410             self.remove_row(child_row);
411         });
412
413         row.html_tr.remove();
414         removeFromArray(this.rows, row);
415     },
416
417     draw: function () {
418         this.get_data(this.groupby.row)
419             .then(this.proxy('build_table'))
420             .done(this.proxy('_draw'));
421     },
422
423     build_table: function (data) {
424         var self = this;
425
426         this.cols = [{
427             path: [],
428             value: this.measure_label,
429             expanded: false,
430             parent: null,
431             children: [],
432             html_tds: [],
433             domain: this.domain,
434             header: $(this.make_cell(this.measure_label, {is_border:true})),
435         }];
436
437         _.each(data, function (datapt) {
438             self.make_row(datapt);
439         });
440     },
441
442     _draw: function () {
443
444         this.$el.empty();
445         var self = this;
446         var header;
447
448         if (this.groupby.row.length > 0) {
449             header = '<tr><td class="graph_border">' +
450                     this.fields[this.groupby.row[0]].string +
451                     '</td><td class="graph_border">' +
452                     this.measure_label +
453                     '</td></tr>';
454         } else {
455             header = '<tr class="graph_table_header"><td class="graph_border">' +
456                     '</td><td class="graph_border">' +
457                     this.measure_label +
458                     '</td></tr>';
459         }
460         this.$el.append(header);
461
462         _.each(this.rows, function (row) {
463             self.$el.append(row.html_tr);
464         });
465
466     }
467 });
468
469  /**
470   * ChartView widget.  It displays the data in chart form, using the nvd3
471   * library.  Various modes include bar charts, pie charts or line charts.
472   */
473 var ChartView = BasicDataView.extend({
474     template: 'chart_view',
475
476     set_mode: function (mode) {
477         this.render = this['render_' + mode];
478         this.need_redraw = true;
479     },
480
481     draw: function () {
482         var self = this;
483         this.$el.empty();
484         this.$el.append('<svg></svg>');
485         this.get_data(this.groupby.row).done(function (data) {
486             self.render(data);
487         });
488     },
489
490     format_data:  function (datapt) {
491         var val = datapt.attributes;
492         return {
493             x: datapt.attributes.value[1],
494             y: this.measure ? val.aggregates[this.measure] : val.length,
495         };
496     },
497
498     render_bar_chart: function (data) {
499         var formatted_data = [{
500                 key: 'Bar chart',
501                 values: _.map(data, this.proxy('format_data')),
502             }];
503
504         nv.addGraph(function () {
505             var chart = nv.models.discreteBarChart()
506                 .tooltips(false)
507                 .showValues(true)
508                 .staggerLabels(true)
509                 .width(650)
510                 .height(400);
511
512             d3.select('.graph_chart svg')
513                 .datum(formatted_data)
514                 .attr('width', 650)
515                 .attr('height', 400)
516                 .call(chart);
517
518             nv.utils.windowResize(chart.update);
519             return chart;
520         });
521     },
522
523     render_line_chart: function (data) {
524         var formatted_data = [{
525                 key: this.measure_label,
526                 values: _.map(data, this.proxy('format_data'))
527             }];
528
529         nv.addGraph(function () {
530             var chart = nv.models.lineChart()
531                 .x(function (d,u) { return u; })
532                 .width(600)
533                 .height(300)
534                 .margin({top: 30, right: 20, bottom: 20, left: 60});
535
536             d3.select('.graph_chart svg')
537                 .attr('width', 600)
538                 .attr('height', 300)
539                 .datum(formatted_data)
540                 .call(chart);
541
542             return chart;
543           });
544     },
545
546     render_pie_chart: function (data) {
547         var formatted_data = _.map(data, this.proxy('format_data'));
548
549         nv.addGraph(function () {
550             var chart = nv.models.pieChart()
551                 .color(d3.scale.category10().range())
552                 .width(650)
553                 .height(400);
554
555             d3.select('.graph_chart svg')
556                 .datum(formatted_data)
557                 .transition().duration(1200)
558                 .attr('width', 650)
559                 .attr('height', 400)
560                 .call(chart);
561
562             nv.utils.windowResize(chart.update);
563             return chart;
564         });
565     },
566
567 });
568
569 // utility
570 function removeFromArray(array, element) {
571     var index = array.indexOf(element);
572     if (index > -1) {
573         array.splice(index, 1);
574     }
575 }
576
577 /**
578  * Query the server and return a deferred which will return the data
579  * with all the groupbys applied (this is done for now, but the goal
580  * is to modify read_group in order to allow eager and lazy groupbys
581  */
582 function query_groups (model, fields, domain, groupbys) {
583     return model.query(fields)
584         .filter(domain)
585         .group_by(groupbys)
586         .then(function (results) {
587             var non_empty_results = _.filter(results, function (group) {
588                 return group.attributes.length > 0;
589             });
590             if (groupbys.length <= 1) {
591                 return non_empty_results;
592             } else {
593                 var get_subgroups = $.when.apply(null, _.map(non_empty_results, function (result) {
594                     var new_domain = result.model._domain;
595                     var new_groupings = groupbys.slice(1);
596                     return query_groups(model, fields,new_domain, new_groupings).then(function (subgroups) {
597                         result.subgroups_data = subgroups;
598                     });
599                 }));
600                 return get_subgroups.then(function () {
601                     return non_empty_results;
602                 });
603             }
604         });
605 }
606
607
608 };
609