c3c5e9f62b9bc53d324c38311de152c6bf01b25c
[odoo/odoo.git] / addons / base_graph / static / src / js / graph.js
1 /*---------------------------------------------------------
2  * OpenERP base_graph
3  *---------------------------------------------------------*/
4
5 openerp.base_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 QWeb.add_template('/base_graph/static/src/xml/base_graph.xml');
16 openerp.base.views.add('graph', 'openerp.base_graph.GraphView');
17 openerp.base_graph.GraphView = openerp.base.View.extend({
18
19     init: function(view_manager, session, element_id, dataset, view_id) {
20         this._super(session, element_id);
21         this.view_manager = view_manager;
22         this.dataset = dataset;
23         this.model = this.dataset.model;
24         this.view_id = view_id;
25     },
26     do_show: function () {
27         // TODO: re-trigger search
28         this.$element.show();
29     },
30     do_hide: function () {
31         this.$element.hide();
32     },
33     start: function() {
34         return this.rpc("/base_graph/graphview/load", {"model": this.model, "view_id": this.view_id}, this.on_loaded);
35     },
36     on_loaded: function(data) {
37         this.all_fields = data.all_fields;
38         this.fields_view = data.fields_view;
39         this.name = this.fields_view.name || this.fields_view.arch.attrs.string;
40         this.view_id = this.fields_view.view_id;
41         this.chart = this.fields_view.arch.attrs.type || 'pie';
42         this.fields = this.fields_view.fields;
43         this.chart_info_fields = [];
44         this.operator_field = '';
45         this.operator_field_one = '';
46         this.operator = [];
47         this.group_field = '';
48         this.orientation = this.fields_view.arch.attrs.orientation || '';
49         this.elem_id = this.$element[0]['id'];
50
51         _.each(this.fields_view.arch.children, function (field) {
52             if (field.attrs.operator) {
53                 this.operator.push(field.attrs.name);
54             }
55             else if (field.attrs.group) {
56                 this.group_field = field.attrs.name;
57             }
58             else {
59                 this.chart_info_fields.push(field.attrs.name);
60             }
61         }, this);
62
63         this.operator_field = this.operator[0];
64         if(this.operator.length > 1){
65             this.operator_field_one = this.operator[1];
66         }
67         if(this.operator == ''){
68             this.operator_field = this.chart_info_fields[1];
69         }
70         this.chart_info = this.chart_info_fields[0];
71         this.x_title = this.fields[this.chart_info_fields[0]]['string'];
72         this.y_title = this.fields[this.operator_field]['string'];
73         this.load_chart();
74     },
75
76     load_chart: function(data) {
77         var self = this;
78         if(data){
79             this.x_title = this.all_fields[this.chart_info_fields]['string'];
80             this.y_title = this.all_fields[this.operator_field]['string'];
81             self.schedule_chart(data);
82         }else{
83             this.dataset.read_ids(
84                 this.dataset.ids,
85                 {}, function(res) {
86                     self.schedule_chart(res);
87                 });
88         }
89     },
90
91     schedule_chart: function(results) {
92         this.$element.html(QWeb.render("GraphView", {"fields_view": this.fields_view, "chart": this.chart,'elem_id': this.elem_id}));
93         /*if (!results.length) {
94             return;
95         }*/
96         _.each(results, function (result) {
97             _.each(result, function (field_value, field_name) {
98                 if (typeof field_value == 'object') {
99                     result[field_name] = field_value[field_value.length - 1];
100                 }
101                 if (typeof field_value == 'string') {
102                     var choices = this.all_fields[field_name]['selection'];
103                     _.each(choices, function (choice) {
104                         if (field_value == choice[0]) {
105                             result[field_name] = choice;
106                         }
107                     });
108                 }
109             }, this);
110         }, this);
111
112         var graph_data = {};
113         _.each(results, function (result) {
114             var column_key = result[this.chart_info_fields] + "_" + result[this.group_field];
115             var column_descriptor = {};
116             if (graph_data[column_key] == undefined) {
117                 column_descriptor[this.operator_field] = result[this.operator_field];
118                 if (this.operator.length > 1) {
119                     column_descriptor[this.operator_field_one] = result[this.operator_field_one];
120                 }
121                 column_descriptor[this.chart_info_fields] = result[this.chart_info_fields];
122                 if (this.group_field) {
123                     column_descriptor[this.group_field] = (typeof result[this.group_field] == 'object') ? result[this.group_field][1] : result[this.group_field];
124                 }
125             } else {
126                 column_descriptor = graph_data[column_key];
127                 column_descriptor[this.operator_field] += result[this.operator_field];
128                 if (this.operator.length > 1) {
129                     column_descriptor[this.operator_field_one] += result[this.operator_field_one];
130                 }
131             }
132             graph_data[column_key] = column_descriptor;
133         }, this);
134
135         if (this.chart == 'bar') {
136             return this.schedule_bar(_.values(graph_data));
137         } else if (this.chart == "pie") {
138             return this.schedule_pie(_.values(graph_data));
139         }
140     },
141
142     schedule_bar: function(results) {
143         var self = this;
144         var view_chart = '';
145         var group_list = [];
146         var newkey = '', newkey_one;
147
148         if(self.group_field && (this.operator.length <= 1)){
149             view_chart = self.orientation == 'horizontal'? 'stackedBarH' : 'stackedBar';
150         }else{
151             view_chart = self.orientation == 'horizontal'? 'barH' : 'bar';
152         }
153
154         _.each(results, function (result) {
155             if (self.group_field && (this.operator.length <= 1)) {
156                 newkey = result[self.group_field].split(' ').join('_');
157             } else {
158                 newkey = "val";
159             }
160
161             if (_.contains(group_list, newkey)) {
162                 return;
163             }
164             group_list.push(newkey);
165             if (this.operator.length > 1) {
166                 newkey_one = "val1";
167                 group_list.push(newkey_one);
168             }
169         }, this);
170
171         if (group_list.length <=1){
172             group_list = [];
173             group_list.push(newkey = "val");
174         }
175
176         var abscissa_data = {};
177         _.each(results, function (result) {
178             var label = result[self.chart_info_fields],
179               section = {};
180             if (self.group_field && (group_list.length > 1) && (self.operator.length <= 1)){
181                 newkey = result[self.group_field].split(' ').join('_');
182             }else{
183                 newkey = "val";
184             }
185             if (abscissa_data[label] == undefined){
186                 section[self.chart_info_fields] = label;
187                 _.each(group_list, function (group) {
188                     section[group] = 0;
189                 });
190             } else {
191                 section = abscissa_data[label];
192             }
193             section[newkey] = result[self.operator_field];
194             if (self.operator.length > 1){
195                 section[newkey_one] = result[self.operator_field_one];
196             }
197             abscissa_data[label] = section;
198         });
199
200         //for legend color
201         var grp_color = _.map(group_list, function (group_legend, index) {
202             var legend = {color: COLOR_PALETTE[index]};
203             if (group_legend == "val"){
204                 legend['text'] = self.fields[self.operator_field]['string']
205             }else if(group_legend == "val1"){
206                 legend['text'] = self.fields[self.operator_field_one]['string']
207             }else{
208                 legend['text'] = group_legend;
209             }
210             return legend;
211         });
212
213         //for axis's value and title
214         var max_min = [];
215         var max = 0;
216         var min = 0;
217         var step = 0;
218         var stack_data = 0;
219         var minimum = 0;
220
221         if(! _.isEmpty(abscissa_data)){
222             _.each(abscissa_data, function (abscissa_datas) {
223                 if (group_list.length <= 1){
224                     max_min.push(abscissa_datas[group_list]);
225                 }else{
226                     stack_data = (abscissa_datas[group_list[0]]) + (abscissa_datas[group_list[1]]);
227                     max_min.push(stack_data);
228                 }
229             });
230             max = Math.max.apply(Math,max_min);
231             minimum = Math.min.apply(Math,max_min);
232             if (minimum < 0){
233                 min = minimum;
234             }
235             if (max != 0){
236                 if (max < 0){
237                     max = max - (10 + max % 10)
238                 }else{
239                     max = max + (10 - (max % 10))
240                 }
241                 step = Math.round(max/10);
242             }else{
243                 max = 9;
244                 step = 1;
245             }
246         }else{
247             max = 9;
248             step=1;
249         }
250
251         var abscissa_description = {
252             template: self.chart_info_fields,
253             title: "<b>"+self.x_title+"</b>"
254         };
255
256         var ordinate_description = {
257             lines: true,
258             title: "<b>"+self.y_title+"</b>",
259             start: min,
260             step: step,
261             end: max
262         };
263
264         var x_axis, y_axis;
265         if (self.orientation == 'horizontal'){
266              x_axis = ordinate_description;
267              y_axis = abscissa_description;
268         }else{
269              x_axis = abscissa_description;
270              y_axis = ordinate_description;
271         }
272
273         var bar_chart = new dhtmlXChart({
274             view: view_chart,
275             container: self.elem_id+"-barchart",
276             value:"#"+group_list[0]+"#",
277             gradient: "3d",
278             border: false,
279             width: 1024,
280             tooltip:{
281                 template:"#"+group_list[0]+"#"
282             },
283             radius: 0,
284             color:grp_color[0]['color'],
285             origin:0,
286             xAxis:{
287                 template:function(obj){
288                     if(x_axis['template']){
289                         var val = obj[x_axis['template']];
290                         val = (typeof val == 'object')?val[1]:(!val?'Undefined':val);
291                         return val;
292                     }else{
293                         return obj;
294                     }
295                 },
296                 title:x_axis['title'],
297                 lines:x_axis['lines']
298             },
299             yAxis:{
300                 template:function(obj){
301                     if(y_axis['template']){
302                         var vals = obj[y_axis['template']];
303                         vals = (typeof vals == 'object')?vals[1]:(!vals?'Undefined':vals);
304                         return vals;
305                     }else{
306                         return obj;
307                     }
308                 },
309                 title:y_axis['title'],
310                 lines: y_axis['lines'],
311                 start:y_axis['start'],
312                 step:y_axis['step'],
313                 end:y_axis['end']
314             },
315             padding: {
316                 left: 75
317             },
318             legend: {
319                 values: grp_color,
320                 align:"left",
321                 valign:"top",
322                 layout: "x",
323                 marker:{
324                     type:"round",
325                     width:12
326                 }
327             }
328         });
329         for (var m = 1; m<group_list.length;m++){
330             bar_chart.addSeries({
331                 value: "#"+group_list[m]+"#",
332                 tooltip:{
333                     template:"#"+group_list[m]+"#"
334                 },
335                 color: grp_color[m]['color']
336             });
337         }
338         bar_chart.parse(_.values(abscissa_data), "json");
339         jQuery("#"+self.elem_id+"-barchart").height(jQuery("#"+self.elem_id+"-barchart").height()+50);
340         bar_chart.attachEvent("onItemClick", function(id) {
341             self.open_list_view(bar_chart.get(id));
342         });
343     },
344     schedule_pie: function(result) {
345         var self = this;
346         var chart =  new dhtmlXChart({
347             view:"pie3D",
348             container:self.elem_id+"-piechart",
349             value:"#"+self.operator_field+"#",
350             pieInnerText:function(obj) {
351                 var sum = chart.sum("#"+self.operator_field+"#");
352                 var val = obj[self.operator_field] / sum * 100 ;
353                 return val.toFixed(1) + "%";
354             },
355             gradient:"3d",
356             height: 20,
357             radius: 200,
358             legend: {
359                 width: 300,
360                 align:"left",
361                 valign:"top",
362                 layout: "x",
363                 marker:{
364                     type:"round",
365                     width:12
366                 },
367                 template:function(obj){
368                     var val = obj[self.chart_info_fields];
369                     val = (typeof val == 'object')?val[1]:val;
370                     return val;
371                 }
372             }
373         });
374         chart.parse(result,"json");
375         chart.attachEvent("onItemClick", function(id) {
376             self.open_list_view(chart.get(id));
377         });
378     },
379     open_list_view : function (id){
380         var self = this;
381         id = id[self.chart_info_fields];
382         if (typeof id == 'object'){
383             id = id[0];
384         }
385         if(this.view_manager.action.context){
386            this.view_manager.action.context = {};
387         }
388         if(!this.view_manager.action.domain) {
389             this.view_manager.action.domain = [[self.chart_info_fields, '=', id],['id','in',self.dataset.ids]];
390         } else {
391             this.view_manager.action.domain.push([self.chart_info_fields, '=', id],['id','in',self.dataset.ids]);
392         }
393         var action_manager = new openerp.base.ActionManager(this.view_manager.session, this.view_manager.element_id);
394         action_manager.start();
395         action_manager.do_action(this.view_manager.action);
396     },
397     do_search: function(domains, contexts, groupbys) {
398         var self = this;
399         this.rpc('/base/session/eval_domain_and_context', {
400             domains: domains,
401             contexts: contexts,
402             group_by_seq: groupbys
403         }, function (results) {
404             // TODO: handle non-empty results.group_by with read_group
405             if(results.group_by  && results.group_by != ''){
406                 self.chart_info_fields = results.group_by[0];
407             }else{
408                 self.chart_info_fields = self.chart_info;
409             }
410             self.dataset.context = self.context = results.context;
411             self.dataset.domain = self.domain = results.domain;
412             self.dataset.read_slice({}, 0, self.limit,function(response){
413                 self.load_chart(response);
414             });
415         });
416     }
417
418 });
419
420 // here you may tweak globals object, if any, and play with on_* or do_* callbacks on them
421
422 };
423
424 // vim:et fdc=0 fdl=0: