[MERGE] graph issues fixes
[odoo/odoo.git] / addons / web_graph / static / src / js / graph.js
1 /*---------------------------------------------------------
2  * OpenERP web_graph
3  *---------------------------------------------------------*/
4
5 openerp.web_graph = function (openerp) {
6 var COLOR_PALETTE = [
7     '#cc99ff', '#ccccff', '#48D1CC', '#CFD784', '#8B7B8B', '#75507b',
8     '#b0008c', '#ff0000', '#ff8e00', '#9000ff', '#0078ff', '#00ff00',
9     '#e6ff00', '#ffff00', '#905000', '#9b0000', '#840067', '#9abe00',
10     '#ffc900', '#510090', '#0000c9', '#009b00', '#75507b', '#3465a4',
11     '#73d216', '#c17d11', '#edd400', '#fcaf3e', '#ef2929', '#ff00c9',
12     '#ad7fa8', '#729fcf', '#8ae234', '#e9b96e', '#fce94f', '#f57900',
13     '#cc0000', '#d400a8'];
14
15 var QWeb = openerp.web.qweb,
16      _lt = openerp.web._lt;
17 openerp.web.views.add('graph', 'openerp.web_graph.GraphView');
18 openerp.web_graph.GraphView = openerp.web.View.extend({
19     display_name: _lt('Graph'),
20
21     init: function(parent, dataset, view_id, options) {
22         this._super(parent);
23         this.set_default_options(options);
24         this.dataset = dataset;
25         this.view_id = view_id;
26
27         this.first_field = null;
28         this.abscissa = null;
29         this.ordinate = null;
30         this.columns = [];
31         this.group_field = null;
32         this.is_loaded = $.Deferred();
33
34         this.renderer = null;
35     },
36     stop: function () {
37         if (this.renderer) {
38             clearTimeout(this.renderer);
39         }
40         this._super();
41     },
42     start: function() {
43         var self = this;
44         this._super();
45         var loaded;
46         if (this.embedded_view) {
47             loaded = $.when([self.embedded_view]);
48         } else {
49             loaded = this.rpc('/web/view/load', {
50                     model: this.dataset.model,
51                     view_id: this.view_id,
52                     view_type: 'graph'
53             });
54         }
55         return $.when(
56             this.dataset.call_and_eval('fields_get', [false, {}], null, 1),
57             loaded)
58             .then(function (fields_result, view_result) {
59                 self.fields = fields_result[0];
60                 self.fields_view = view_result[0];
61                 self.on_loaded(self.fields_view);
62             });
63     },
64     /**
65      * Returns all object fields involved in the graph view
66      */
67     list_fields: function () {
68         var fs = [this.abscissa];
69         fs.push.apply(fs, _(this.columns).pluck('name'));
70         if (this.group_field) {
71             fs.push(this.group_field);
72         }
73         return fs;
74     },
75     on_loaded: function() {
76         this.chart = this.fields_view.arch.attrs.type || 'pie';
77         this.orientation = this.fields_view.arch.attrs.orientation || 'vertical';
78
79         _.each(this.fields_view.arch.children, function (field) {
80             var attrs = field.attrs;
81             if (attrs.group) {
82                 this.group_field = attrs.name;
83             } else if(!this.abscissa) {
84                 this.first_field = this.abscissa = attrs.name;
85             } else {
86                 this.columns.push({
87                     name: attrs.name,
88                     operator: attrs.operator || '+'
89                 });
90             }
91         }, this);
92         this.ordinate = this.columns[0].name;
93         this.is_loaded.resolve();
94     },
95     schedule_chart: function(results) {
96         var self = this;
97         this.$element.html(QWeb.render("GraphView", {
98             "fields_view": this.fields_view,
99             "chart": this.chart,
100             'element_id': this.widget_parent.element_id
101         }));
102
103         var fields = _(this.columns).pluck('name').concat([this.abscissa]);
104         if (this.group_field) { fields.push(this.group_field); }
105         // transform search result into usable records (convert from OpenERP
106         // value shapes to usable atomic types
107         var records = _(results).map(function (result) {
108             var point = {};
109             _(result).each(function (value, field) {
110                 if (!_(fields).contains(field)) { return; }
111                 if (value === false) { point[field] = false; return; }
112                 switch (self.fields[field].type) {
113                 case 'selection':
114                     point[field] = _(self.fields[field].selection).detect(function (choice) {
115                         return choice[0] === value;
116                     })[1];
117                     break;
118                 case 'many2one':
119                     point[field] = value[1];
120                     break;
121                 case 'integer': case 'float': case 'char':
122                 case 'date': case 'datetime':
123                     point[field] = value;
124                     break;
125                 default:
126                     throw new Error(
127                         "Unknown field type " + self.fields[field].type
128                         + "for field " + field + " (" + value + ")");
129                 }
130             });
131             return point;
132         });
133         // aggregate data, because dhtmlx is crap. Aggregate on abscissa field,
134         // leave split on group field => max m*n records where m is the # of
135         // values for the abscissa and n is the # of values for the group field
136         var graph_data = [];
137         _(records).each(function (record) {
138             var abscissa = record[self.abscissa],
139                 group = record[self.group_field];
140             var r = _(graph_data).detect(function (potential) {
141                 return potential[self.abscissa] === abscissa
142                         && (!self.group_field
143                             || potential[self.group_field] === group);
144             });
145             var datapoint = r || {};
146
147             datapoint[self.abscissa] = abscissa;
148             if (self.group_field) { datapoint[self.group_field] = group; }
149             _(self.columns).each(function (column) {
150                 var val = record[column.name],
151                     aggregate = datapoint[column.name];
152                 switch(column.operator) {
153                 case '+':
154                     datapoint[column.name] = (aggregate || 0) + val;
155                     return;
156                 case '*':
157                     datapoint[column.name] = (aggregate || 1) * val;
158                     return;
159                 case 'min':
160                     datapoint[column.name] = (aggregate || Infinity) > val
161                                            ? val
162                                            : aggregate;
163                     return;
164                 case 'max':
165                     datapoint[column.name] = (aggregate || -Infinity) < val
166                                            ? val
167                                            : aggregate;
168                 }
169             });
170
171             if (!r) { graph_data.push(datapoint); }
172         });
173         graph_data = _(graph_data).sortBy(function (point) {
174             return point[self.abscissa] + '[[--]]' + point[self.group_field];
175         });
176         if (_.include(['bar','line','area'],this.chart)) {
177             return this.schedule_bar_line_area(graph_data);
178         } else if (this.chart == "pie") {
179             return this.schedule_pie(graph_data);
180         }
181     },
182     schedule_bar_line_area: function(results) {
183         var self = this;
184         var group_list,
185         view_chart = (self.chart == 'line')?'line':(self.chart == 'area')?'area':'';
186         if (!this.group_field || !results.length) {
187             if (self.chart == 'bar'){
188                 view_chart = (this.orientation === 'horizontal') ? 'barH' : 'bar';
189             }
190             group_list = _(this.columns).map(function (column, index) {
191                 return {
192                     group: column.name,
193                     text: self.fields[column.name].string,
194                     color: COLOR_PALETTE[index % (COLOR_PALETTE.length)]
195                 }
196             });
197         } else {
198             // dhtmlx handles clustered bar charts (> 1 column per abscissa
199             // value) and stacked bar charts (basically the same but with the
200             // columns on top of one another instead of side by side), but it
201             // does not handle clustered stacked bar charts
202             if (self.chart == 'bar' && (this.columns.length > 1)) {
203                 this.$element.text(
204                     'OpenERP Web does not support combining grouping and '
205                   + 'multiple columns in graph at this time.');
206                 throw new Error(
207                     'dhtmlx can not handle columns counts of that magnitude');
208             }
209             // transform series for clustered charts into series for stacked
210             // charts
211             if (self.chart == 'bar'){
212                 view_chart = (this.orientation === 'horizontal')
213                         ? 'stackedBarH' : 'stackedBar';
214             }
215             group_list = _(results).chain()
216                     .pluck(this.group_field)
217                     .uniq()
218                     .map(function (value, index) {
219                         if(value) {
220                             value = value.toLowerCase().replace(/[\s\/]+/g,'_');
221                         }
222                         return {
223                             group: _.str.sprintf('%s_%s', self.ordinate, value),
224                             text: value,
225                             color: COLOR_PALETTE[index % COLOR_PALETTE.length]
226                         };
227                     }).value();
228
229             results = _(results).chain()
230                 .groupBy(function (record) { return record[self.abscissa]; })
231                 .map(function (records) {
232                     var r = {};
233                     // second argument is coerced to a str, no good for boolean
234                     r[self.abscissa] = records[0][self.abscissa];
235                     _(records).each(function (record) {
236                         var value = record[self.group_field];
237                         if(value) {
238                             record[self.group_field] = value.toLowerCase().replace(/[\s\/]+/g,'_');
239                         }
240                         var key = _.str.sprintf('%s_%s', self.ordinate, value);
241                         r[key] = record[self.ordinate];
242                     });
243                     return r;
244                 })
245                 .value();
246         }
247         var abscissa_description = {
248             title: "<b>" + this.fields[this.abscissa].string + "</b>",
249             template: function (obj) {
250                 return obj[self.abscissa] || 'Undefined';
251             }
252         };
253         var ordinate_description = {
254             lines: true,
255             title: "<b>" + this.fields[this.ordinate].string + "</b>"
256         };
257
258         var x_axis, y_axis;
259         if (self.chart == 'bar' && self.orientation == 'horizontal') {
260             x_axis = ordinate_description;
261             y_axis = abscissa_description;
262         } else {
263             x_axis = abscissa_description;
264             y_axis = ordinate_description;
265         }
266         var renderer = function () {
267             if (self.$element.is(':hidden')) {
268                 self.renderer = setTimeout(renderer, 100);
269                 return;
270             }
271             self.renderer = null;
272             var charts = new dhtmlXChart({
273                 view: view_chart,
274                 container: self.widget_parent.element_id+"-"+self.chart+"chart",
275                 value:"#"+group_list[0].group+"#",
276                 gradient: (self.chart == "bar") ? "3d" : "light",
277                 alpha: (self.chart == "area") ? 0.6 : 1,
278                 border: false,
279                 width: 1024,
280                 tooltip:{
281                     template: _.str.sprintf("#%s#, %s=#%s#",
282                         self.abscissa, group_list[0].text, group_list[0].group)
283                 },
284                 radius: 0,
285                 color: (self.chart != "line") ? group_list[0].color : "",
286                 item: (self.chart == "line") ? {
287                             borderColor: group_list[0].color,
288                             color: "#000000"
289                         } : "",
290                 line: (self.chart == "line") ? {
291                             color: group_list[0].color,
292                             width: 3
293                         } : "",
294                 origin:0,
295                 xAxis: x_axis,
296                 yAxis: y_axis,
297                 padding: {
298                     left: 75
299                 },
300                 legend: {
301                     values: group_list,
302                     align:"left",
303                     valign:"top",
304                     layout: "x",
305                     marker: {
306                         type:"round",
307                         width:12
308                     }
309                 }
310             });
311             self.$element.find("#"+self.widget_parent.element_id+"-"+self.chart+"chart").width(
312                 self.$element.find("#"+self.widget_parent.element_id+"-"+self.chart+"chart").width()+120);
313
314             for (var m = 1; m<group_list.length;m++){
315                 var column = group_list[m];
316                 if (column.group === self.group_field) { continue; }
317                 charts.addSeries({
318                     value: "#"+column.group+"#",
319                     tooltip:{
320                         template: _.str.sprintf("#%s#, %s=#%s#",
321                             self.abscissa, column.text, column.group)
322                     },
323                     color: (self.chart != "line") ? column.color : "",
324                     item: (self.chart == "line") ? {
325                             borderColor: column.color,
326                             color: "#000000"
327                         } : "",
328                     line: (self.chart == "line") ? {
329                             color: column.color,
330                             width: 3
331                         } : ""
332                 });
333             }
334             charts.parse(results, "json");
335             self.$element.find("#"+self.widget_parent.element_id+"-"+self.chart+"chart").height(
336                 self.$element.find("#"+self.widget_parent.element_id+"-"+self.chart+"chart").height()+50);
337             charts.attachEvent("onItemClick", function(id) {
338                 self.open_list_view(charts.get(id));
339             });
340         };
341         if (this.renderer) {
342             clearTimeout(this.renderer);
343         }
344         this.renderer = setTimeout(renderer, 0);
345     },
346     schedule_pie: function(result) {
347         var self = this;
348         var renderer = function () {
349             if (self.$element.is(':hidden')) {
350                 self.renderer = setTimeout(renderer, 100);
351                 return;
352             }
353             self.renderer = null;
354             var chart =  new dhtmlXChart({
355                 view:"pie3D",
356                 container:self.widget_parent.element_id+"-piechart",
357                 value:"#"+self.ordinate+"#",
358                 pieInnerText:function(obj) {
359                     var sum = chart.sum("#"+self.ordinate+"#");
360                     var val = obj[self.ordinate] / sum * 100 ;
361                     return val.toFixed(1) + "%";
362                 },
363                 tooltip:{
364                     template:"#"+self.abscissa+"#"+"="+"#"+self.ordinate+"#"
365                 },
366                 gradient:"3d",
367                 height: 20,
368                 radius: 200,
369                 legend: {
370                     width: 300,
371                     align:"left",
372                     valign:"top",
373                     layout: "x",
374                     marker:{
375                         type:"round",
376                         width:12
377                     },
378                     template:function(obj){
379                         return obj[self.abscissa] || 'Undefined';
380                     }
381                 }
382             });
383             chart.parse(result,"json");
384             chart.attachEvent("onItemClick", function(id) {
385                 self.open_list_view(chart.get(id));
386             });
387         };
388         if (this.renderer) {
389             clearTimeout(this.renderer);
390         }
391         this.renderer = setTimeout(renderer, 0);
392     },
393     open_list_view : function (id){
394         var self = this;
395         // unconditionally nuke tooltips before switching view
396         $(".dhx_tooltip").remove('div');
397         id = id[this.abscissa];
398         if(this.fields[this.abscissa].type == "selection"){
399             id = _.detect(this.fields[this.abscissa].selection,function(select_value){
400                 return _.include(select_value, id);
401             });
402         }
403         if (typeof id == 'object'){
404             id = id[0];
405         }
406
407         var views;
408         if (this.widget_parent.action) {
409             views = this.widget_parent.action.views;
410             if (!_(views).detect(function (view) {
411                     return view[1] === 'list' })) {
412                 views = [[false, 'list']].concat(views);
413             }
414         } else {
415             views = _(["list", "form", "graph"]).map(function(mode) {
416                 return [false, mode];
417             });
418         }
419         this.do_action({
420             res_model : this.dataset.model,
421             domain: [[this.abscissa, '=', id], ['id','in',this.dataset.ids]],
422             views: views,
423             type: "ir.actions.act_window",
424             flags: {default_view: 'list'}
425         });
426     },
427
428     do_search: function(domain, context, group_by) {
429         var self = this;
430         return $.when(this.is_loaded).pipe(function() {
431             // TODO: handle non-empty group_by with read_group?
432             if (!_(group_by).isEmpty()) {
433                 self.abscissa = group_by[0];
434             } else {
435                 self.abscissa = self.first_field;
436             }
437             return self.dataset.read_slice(self.list_fields()).then($.proxy(self, 'schedule_chart'));
438         });
439     },
440
441     do_show: function() {
442         this.do_push_state({});
443         return this._super();
444     }
445 });
446 };
447 // vim:et fdc=0 fdl=0: