[IMP] makes display smarter list of options in dropdown menu on pivottable widget...
[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         this.model = model;
148         this.fields = options.fields;
149         this.domain = options.domain;
150         this.row_groupby = options.row_groupby;
151         this.col_groupby = options.col_groupby;
152         this.measure = options.measure;
153         this.measure_label = options.measure ? options.fields[options.measure].string : 'Quantity';
154         this.data = [];
155         this.need_redraw = true;
156         this.important_fields = options.important_fields;
157     },
158
159     get_descr: function (field_id) {
160         return this.fields[field_id].string;
161     },
162
163     set_domain: function (domain) {
164         this.domain = domain;
165         this.need_redraw = true;
166     },
167
168     set_row_groupby: function (row_groupby) {
169         this.row_groupby = row_groupby;
170         this.need_redraw = true;
171     },
172
173     set_col_groupby: function (col_groupby) {
174         this.col_groupby = col_groupby;
175         this.need_redraw = true;
176     },
177
178     set_measure: function (measure) {
179         this.measure = measure;
180         this.need_redraw = true;
181     },
182
183     show: function () {
184         if (this.need_redraw) {
185             this.draw();
186             this.need_redraw = false;
187         }
188         this.$el.css('display', 'block');
189     },
190
191     hide: function () {
192         this.$el.css('display', 'none');
193     },
194
195     draw: function() {
196     },
197
198     get_data: function (groupby) {
199         var view_fields = this.row_groupby.concat(this.measure, this.col_groupby);
200         return query_groups(this.model, view_fields, this.domain, groupby);
201     },
202
203 });
204
205  /**
206   * PivotTable widget.  It displays the data in tabular data and allows the
207   * user to drill down and up in the table
208   */
209 var PivotTable = BasicDataView.extend({
210     template: 'pivot_table',
211     rows: [],
212     cols: [],
213     current_row_id : 0,
214
215     events: {
216         'click .graph_border > a' : function (event) {
217             var self = this;
218             event.preventDefault();
219             var row_id = event.target.attributes['data-row-id'].nodeValue;
220
221             var row = this.get_row(row_id);
222             if (row.expanded) {
223                 this.fold_row(row_id);
224             } else {
225                 if (row.path.length < this.row_groupby.length) {
226                     var field_to_expand = this.row_groupby[row.path.length];
227                     this.expand_row(row_id, field_to_expand);
228                 } else {
229                     var already_grouped = self.row_groupby.concat(self.col_groupby);
230                     var possible_groups = _.difference(self.important_fields, already_grouped);
231                     var dropdown_options = {
232                         fields: _.map(possible_groups, function (field) {
233                             return {id: field, value: self.get_descr(field)};
234                         }),
235                         row_id: row_id,
236                     };
237                     this.dropdown = $(QWeb.render('field_selection', dropdown_options));
238                     $(event.target).after(this.dropdown);
239                     $('.field-selection').next('.dropdown-menu').toggle();
240                 }
241             }
242
243     
244         },
245         'click a.field-selection' : function (event) {
246             event.preventDefault();
247             this.dropdown.remove();
248             var row_id = event.target.attributes['data-row-id'].nodeValue;
249             var field_id = event.target.attributes['data-field-id'].nodeValue;
250             this.expand_row(row_id, field_id);
251         },
252     },
253
254     clear_groups: function () {
255         this.row_groupby = [];
256         this.col_groupby = [];
257         this.rows = [];
258         this.cols = [];
259         this.draw();
260     },
261
262     init: function (model, options) {
263         this._super(model, options);
264     },
265
266     generate_id: function () {
267         this.current_row_id += 1;
268         return this.current_row_id - 1;
269     },
270
271     get_row: function (id) {
272         return _.find(this.rows, function(row) {
273             return (row.id == id);
274         });
275     },
276
277     make_cell: function (content, options) {
278         var attrs = ['<td'];
279         if (options && options.is_border) {
280             attrs.push('class="graph_border"');
281         }
282
283         attrs.push('>');
284         if (options && options.indent) {
285             _.each(_.range(options.indent), function () {
286                 attrs.push('<span class="web_graph_indent"></span>');
287             });
288         }
289         if (options && options.foldable) {
290             attrs.push('<a data-row-id="'+ options.row_id + '" href="#" class="icon-plus-sign"> </a>');
291         }
292         return attrs.join(' ') + content + '</td>';
293     },
294
295     make_row: function (data, parent_id) {
296         var has_parent = (parent_id !== undefined);
297         var parent = has_parent ? this.get_row(parent_id) : null;
298         var path;
299         if (has_parent) {
300             path = parent.path.concat(data.attributes.grouped_on);
301         } else if (data.attributes.grouped_on !== undefined) {
302             path = [data.attributes.grouped_on];
303         } else {
304             path = [];
305         }
306
307         var indent_level = has_parent ? parent.path.length : 0;
308         var value = (this.row_groupby.length > 0) ? data.attributes.value[1] : 'Total';
309
310
311         var jquery_row = $('<tr></tr>');
312         var row_id = this.generate_id();
313
314         var header = $(this.make_cell(value, {is_border:true, indent: indent_level, foldable:true, row_id: row_id}));
315         jquery_row.html(header);
316         jquery_row.append(this.make_cell(data.attributes.aggregates[this.measure]));
317
318         var row = {
319             id: row_id,
320             path: path,
321             value: value,
322             expanded: false,
323             parent: parent_id,
324             children: [],
325             html_tr: jquery_row,
326             domain: data.model._domain,
327         };
328         // rows.splice(index of parent if any,0,row);
329         this.rows.push(row);  // to do, insert it properly
330
331         if (this.row_groupby.length === 0) {
332             row.remove_when_expanded = true;
333             row.domain = this.domain;
334         }
335         if (has_parent) {
336             parent.children.push(row.id);
337         }
338         return row;
339     },
340
341     expand_row: function (row_id, field_id) {
342         var self = this;
343         var row = this.get_row(row_id);
344
345         if (row.path.length == this.row_groupby.length) {
346             this.row_groupby.push(field_id);
347         }
348
349         var visible_fields = this.row_groupby.concat(this.col_groupby, this.measure);
350
351         if (row.remove_when_expanded) {
352             this.rows = [];
353         } else {
354             row.expanded = true;
355             row.html_tr.find('.icon-plus-sign')
356                 .removeClass('icon-plus-sign')
357                 .addClass('icon-minus-sign');
358         }
359
360         query_groups(this.model, visible_fields, row.domain, [field_id])
361             .then(function (data) {
362                 _.each(data.reverse(), function (datapt) {
363                     var new_row;
364                     if (row.remove_when_expanded) {
365                         new_row = self.make_row(datapt);
366                         self.$('tr.graph_table_header').after(new_row.html_tr);
367                     } else {
368                         new_row = self.make_row(datapt, row_id);
369                         row.html_tr.after(new_row.html_tr);
370                     }
371                 });
372                 if (row.remove_when_expanded) {
373                     row.html_tr.remove();
374                 }
375         });
376
377     },
378
379     fold_row: function (row_id) {
380         var self = this;
381         var row = this.get_row(row_id);
382
383         _.each(row.children, function (child_row) {
384             self.remove_row(child_row);            
385         });
386         row.children = [];
387
388         row.expanded = false;
389         row.html_tr.find('.icon-minus-sign')
390             .removeClass('icon-minus-sign')
391             .addClass('icon-plus-sign');;
392
393     },
394
395     remove_row: function (row_id) {
396         var self = this;
397         var row = this.get_row(row_id);
398
399         _.each(row.children, function (child_row) {
400             self.remove_row(child_row);
401         });
402
403         row.html_tr.remove();
404     },
405
406     draw: function () {
407         this.get_data(this.row_groupby)
408             .then(this.proxy('build_table'))
409             .done(this.proxy('_draw'));
410     },
411
412     build_table: function (data) {
413         var self = this;
414
415         this.cols = [{
416             path: [],
417             value: this.measure_label,
418             expanded: false,
419             parent: null,
420             children: [],
421             html_tds: [],
422             domain: this.domain,
423             header: $(this.make_cell(this.measure_label, {is_border:true})),
424         }];
425
426         _.each(data, function (datapt) {
427             self.make_row(datapt);
428         });
429     },
430
431     _draw: function () {
432
433         this.$el.empty();
434         var self = this;
435         var header;
436
437         if (this.row_groupby.length > 0) {
438             header = '<tr><td class="graph_border">' +
439                     this.fields[this.row_groupby[0]].string +
440                     '</td><td class="graph_border">' +
441                     this.measure_label +
442                     '</td></tr>';
443         } else {
444             header = '<tr class="graph_table_header"><td class="graph_border">' +
445                     '</td><td class="graph_border">' +
446                     this.measure_label +
447                     '</td></tr>';
448         }
449         this.$el.append(header);
450
451         _.each(this.rows, function (row) {
452             self.$el.append(row.html_tr);
453         });
454
455     }
456 });
457
458  /**
459   * ChartView widget.  It displays the data in chart form, using the nvd3
460   * library.  Various modes include bar charts, pie charts or line charts.
461   */
462 var ChartView = BasicDataView.extend({
463     template: 'chart_view',
464
465     set_mode: function (mode) {
466         this.render = this['render_' + mode];
467         this.need_redraw = true;
468     },
469
470     draw: function () {
471         var self = this;
472         this.$el.empty();
473         this.$el.append('<svg></svg>');
474         this.get_data(this.row_groupby).done(function (data) {
475             self.render(data);
476         });
477     },
478
479     format_data:  function (datapt) {
480         var val = datapt.attributes;
481         return {
482             x: datapt.attributes.value[1],
483             y: this.measure ? val.aggregates[this.measure] : val.length,
484         };
485     },
486
487     render_bar_chart: function (data) {
488         var formatted_data = [{
489                 key: 'Bar chart',
490                 values: _.map(data, this.proxy('format_data')),
491             }];
492
493         nv.addGraph(function () {
494             var chart = nv.models.discreteBarChart()
495                 .tooltips(false)
496                 .showValues(true)
497                 .staggerLabels(true)
498                 .width(650)
499                 .height(400);
500
501             d3.select('.graph_chart svg')
502                 .datum(formatted_data)
503                 .attr('width', 650)
504                 .attr('height', 400)
505                 .call(chart);
506
507             nv.utils.windowResize(chart.update);
508             return chart;
509         });
510     },
511
512     render_line_chart: function (data) {
513         var formatted_data = [{
514                 key: this.measure_label,
515                 values: _.map(data, this.proxy('format_data'))
516             }];
517
518         nv.addGraph(function () {
519             var chart = nv.models.lineChart()
520                 .x(function (d,u) { return u; })
521                 .width(600)
522                 .height(300)
523                 .margin({top: 30, right: 20, bottom: 20, left: 60});
524
525             d3.select('.graph_chart svg')
526                 .attr('width', 600)
527                 .attr('height', 300)
528                 .datum(formatted_data)
529                 .call(chart);
530
531             return chart;
532           });
533     },
534
535     render_pie_chart: function (data) {
536         var formatted_data = _.map(data, this.proxy('format_data'));
537
538         nv.addGraph(function () {
539             var chart = nv.models.pieChart()
540                 .color(d3.scale.category10().range())
541                 .width(650)
542                 .height(400);
543
544             d3.select('.graph_chart svg')
545                 .datum(formatted_data)
546                 .transition().duration(1200)
547                 .attr('width', 650)
548                 .attr('height', 400)
549                 .call(chart);
550
551             nv.utils.windowResize(chart.update);
552             return chart;
553         });
554     },
555
556 });
557
558 /**
559  * Query the server and return a deferred which will return the data
560  * with all the groupbys applied (this is done for now, but the goal
561  * is to modify read_group in order to allow eager and lazy groupbys
562  */
563 function query_groups (model, fields, domain, groupbys) {
564     return model.query(fields)
565         .filter(domain)
566         .group_by(groupbys)
567         .then(function (results) {
568             var non_empty_results = _.filter(results, function (group) {
569                 return group.attributes.length > 0;
570             });
571             if (groupbys.length <= 1) {
572                 return non_empty_results;
573             } else {
574                 var get_subgroups = $.when.apply(null, _.map(non_empty_results, function (result) {
575                     var new_domain = result.model._domain;
576                     var new_groupings = groupbys.slice(1);
577                     return query_groups(model, fields,new_domain, new_groupings).then(function (subgroups) {
578                         result.subgroups_data = subgroups;
579                     });
580                 }));
581                 return get_subgroups.then(function () {
582                     return non_empty_results;
583                 });
584             }
585         });
586 }
587
588
589 };
590