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