[REF] removes a few useless lines in view_loading method (addon web_graph)
[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
26     events: {
27         'click .graph_mode_selection li' : function (event) {
28             event.preventDefault();
29             var mode = event.target.attributes['data-mode'].nodeValue;
30             this.mode = mode;
31             this.display_data();
32         },
33
34         'click .graph_measure_selection li' : function (event) {
35             event.preventDefault();
36             var measure = event.target.attributes['data-choice'].nodeValue;
37             this.measure = (measure === '__count') ? null : measure;
38             this.pivot_table.set_measure(this.measure)
39                 .then(this.proxy('display_data'));
40         },
41
42         'click .graph_expand_selection li' : function (event) {
43             event.preventDefault();
44             switch (event.target.attributes['data-choice'].nodeValue) {
45                 case 'fold_columns':
46                     this.pivot_table.fold_cols();
47                     this.display_data();
48                     break;
49                 case 'fold_rows':
50                     this.pivot_table.fold_rows();
51                     this.display_data();
52                     break;
53                 case 'fold_all':
54                     this.pivot_table.fold_all();
55                     this.display_data();
56                     break;
57                 case 'expand_all':
58                     this.pivot_table.expand_all().then(this.proxy('display_data'));
59                     break;
60             }
61         },
62
63         'click .graph_options_selection li' : function (event) {
64             event.preventDefault();
65             switch (event.target.attributes['data-choice'].nodeValue) {
66                 case 'swap_axis':
67                     this.pivot_table.swap_axis();
68                     this.display_data();
69                     break;
70                 case 'update_values':
71                     this.pivot_table.update_values().then(this.proxy('display_data'));
72                     break;
73                 case 'export_data':
74                     // Export code...  To do...
75                     break;
76             }
77         },
78
79         'click .web_graph_click' : function (event) {
80             event.preventDefault();
81             event.stopPropagation();
82             var id = event.target.attributes['data-id'].nodeValue;
83             this.handle_header_event({id:id, event:event});
84         },
85
86         'click a.field-selection' : function (event) {
87             var id = event.target.attributes['data-id'].nodeValue,
88                 field_id = event.target.attributes['data-field-id'].nodeValue;
89             event.preventDefault();
90             this.pivot_table.expand(id, field_id)
91                 .then(this.proxy('display_data'));
92         },
93     },
94
95     init: function(parent, dataset, view_id, options) {
96         this._super(parent);
97         this.dataset = dataset;
98         this.set_default_options(options);
99         this.dropdown = null;
100         this.pivot_table = null;
101         this.heat_map_mode = false;
102         this.mode = 'pivot';
103         this.measure = null;
104         this.measure_list = [];
105         this.important_fields = [];
106     },
107
108     start: function () {
109         this.table = $('<table></table>');
110         this.$('.graph_main_content').append(this.table);
111         instance.web.bus.on('click', this, function (ev) {
112             if (this.dropdown) {
113                 this.dropdown.remove();
114                 this.dropdown = null;
115             }
116         });
117         return this.load_view();
118     },
119
120     view_loading: function (fields_view_get) {
121         var self = this,
122             model = new instance.web.Model(fields_view_get.model, {group_by_no_leaf: true}),
123             row_groupby = [];
124
125         // get the default groupbys and measure defined in the field view
126         _.each(fields_view_get.arch.children, function (field) {
127             if ('name' in field.attrs) {
128                 if ('operator' in field.attrs) {
129                     self.measure_list.push(field.attrs.name);
130                 } else {
131                     row_groupby.push(field.attrs.name);
132                 }
133             }
134         });
135         if (this.measure_list.length > 0) {
136             this.measure = this.measure_list[0];
137         }
138
139         // get the most important fields (of the model) by looking at the
140         // groupby filters defined in the search view
141         var options = {model:model, view_type: 'search'},
142             deferred1 = instance.web.fields_view_get(options).then(function (search_view) {
143                 var groups = _.select(search_view.arch.children, function (c) {
144                     return (c.tag == 'group') && (c.attrs.string != 'Display');
145                 });
146                 _.each(groups, function(g) {
147                     _.each(g.children, function (g) {
148                         if (g.attrs.context) {
149                             var field_id = py.eval(g.attrs.context).group_by;
150                             self.important_fields.push(field_id);
151                         }
152                     });
153                 });
154             });
155
156         // get the fields descriptions from the model
157         var deferred2 = model.call('fields_get', []).then(function (fs) { 
158             self.fields = fs; 
159             var measure_selection = self.$('.graph_measure_selection');
160             _.each(self.measure_list, function (measure) {
161                 var choice = $('<a></a>').attr('data-choice', measure)
162                                          .attr('href', '#')
163                                          .append(self.fields[measure].string);
164                 measure_selection.append($('<li></li>').append(choice));
165
166             });
167         });
168
169         return $.when(deferred1, deferred2).then(function () {
170             var data = {
171                 model: model,
172                 domain: [],
173                 measure: self.measure,
174                 col_groupby: [],
175                 row_groupby: row_groupby,
176             };
177             self.pivot_table = new openerp.web_graph.PivotTable(data);
178         });
179     },
180
181     do_search: function (domain, context, group_by) {
182         this.pivot_table.domain = domain;
183         this.pivot_table.update_values().done(this.proxy('display_data'));
184     },
185
186     do_show: function () {
187         this.do_push_state({});
188         return this._super();
189     },
190
191     display_data: function () {
192         this.$('.graph_main_content svg').remove();
193         this.table.empty();
194
195         if (this.pivot_table.no_data) {
196             var msg = 'No data available. Try to remove any filter or add some data.';
197             this.table.append($('<tr><td>' + msg + '</td></tr>'));
198         } else {
199             var table_modes = ['pivot', 'heatmap', 'row_heatmap', 'col_heatmap'];
200             if (_.contains(table_modes, this.mode)) {
201                 this.draw_table();
202             } else {
203                 this.$('.graph_main_content').append($('<div><svg></svg></div>'));
204                 var svg = this.$('.graph_main_content svg')[0];
205                 openerp.web_graph.draw_chart(this.mode, this.pivot_table, svg);
206             }
207         }
208     },
209
210     handle_header_event: function (options) {
211         var pivot = this.pivot_table,
212             id = options.id,
213             header = pivot.get_header(id);
214
215         if (header.is_expanded) {
216             pivot.fold(header);
217             this.display_data();
218         } else {
219             if (header.path.length < header.root.groupby.length) {
220                 var field = header.root.groupby[header.path.length];
221                 pivot.expand(id, field).then(this.proxy('display_data'));
222             } else {
223                 this.display_dropdown({id:header.id,
224                                        target: $(options.event.target),
225                                        x: options.event.pageX,
226                                        y: options.event.pageY});
227             }
228         }
229     },
230
231     display_dropdown: function (options) {
232         var self = this,
233             pivot = this.pivot_table,
234             already_grouped = pivot.rows.groupby.concat(pivot.cols.groupby),
235             possible_groups = _.difference(self.important_fields, already_grouped),
236             dropdown_options = {
237                 header_id: options.id,
238                 fields: _.map(possible_groups, function (field) {
239                     return {id: field, value: self.fields[field].string};
240             })};
241
242         this.dropdown = $(QWeb.render('field_selection', dropdown_options));
243         options.target.after(this.dropdown);
244         this.dropdown.css({position:'absolute',
245                            left:options.x,
246                            top:options.y});
247         this.$('.field-selection').next('.dropdown-menu').toggle();
248     },
249
250     measure_label: function () {
251         return (this.measure) ? this.fields[this.measure].string : 'Quantity';
252     },
253
254     draw_table: function () {
255         this.pivot_table.rows.main.title = 'Total';
256         this.pivot_table.cols.main.title = this.measure_label();
257         this.draw_top_headers();
258         _.each(this.pivot_table.rows.headers, this.proxy('draw_row'));
259     },
260
261     make_border_cell: function (colspan, rowspan) {
262         return $('<td></td>').addClass('graph_border')
263                              .attr('colspan', colspan)
264                              .attr('rowspan', rowspan);
265     },
266
267     make_header_title: function (header) {
268         return $('<span> </span>')
269             .addClass('web_graph_click')
270             .attr('href', '#')
271             .addClass((header.is_expanded) ? 'icon-minus-sign' : 'icon-plus-sign')
272             .append((header.title !== undefined) ? header.title : 'Undefined');
273     },
274
275     draw_top_headers: function () {
276         var self = this,
277             pivot = this.pivot_table,
278             height = _.max(_.map(pivot.cols.headers, function(g) {return g.path.length;})),
279             header_cells = [[this.make_border_cell(1, height)]];
280
281         function set_dim (cols) {
282             _.each(cols.children, set_dim);
283             if (cols.children.length === 0) {
284                 cols.height = height - cols.path.length + 1;
285                 cols.width = 1;
286             } else {
287                 cols.height = 1;
288                 cols.width = _.reduce(cols.children, function (sum,c) { return sum + c.width;}, 0);
289             }
290         }
291
292         function make_col_header (col) {
293             var cell = self.make_border_cell(col.width, col.height);
294             return cell.append(self.make_header_title(col).attr('data-id', col.id));
295         }
296
297         function make_cells (queue, level) {
298             var col = queue[0];
299             queue = _.rest(queue).concat(col.children);
300             if (col.path.length == level) {
301                 _.last(header_cells).push(make_col_header(col));
302             } else {
303                 level +=1;
304                 header_cells.push([make_col_header(col)]);
305             }
306             if (queue.length !== 0) {
307                 make_cells(queue, level);
308             }
309         }
310
311         set_dim(pivot.cols.main);  // add width and height info to columns headers
312         if (pivot.cols.main.children.length === 0) {
313             make_cells(pivot.cols.headers, 0);
314         } else {
315             make_cells(pivot.cols.main.children, 1);
316             header_cells[0].push(self.make_border_cell(1, height).append('Total').css('font-weight', 'bold'));
317         }
318
319         _.each(header_cells, function (cells) {
320             self.table.append($('<tr></tr>').append(cells));
321         });
322     },
323
324     draw_row: function (row) {
325         var self = this,
326             pivot = this.pivot_table,
327             html_row = $('<tr></tr>'),
328             row_header = this.make_border_cell(1,1)
329                 .append(this.make_header_title(row).attr('data-id', row.id))
330                 .addClass('graph_border');
331
332         for (var i in _.range(row.path.length)) {
333             row_header.prepend($('<span/>', {class:'web_graph_indent'}));
334         }
335
336         html_row.append(row_header);
337
338         _.each(pivot.cols.headers, function (col) {
339             if (col.children.length === 0) {
340                 var value = pivot.get_value(row.id, col.id),
341                     cell = make_cell(value, col);
342                 html_row.append(cell);
343             }
344         });
345
346         if (pivot.cols.main.children.length > 0) {
347             var cell = make_cell(pivot.get_total(row), pivot.cols.main)
348                             .css('font-weight', 'bold');
349             html_row.append(cell);
350         }
351
352         this.table.append(html_row);
353
354         function make_cell (value, col) {
355             var color,
356                 total,
357                 cell = $('<td></td>');
358             if ((self.mode === 'pivot') && (row.is_expanded) && (row.path.length <=2)) {
359                 color = row.path.length * 5 + 240;
360                 cell.css('background-color', $.Color(color, color, color));
361             }
362             if (value === undefined) {
363                 return cell;
364             }
365             cell.append(value);
366             if (self.mode === 'heatmap') {
367                 total = pivot.get_total();
368                 color = Math.floor(50 + 205*(total - value)/total);
369                 cell.css('background-color', $.Color(255, color, color));
370             }
371             if (self.mode === 'row_heatmap') {
372                 total = pivot.get_total(row);
373                 color = Math.floor(50 + 205*(total - value)/total);
374                 cell.css('background-color', $.Color(255, color, color));
375             }
376             if (self.mode === 'col_heatmap') {
377                 total = pivot.get_total(col);
378                 color = Math.floor(50 + 205*(total - value)/total);
379                 cell.css('background-color', $.Color(255, color, color));
380             }
381             return cell;
382         }
383     },
384 });
385
386 };