[IMP] add heat map functionality to pivot table (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.switch_mode(mode);
31         },
32
33         'click .web_graph_click' : function (event) {
34             event.preventDefault();
35             if (event.target.attributes['data-row-id'] !== undefined) {
36                 this.handle_header_event({type:'row', event:event});
37
38             }
39             if (event.target.attributes['data-col-id'] !== undefined) {
40                 this.handle_header_event({type:'col', event:event});
41             }
42         },
43
44         'click a.field-selection' : function (event) {
45             var id,
46                 field_id = event.target.attributes['data-field-id'].nodeValue;
47             event.preventDefault();
48             this.dropdown.remove();
49             if (event.target.attributes['data-row-id'] !== undefined) {
50                 id = event.target.attributes['data-row-id'].nodeValue;
51                 this.pivot_table.expand_row(id, field_id)
52                     .then(this.proxy('draw_table'));
53             } 
54             if (event.target.attributes['data-col-id'] !== undefined) {
55                 id = event.target.attributes['data-col-id'].nodeValue;
56                 this.pivot_table.expand_col(id, field_id)
57                     .then(this.proxy('draw_table'));
58             } 
59         },
60
61         'click label.graph_swap_axis' : function (event) {
62             this.pivot_table.swap_axis();
63             this.draw_table();
64         },
65
66         'click label.graph_fold_all' : function (event) {
67             this.pivot_table.fold_all();
68             this.draw_table();
69         },
70
71         'click label.graph_fold_rows' : function (event) {
72             this.pivot_table.fold_rows();
73             this.draw_table();
74         },
75
76         'click label.graph_fold_cols' : function (event) {
77             this.pivot_table.fold_cols();
78             this.draw_table();
79         },
80
81         'click label.graph_heat_map' : function (event) {
82             this.heat_map_mode = !this.heat_map_mode;
83             this.draw_table();
84         },
85     },
86
87     view_loading: function (fields_view_get) {
88         var self = this,
89             model = new instance.web.Model(fields_view_get.model, {group_by_no_leaf: true}),
90             domain = [],
91             measure = null,
92             fields,
93             important_fields = [],
94             col_groupby = [], 
95             row_groupby = [];
96
97         this.pivot_table = null;
98         this.heat_map_mode = false;
99
100         // get the default groupbys and measure defined in the field view
101         _.each(fields_view_get.arch.children, function (field) {
102             if ('name' in field.attrs) {
103                 if ('operator' in field.attrs) {
104                     measure = field.attrs.name;
105                 } else {
106                     row_groupby.push(field.attrs.name);
107                 }
108             }
109         });
110
111         // get the most important fields (of the model) by looking at the
112         // groupby filters defined in the search view
113         var load_view = instance.web.fields_view_get({
114             model: model,
115             view_type: 'search',
116         });
117
118         var important_fields_def = $.when(load_view).then(function (search_view) {
119             var groups = _.select(search_view.arch.children, function (c) {
120                 return (c.tag == 'group') && (c.attrs.string != 'Display');
121             });
122             _.each(groups, function(g) {
123                 _.each(g.children, function (g) {
124                     if (g.attrs.context) {
125                         var field_id = py.eval(g.attrs.context).group_by;
126                         important_fields.push(field_id);
127                     }
128                 });
129             });
130         });
131
132         // get the fields descriptions from the model
133         var field_descr_def = model.call('fields_get', [])
134             .then(function (fs) { fields = fs; });
135
136         return $.when(important_fields_def, field_descr_def)
137             .then(function () {
138                 self.data = {
139                     model: model,
140                     domain: domain,
141                     fields: fields,
142                     important_fields: important_fields,
143                     measure: measure,
144                     measure_label: fields[measure].string,
145                     col_groupby: [],
146                     row_groupby: row_groupby,
147                     groups: [],
148                     total: null,
149                 };
150             });
151     },
152
153     start: function () {
154         this.table = $('<table></table>');
155         this.svg = $('<div><svg></svg></div>');
156         this.$el.filter('.graph_main_content').append(this.table);
157         this.$el.filter('.graph_main_content').append(this.svg);
158         return this.load_view();
159     },
160
161     do_search: function (domain, context, group_by) {
162         var self = this;
163         this.data.domain = new instance.web.CompoundDomain(domain);
164
165         if (!this.pivot_table) {
166             self.pivot_table = new PivotTable(self.data);
167             self.pivot_table.start().then(self.proxy('draw_table'));
168         } else {
169             this.pivot_table.update_values.done(function () {
170                 self.draw_table();
171             });
172         }
173     },
174
175     do_show: function () {
176         this.do_push_state({});
177         return this._super();
178     },
179
180     switch_mode: function (mode) {
181         var self = this;
182         this.mode = mode;
183         if (mode === 'pivot') {
184             this.table.css('display', 'block');
185             this.svg.css('display','none');
186         } else {
187             this.table.css('display', 'none');
188             this.svg.remove();
189             this.svg = $('<div><svg></svg></div>');
190             this.$el.filter('.graph_main_content').append(this.svg);
191             draw_chart(this.svg, mode, this.pivot_table);
192
193         }
194     },
195
196     handle_header_event: function (options) {
197         var pivot = this.pivot_table,
198             id = options.event.target.attributes['data-' + options.type + '-id'].nodeValue,
199             header = pivot['get_' + options.type](id);
200
201         if (header.is_expanded) {
202             pivot['fold_' + options.type](header);
203             this.draw_table();
204         } else {
205             if (header.path.length < pivot[options.type + 's'].groupby.length) {
206                 // expand the corresponding header
207                 var field = pivot[options.type + 's'].groupby[header.path.length];
208                 pivot['expand_' + options.type](id, field)
209                     .then(this.proxy('draw_table'));
210             } else {
211                 // display dropdown to query field to expand
212                 this.display_dropdown({id:header.id, 
213                                        type: options.type,
214                                        target: $(event.target), 
215                                        x: event.pageX, 
216                                        y: event.pageY});
217             }
218         }
219     },
220
221     display_dropdown: function (options) {
222         var self = this,
223             pivot = this.pivot_table,
224             already_grouped = pivot.rows.groupby.concat(pivot.cols.groupby),
225             possible_groups = _.difference(self.data.important_fields, already_grouped),
226             dropdown_options = {
227                 fields: _.map(possible_groups, function (field) {
228                     return {id: field, value: self.data.fields[field].string};
229             })};
230         dropdown_options[options.type + '_id'] = options.id;
231
232         this.dropdown = $(QWeb.render('field_selection', dropdown_options));
233         options.target.after(this.dropdown);
234         this.dropdown.css({position:'absolute',
235                            left:options.x,
236                            top:options.y});
237         $('.field-selection').next('.dropdown-menu').toggle();
238     },
239
240     draw_table: function () {
241         this.table.empty();
242         this.draw_top_headers();
243         _.each(this.pivot_table.rows.headers, this.proxy('draw_row'));
244     },
245
246     make_border_cell: function (colspan, rowspan) {
247         return $('<td></td>').addClass('graph_border')
248                              .attr('colspan', colspan)
249                              .attr('rowspan', rowspan);
250     },
251
252     make_header_title: function (header) {
253         return $('<span> </span>')
254             .addClass('web_graph_click')
255             .attr('href', '#')
256             .addClass((header.is_expanded) ? 'icon-minus-sign' : 'icon-plus-sign')
257             .append(header.name);
258     },
259
260     draw_top_headers: function () {
261         var self = this,
262             pivot = this.pivot_table,
263             height = _.max(_.map(pivot.cols.headers, function(g) {return g.path.length;})),
264             header_cells = [[this.make_border_cell(1, height)]];
265
266         function set_dim (cols) {
267             _.each(cols.children, set_dim);
268             if (cols.children.length === 0) {
269                 cols.height = height - cols.path.length + 1;
270                 cols.width = 1;
271             } else {
272                 cols.height = 1;
273                 cols.width = _.reduce(cols.children, function (sum,c) { return sum + c.width;}, 0);
274             }
275         }
276
277         function make_col_header (col) {
278             var cell = self.make_border_cell(col.width, col.height);
279             return cell.append(self.make_header_title(col).attr('data-col-id', col.id));
280         }
281
282         function make_cells (queue, level) {
283             var col = queue[0];
284             queue = _.rest(queue).concat(col.children);
285             if (col.path.length == level) {
286                 _.last(header_cells).push(make_col_header(col));
287             } else {
288                 level +=1;
289                 header_cells.push([make_col_header(col)]);
290             }
291             if (queue.length !== 0) {
292                 make_cells(queue, level);
293             }
294         }
295
296         set_dim(pivot.cols.main);  // add width and height info to columns headers
297         if (pivot.cols.main.children.length === 0) {
298             make_cells(pivot.cols.headers, 0);
299         } else {
300             make_cells(pivot.cols.main.children, 1);
301         }
302
303         _.each(header_cells, function (cells) {
304             self.table.append($("<tr></tr>").append(cells));
305         });
306     },
307
308     draw_row: function (row) {
309         var self = this,
310             pivot = this.pivot_table,
311             html_row = $('<tr></tr>'),
312             row_header = this.make_border_cell(1,1)
313                 .append(this.make_header_title(row).attr('data-row-id', row.id))
314                 .addClass('graph_border');
315
316         for (var i in _.range(row.path.length)) {
317             row_header.prepend($('<span/>', {class:'web_graph_indent'}));
318         }
319
320         html_row.append(row_header);
321
322         _.each(pivot.cols.headers, function (col) {
323             if (col.children.length === 0) {
324                 var value = pivot.get_value(row.id, col.id),
325                     cell = $('<td></td>');
326
327                 cell.append((value === undefined) ? '' : value);
328                 if ((self.heat_map_mode) && (value !== undefined)) {
329                     // heat map
330                     console.log("heat map", self.heat_map_mode, pivot.total);
331                     var ratio = Math.floor(70 + 185*(pivot.total - value)/pivot.total);
332                     console.log("ratio",ratio);
333                     cell.css("background-color", "rgb(255," + ratio + "," + ratio + ")");
334                 } 
335                 html_row.append(cell);
336             }
337         });
338         this.table.append(html_row);
339     }
340 });
341
342 };