[REF] preparation work to allows row expansion to query and display correct data...
[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 a widget (PivotTable), some data, and 
19   * calls to charts function.
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, bar_chart, line_chart or pie_chart
26     pivot_table: null,
27
28     events: {
29         'click .graph_mode_selection li' : function (event) {
30             event.preventDefault();
31             this.mode = event.target.attributes['data-mode'].nodeValue;
32             this.display_data();
33         },
34     },
35
36     view_loading: function (fields_view_get) {
37         var self = this;
38         var model = new instance.web.Model(fields_view_get.model, {group_by_no_leaf: true});
39         var domain = [];
40         var col_groupby = [];
41         var row_groupby = [];
42         var measure = null;
43         var fields;
44         var important_fields = [];
45
46         // get the default groupbys and measure defined in the field view
47         _.each(fields_view_get.arch.children, function (field) {
48             if ('name' in field.attrs) {
49                 if ('operator' in field.attrs) {
50                     measure = field.attrs.name;
51                 } else {
52                     row_groupby.push(field.attrs.name);
53                 }
54             }
55         });
56
57         // get the most important fields (of the model) by looking at the
58         // groupby filters defined in the search view
59         var load_view = instance.web.fields_view_get({
60             model: model,
61             view_type: 'search',
62         });
63
64         var important_fields_def = $.when(load_view).then(function (search_view) {
65             var groups = _.select(search_view.arch.children, function (c) {
66                 return (c.tag == 'group') && (c.attrs.string != 'Display');
67             });
68             _.each(groups, function(g) {
69                 _.each(g.children, function (g) {
70                     if (g.attrs.context) {
71                         var field_id = py.eval(g.attrs.context).group_by;
72                         important_fields.push(field_id);
73                     }
74                 });
75             });
76         });
77
78         // get the fields descriptions from the model
79         var field_descr_def = model.call('fields_get', [])
80             .then(function (fs) { fields = fs; });
81
82         return $.when(important_fields_def, field_descr_def)
83             .then(function () {
84                 self.data = {
85                     model: model,
86                     domain: domain,
87                     fields: fields,
88                     important_fields: important_fields,
89                     measure: measure,
90                     measure_label: fields[measure].string,
91                     col_groupby: [],
92                     row_groupby: row_groupby,
93                     groups: [],
94                     total: null,
95                 };
96             });
97     },
98
99     display_data : function () {
100         var content = this.$el.filter('.graph_main_content');
101         content.find('svg').remove();
102         var self = this;
103         if (this.mode === 'pivot') {
104             this.pivot_table.show();
105         } else {
106             this.pivot_table.hide();
107             content.append('<svg></svg>');
108             var view_fields = this.data.row_groupby.concat(this.data.measure, this.data.col_groupby);
109             query_groups(this.data.model, view_fields, this.data.domain, this.data.row_groupby).then(function (groups) {
110                 Charts[self.mode](groups, self.data.measure, self.data.measure_label);
111             });
112
113         }
114     },
115
116     do_search: function (domain, context, group_by) {
117         this.data.domain = new instance.web.CompoundDomain(domain);
118
119         if (this.pivot_table) {
120             this.pivot_table.draw(true);
121         } else {
122             this.pivot_table = new PivotTable(this.data);
123             this.pivot_table.appendTo('.graph_main_content');
124         }
125         this.display_data();
126     },
127
128     do_show: function () {
129         this.do_push_state({});
130         return this._super();
131     },
132
133 });
134
135
136  /**
137   * PivotTable widget.  It displays the data in tabular data and allows the
138   * user to drill down and up in the table
139   */
140 var PivotTable = instance.web.Widget.extend({
141     template: 'pivot_table',
142     data: null,
143     headers: [],
144     rows: [],
145     cols: [],
146     id_seed : 0,
147
148     events: {
149         'click .web_graph_click' : function (event) {
150             event.preventDefault();
151
152             if (event.target.attributes['data-row-id'] !== undefined) {
153                 this.handle_row_event(event);
154             }
155             if (event.target.attributes['data-col-id'] !== undefined) {
156                 this.handle_col_event(event);
157             }
158         },
159
160         'click a.field-selection' : function (event) {
161             var id,
162                 field_id = event.target.attributes['data-field-id'].nodeValue;
163             event.preventDefault();
164             this.dropdown.remove();
165             if (event.target.attributes['data-row-id'] !== undefined) {
166                 id = event.target.attributes['data-row-id'].nodeValue;
167                 this.expand_row(id, field_id);
168             } 
169             if (event.target.attributes['data-col-id'] !== undefined) {
170                 id = event.target.attributes['data-col-id'].nodeValue;
171                 this.expand_col(id, field_id);
172             } 
173         },
174     },
175
176     handle_row_event: function (event) {
177         var row_id = event.target.attributes['data-row-id'].nodeValue,
178             row = this.get_row(row_id);
179
180         if (row.expanded) {
181             this.fold_row(row_id);
182         } else {
183             if (row.path.length < this.data.row_groupby.length) {
184                 var field_to_expand = this.data.row_groupby[row.path.length];
185                 this.expand_row(row_id, field_to_expand);
186             } else {
187                 this.display_dropdown({row_id:row_id, 
188                                        target: $(event.target), 
189                                        x: event.pageX, 
190                                        y: event.pageY});
191             }
192         }
193     },
194
195     handle_col_event: function (event) {
196         var col_id = event.target.attributes['data-col-id'].nodeValue,
197             col = this.get_col(col_id);
198
199         if (col.expanded) {
200             this.fold_col(col_id);
201         } else {
202             if (col.path.length < this.data.col_groupby.length) {
203                 var field_to_expand = this.data.col_groupby[col.path.length];
204                 this.expand_col(col_id, field_to_expand);
205             } else {
206                 this.display_dropdown({col_id: col_id, 
207                                        target: $(event.target), 
208                                        x: event.pageX, 
209                                        y: event.pageY});
210             }
211         }
212     },
213
214     init: function (data) {
215         this.data = data;
216     },
217
218     start: function () {
219         this.draw(true);
220     },
221
222     draw: function (load_data) {
223         var self = this;
224
225         if (load_data === true) {
226             var view_fields = this.data.row_groupby.concat(this.data.measure, this.data.col_groupby);
227             query_groups_data(this.data.model, view_fields, this.data.domain, this.data.col_groupby, this.data.row_groupby[0])
228                 .then(function (groups) {
229                     self.data.groups = groups;
230                     return self.get_groups([]);
231                 }).then(function (total) {
232                     self.data.total = [total];
233                     self.build_table();
234                     self.draw(false);
235                 });
236         } else {
237             this.$el.empty();
238
239             this.draw_top_headers();
240
241             _.each(this.rows, function (row) {
242                 self.$el.append(row.html);
243             });
244         }
245     },
246
247     show: function () {
248         this.$el.css('display', 'block');
249     },
250
251     hide: function () {
252         this.$el.css('display', 'none');
253     },
254
255     display_dropdown: function (options) {
256         var self = this,
257             already_grouped = self.data.row_groupby.concat(self.data.col_groupby),
258             possible_groups = _.difference(self.data.important_fields, already_grouped),
259             dropdown_options = {
260                 fields: _.map(possible_groups, function (field) {
261                     return {id: field, value: self.get_descr(field)};
262             })};
263         if (options.row_id) {
264             dropdown_options.row_id= options.row_id;
265         } else {
266             dropdown_options.col_id = options.col_id;
267         }
268
269         this.dropdown = $(QWeb.render('field_selection', dropdown_options));
270         options.target.after(this.dropdown);
271         this.dropdown.css({position:'absolute',
272                            left:options.x,
273                            top:options.y});
274         $('.field-selection').next('.dropdown-menu').toggle();
275     },
276
277     build_table: function () {
278         var self = this;
279         this.rows = [];
280
281
282         var col_id = this.generate_id();
283
284         this.cols= [{
285             id: col_id,
286             path: [],
287             value: this.data.measure_label,
288             expanded: false,
289             parent: null,
290             children: [],
291             cells: [],    // a cell is {td:<jquery td>, row_id:<some id>}
292             domain: this.data.domain,
293         }];
294
295         self.make_top_headers();
296
297         var main_row = this.make_row(this.data.total[0]);
298
299         _.each(this.data.groups, function (group) {
300             self.make_row(group, main_row.id);
301         });
302     },
303
304     get_descr: function (field_id) {
305         return this.data.fields[field_id].string;
306     },
307
308     get_groups: function (groupby) {
309         var view_fields = this.data.row_groupby.concat(this.data.measure, this.data.col_groupby);
310         return query_groups(this.data.model, view_fields, this.data.domain, groupby);
311     },
312
313     make_top_headers : function () {
314         var self = this,
315             header;
316
317         function partition (columns) {
318             return _.reduce(columns, function (partial, col) {
319                 if (partial.length === 0) return [[col]];
320                 if (col.path.length > _.first(_.last(partial)).path.length) {
321                     _.last(partial).push(col);
322                 } else {
323                     partial.push([col]);
324                 }
325                 return partial;
326             }, []);
327         }
328
329         function side_by_side(blocks) {
330             var result = _.zip.apply(_,blocks);
331             result = _.map(result, function(line) {return _.compact(_.flatten(line))});
332             return result;
333         }
334
335         function make_header_cell(col, span) {
336             var options = {
337                 is_border:true,
338                 foldable:true,
339                 row_span: (span === undefined) ? 1 : span,
340                 col_id: col.id,
341             };
342             var result = self.make_cell(col.value, options);
343             if (col.expanded) {
344                 result.find('.icon-plus-sign')
345                     .removeClass('icon-plus-sign')
346                     .addClass('icon-minus-sign');
347             }
348             return result;
349         }
350
351         function calculate_width(cols) {
352             if (cols.length === 1) {
353                 return 1;
354             }
355             var p = partition(_.rest(cols));
356             return _.reduce(p, function(x, y){ return x + calculate_width(y); }, 0);
357         }
358
359         function make_header_cells(cols, height) {
360             var p = partition(cols);
361             if ((p.length === 1) && (p[0].length === 1)) {
362                 var result = [[make_header_cell(cols[0], height)]];
363                 return result;
364             }
365             if ((p.length === 1) && (p[0].length > 1)) {
366                 var cell = make_header_cell(p[0][0]);
367                 cell.attr('colspan', calculate_width(cols));
368                 return [[cell]].concat(make_header_cells(_.rest(cols), height - 1));
369             }
370             if (p.length > 1) {
371                 return side_by_side(_.map(p, function (group) {
372                     return make_header_cells(group, height);
373                 }));
374             }
375         }
376
377         if (this.cols.length === 1) {
378             header = $('<tr></tr>');
379             header.append(this.make_cell('', {is_border:true}));
380             header.append(this.make_cell(this.cols[0].value, 
381                 {is_border:true, foldable:true, col_id:this.cols[0].id}));
382             header.addClass('graph_top');
383             this.headers = [header];
384         } else {
385             var height = _.max(_.map(self.cols, function(g) {return g.path.length;}));
386             var header_rows = make_header_cells(_.rest(this.cols), height);
387
388             header_rows[0].splice(0,0,self.make_cell('', {is_border:true, }).attr('rowspan', height))
389             self.headers = [];
390             _.each(header_rows, function (cells) {
391                 header = $('<tr></tr>');
392                 header.append(cells);
393                 header.addClass('graph_top');
394                 self.headers.push(header);
395             });
396         }
397     },
398
399     draw_top_headers: function () {
400         var self = this;
401         $("tr.graph_top").remove();
402         _.each(this.headers.reverse(), function (header) {
403             self.$el.prepend(header);
404         });
405
406     },
407
408     make_row: function (group, parent_id) {
409         group = group[0];
410         var path,
411             value,
412             expanded,
413             domain,
414             parent,
415             has_parent = (parent_id !== undefined),
416             row_id = this.generate_id();
417
418         if (has_parent) {
419             parent = this.get_row(parent_id);
420             path = parent.path.concat(group.attributes.value[1]);
421             value = group.attributes.value[1];
422             expanded = false;
423             parent.children.push(row_id);
424             domain = group.model._domain;
425         } else {
426             parent = null;
427             path = [];
428             value = 'Total';
429             expanded = true;
430             domain = this.data.domain;
431         }
432
433         var jquery_row = $('<tr></tr>');
434
435         var header = this.make_cell(value, {is_border:true, indent: path.length, foldable:true, row_id: row_id});
436         var cell = this.make_cell(group.attributes.aggregates[this.data.measure]);
437         jquery_row.html(header);
438         jquery_row.append(cell);
439
440         _.each(this.cols, function (col) {
441             col.cells.push({row_id: row_id, td: cell });
442         });
443
444         if (!has_parent) {
445             header.find('.icon-plus-sign')
446                 .removeClass('icon-plus-sign')
447                 .addClass('icon-minus-sign');            
448         }
449
450         var row = {
451             id: row_id,
452             path: path,
453             value: value,
454             expanded: expanded,
455             parent: parent_id,
456             children: [],
457             html: jquery_row,
458             domain: domain,
459         };
460         this.rows.push(row);  // to do, insert it properly, after all childs of parent
461         return row;
462     },
463
464     generate_id: function () {
465         this.id_seed += 1;
466         return this.id_seed - 1;
467     },
468
469     get_row: function (id) {
470         return _.find(this.rows, function(row) {
471             return (row.id == id);
472         });
473     },
474
475     get_col: function (id) {
476         return _.find(this.cols, function(col) {
477             return (col.id == id);
478         });
479     },
480
481     make_cell: function (content, options) {
482         options = _.extend({is_border: false, indent:0, foldable:false}, options);
483         content = (content !== undefined) ? content : 'Undefined';
484
485         var cell = $('<td></td>');
486         if (options.is_border) cell.addClass('graph_border');
487         if (options.row_span) cell.attr('rowspan', options.row_span);
488         if (options.col_span) cell.attr('rowspan', options.col_span);
489         _.each(_.range(options.indent), function () {
490             cell.prepend($('<span/>', {class:'web_graph_indent'}));
491         });
492
493         if (options.foldable) {
494             var attrs = {class:'icon-plus-sign web_graph_click', href:'#'};
495             if (options.row_id !== undefined) attrs['data-row-id'] = options.row_id;
496             if (options.col_id !== undefined) attrs['data-col-id'] = options.col_id;
497             var plus = $('<span/>', attrs);
498             plus.append(' ');
499             plus.append(content);
500             cell.append(plus);
501         } else {
502             cell.append(content);
503         }
504         return cell;
505     },
506
507     expand_row: function (row_id, field_id) {
508         var self = this;
509         var row = this.get_row(row_id);
510
511         if (row.path.length == this.data.row_groupby.length) {
512             this.data.row_groupby.push(field_id);
513         }
514         row.expanded = true;
515         row.html.find('.icon-plus-sign')
516             .removeClass('icon-plus-sign')
517             .addClass('icon-minus-sign');
518
519         var visible_fields = this.data.row_groupby.concat(this.data.col_groupby, this.data.measure);
520         query_groups_data(this.data.model, visible_fields, row.domain, this.data.col_groupby, field_id)
521             .then(function (groups) {
522                 _.each(groups.reverse(), function (group) {
523                     var new_row = self.make_row(group, row_id);
524                     row.html.after(new_row.html);
525                 });
526         });
527
528     },
529
530     expand_col: function (col_id, field_id) {
531         var self = this;
532         var col = this.get_col(col_id);
533
534         if (col.path.length == this.data.col_groupby.length) {
535             this.data.col_groupby.push(field_id);
536         }
537         col.expanded = true;
538
539         var visible_fields = this.data.row_groupby.concat(this.data.col_groupby, this.data.measure);
540         query_groups_data(this.data.model, visible_fields, col.domain, this.data.row_groupby, field_id)
541             .then(function (groups) {
542                 _.each(groups, function (group) {
543                     var new_col = {
544                         id: self.generate_id(),
545                         path: col.path.concat(group[0].attributes.value[1]),
546                         value: group[0].attributes.value[1],
547                         expanded: false,
548                         parent: col_id,
549                         children: [],
550                         cells: [],    // a cell is {td:<jquery td>, row_id:<some id>}
551                         domain: group[0].model._domain,
552                     };
553                     col.children.push(new_col.id);
554                     insertAfter(self.cols, col, new_col)
555                     _.each(col.cells, function (cell) {
556                         var col_path = self.get_row(cell.row_id).path;
557
558                         var datapt = _.find(group, function (g) {
559                             return _.isEqual(g.path.slice(1), col_path);
560                         });
561
562                         var value;
563                         if (datapt === undefined) {
564                             value = '';
565                         } else {
566                             value = datapt.attributes.aggregates[self.data.measure];
567                         }
568                         var new_cell = {
569                             row_id: cell.row_id,
570                             td: self.make_cell(value)
571                         };
572                         new_col.cells.push(new_cell);
573                         cell.td.after(new_cell.td);
574                         cell.td.css('display','none');
575                     });
576
577                 });
578             self.make_top_headers();
579             self.draw_top_headers();
580         });
581     },
582
583     fold_row: function (row_id) {
584         var self = this;
585         var row = this.get_row(row_id);
586
587         _.each(row.children, function (child_row) {
588             self.remove_row(child_row);
589         });
590         row.children = [];
591
592         row.expanded = false;
593         row.html.find('.icon-minus-sign')
594             .removeClass('icon-minus-sign')
595             .addClass('icon-plus-sign');
596
597         var fold_levels = _.map(self.rows, function(g) {return g.path.length;});
598         var new_groupby_length = _.max(fold_levels); 
599
600         this.data.row_groupby.splice(new_groupby_length);
601     },
602
603     remove_row: function (row_id) {
604         var self = this;
605         var row = this.get_row(row_id);
606
607         _.each(row.children, function (child_row) {
608             self.remove_row(child_row);
609         });
610
611         row.html.remove();
612         removeFromArray(this.rows, row);
613
614         _.each(this.cols, function (col) {
615             col.cells = _.filter(col.cells, function (cell) {
616                 return cell.row_id !== row_id;
617             });
618         });
619     },
620
621     fold_col: function (col_id) {
622         var self = this;
623         var col = this.get_col(col_id);
624
625         _.each(col.children, function (child_col) {
626             self.remove_col(child_col);
627         });
628         col.children = [];
629
630         _.each(col.cells, function (cell) {
631             cell.td.css('display','table-cell');
632         });
633         col.expanded = false;
634         // row.html.find('.icon-minus-sign')
635         //     .removeClass('icon-minus-sign')
636         //     .addClass('icon-plus-sign');
637
638         var fold_levels = _.map(self.cols, function(g) {return g.path.length;});
639         var new_groupby_length = _.max(fold_levels); 
640
641         this.data.col_groupby.splice(new_groupby_length);
642         this.make_top_headers();
643         this.draw_top_headers();
644
645             
646     },
647     
648     remove_col: function (col_id) {
649         var self = this;
650         var col = this.get_col(col_id);
651
652         _.each(col.children, function (child_col) {
653             self.remove_col(child_col);
654         });
655
656         _.each(col.cells, function (cell) {
657             cell.td.remove();
658         });
659         // row.html.remove();
660         removeFromArray(this.cols, col);
661
662         // _.each(this.cols, function (col) {
663         //     col.cells = _.filter(col.cells, function (cell) {
664         //         return cell.row_id !== row_id;
665         //     });
666         // });
667     },
668
669
670 });
671
672 };