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