[FIX] fields: inherited fields get their attribute 'state' from their base field
[odoo/odoo.git] / addons / web_graph / static / src / js / graph_widget.js
1
2 /* jshint undef: false  */
3
4 (function () {
5 'use strict';
6 var QWeb = openerp.web.qweb;
7 var _lt = openerp.web._lt;
8 var _t = openerp.web._t;
9
10 nv.dev = false;  // sets nvd3 library in production mode
11
12 openerp.web_graph.Graph = openerp.web.Widget.extend({
13     template: 'GraphWidget',
14
15     // ----------------------------------------------------------------------
16     // Init stuff
17     // ----------------------------------------------------------------------
18     init: function(parent, model,  domain, options) {
19         this._super(parent);
20         this.model = model;
21         this.domain = domain;
22         this.mode = options.mode || 'pivot';  // pivot, bar, pie, line
23         this.heatmap_mode = options.heatmap_mode || 'none';
24         this.visible_ui = options.visible_ui || true;
25         this.bar_ui = options.bar_ui || 'group';
26         this.graph_view = options.graph_view || null;
27         this.pivot_options = options;
28         this.title = options.title || 'Data';
29     },
30
31     start: function() {
32         var self = this;
33         this.table = $('<table>');
34         this.$('.graph_main_content').append(this.table);
35
36         var indexes = {'pivot': 0, 'bar': 1, 'line': 2, 'chart': 3};
37         this.$('.graph_mode_selection label').eq(indexes[this.mode]).addClass('active');
38
39         if (this.mode !== 'pivot') {
40             this.$('.graph_heatmap label').addClass('disabled');
41             this.$('.graph_main_content').addClass('graph_chart_mode');
42         } else {
43             this.$('.graph_main_content').addClass('graph_pivot_mode');
44         }
45
46         // get search view
47         var parent = this.getParent();
48         while (!(parent instanceof openerp.web.ViewManager)) {
49             parent = parent.getParent();
50         }
51         this.search_view = parent.searchview;
52
53         openerp.session.rpc('/web_graph/check_xlwt').then(function (result) {
54             self.$('.graph_options_selection label').last().toggle(result);
55         });
56
57         return this.model.call('fields_get', {
58                     context: this.graph_view.dataset.context
59                 }).then(function (f) {
60             self.fields = f;
61             self.fields.__count = {field:'__count', type: 'integer', string:_t('Count')};
62             self.groupby_fields = self.get_groupby_fields();
63             self.measure_list = self.get_measures();
64             self.add_measures_to_options();
65             self.pivot_options.row_groupby = self.create_field_values(self.pivot_options.row_groupby || []);
66             self.pivot_options.col_groupby = self.create_field_values(self.pivot_options.col_groupby || []);
67             self.pivot_options.measures = self.create_field_values(self.pivot_options.measures || [{field:'__count', type: 'integer', string:'Count'}]);
68             self.pivot = new openerp.web_graph.PivotTable(self.model, self.domain, self.fields, self.pivot_options);
69             self.pivot.update_data().then(function () {
70                 self.display_data();
71                 if (self.graph_view) {
72                     self.graph_view.register_groupby(self.pivot.rows.groupby, self.pivot.cols.groupby);
73                 }
74             });
75             openerp.web.bus.on('click', self, function (event) {
76                 if (self.dropdown) {
77                     self.$row_clicked = $(event.target).closest('tr');
78                     self.dropdown.remove();
79                     self.dropdown = null;
80                 }
81             });
82             self.put_measure_checkmarks();
83         });
84     },
85
86     get_groupby_fields: function () {
87         var search_fields = this.get_search_fields(),
88             search_field_names = _.pluck(search_fields, 'field'),
89             other_fields = [],
90             groupable_types = ['many2one', 'char', 'boolean', 'selection', 'date', 'datetime'];
91
92         _.each(this.fields, function (val, key) {
93             if (!_.contains(search_field_names, key) && 
94                 _.contains(groupable_types, val.type) && 
95                 val.store === true) {
96                 other_fields.push({
97                     field: key,
98                     string: val.string,
99                 });
100             }
101         });
102         return search_fields.concat(other_fields);
103     },
104
105     // this method gets the fields that appear in the search view, under the 
106     // 'Groupby' heading
107     get_search_fields: function () {
108         var self = this;
109
110         var groupbygroups = _(this.search_view.drawer.inputs).select(function (g) {
111             return g instanceof openerp.web.search.GroupbyGroup;
112         });
113
114         var filters = _.flatten(_.pluck(groupbygroups, 'filters'), true),
115             groupbys = _.flatten(_.map(filters, function (filter) {
116                 var groupby = py.eval(filter.attrs.context).group_by;
117                 if (!(groupby instanceof Array)) { groupby = [groupby]; }
118                 return _.map(groupby, function(g) {
119                     return {field: g, filter: filter};
120                 });
121             }));
122
123         return _.uniq(_.map(groupbys, function (groupby) {
124             var field = groupby.field,
125                 filter = groupby.filter,
126                 raw_field = field.split(':')[0],
127                 string = (field === raw_field) ? filter.attrs.string : self.fields[raw_field].string;
128             
129             filter = (field === raw_field) ? filter : undefined;
130
131             return { field: raw_field, string: string, filter: filter };
132         }), false, function (filter) {return filter.field;});
133     },
134
135     // Extracts the integer/float fields which are not 'id'
136     get_measures: function() {
137         return _.compact(_.map(this.fields, function (f, id) {
138             if (((f.type === 'integer') || (f.type === 'float')) && 
139                 (id !== 'id') &&
140                 (f.store !== false)) {
141                 return {field:id, type: f.type, string: f.string};
142             }
143         }));
144     },
145
146     add_measures_to_options: function() {
147         this.$('.graph_measure_selection').append(
148         _.map(this.measure_list, function (measure) {
149             return $('<li>').append($('<a>').attr('data-choice', measure.field)
150                                      .attr('href', '#')
151                                      .text(measure.string));
152         }));
153     },
154
155     // ----------------------------------------------------------------------
156     // Configuration methods
157     // ----------------------------------------------------------------------
158     set: function (domain, row_groupby, col_groupby, measures_groupby) {
159         if (!this.pivot) {
160             this.pivot_options.domain = domain;
161             this.pivot_options.row_groupby = row_groupby;
162             this.pivot_options.col_groupby = col_groupby;
163             this.pivot_options.measures_groupby = measures_groupby;
164             return;
165         }
166         var row_gbs = this.create_field_values(row_groupby),
167             col_gbs = this.create_field_values(col_groupby),
168             measures_gbs = this.create_field_values(measures_groupby),
169             dom_changed = !_.isEqual(this.pivot.domain, domain),
170             row_gb_changed = !_.isEqual(row_gbs, this.pivot.rows.groupby),
171             col_gb_changed = !_.isEqual(col_gbs, this.pivot.cols.groupby),
172             measures_gb_changed = !_.isEqual(measures_gbs, this.pivot.measures),
173             row_reduced = is_strict_beginning_of(row_gbs, this.pivot.rows.groupby),
174             col_reduced = is_strict_beginning_of(col_gbs, this.pivot.cols.groupby),
175             measures_reduced = is_strict_beginning_of(measures_gbs, this.pivot.measures);
176
177         if (!dom_changed && row_reduced && !col_gb_changed && !measures_gb_changed) {
178             this.pivot.fold_with_depth(this.pivot.rows, row_gbs.length);
179             this.display_data();
180             return;
181         }
182         if (!dom_changed && col_reduced && !row_gb_changed && !measures_gb_changed) {
183             this.pivot.fold_with_depth(this.pivot.cols, col_gbs.length);
184             this.display_data();
185             return;
186         }
187
188         if (!dom_changed && col_reduced && row_reduced && !measures_gb_changed) {
189             this.pivot.fold_with_depth(this.pivot.rows, row_gbs.length);
190             this.pivot.fold_with_depth(this.pivot.cols, col_gbs.length);
191             this.display_data();
192             return;
193         }
194
195         if (dom_changed || row_gb_changed || col_gb_changed || measures_gb_changed) {
196             this.pivot.set(domain, row_gbs, col_gbs, measures_gbs).then(this.proxy('display_data'));
197         }
198
199         if (measures_gb_changed) {
200             this.put_measure_checkmarks();
201         }
202     },
203
204     set_mode: function (mode) {
205         this.mode = mode;
206
207         if (mode === 'pivot') {
208             this.$('.graph_heatmap label').removeClass('disabled');
209             this.$('.graph_main_content').removeClass('graph_chart_mode').addClass('graph_pivot_mode');
210         } else {
211             this.$('.graph_heatmap label').addClass('disabled');
212             this.$('.graph_main_content').removeClass('graph_pivot_mode').addClass('graph_chart_mode');
213         }
214         this.display_data();
215     },
216
217     set_heatmap_mode: function (mode) { // none, row, col, all
218         this.heatmap_mode = mode;
219         if (mode === 'none') {
220             this.$('.graph_heatmap label').removeClass('disabled');
221             this.$('.graph_heatmap label').removeClass('active');
222         }
223         this.display_data();
224     },
225
226     create_field_value: function (f) {
227         var field = (_.contains(f, ':')) ? f.split(':')[0] : f,
228             groupby_field = _.findWhere(this.groupby_fields, {field:field}),
229             string = groupby_field ? groupby_field.string : this.fields[field].string,
230             result =  {field: f, string: string, type: this.fields[field].type };
231
232         if (groupby_field) {
233             result.filter = groupby_field.filter;
234         }
235
236         return result;
237     },
238
239     create_field_values: function (field_ids) {
240         return _.map(field_ids, this.proxy('create_field_value'));
241     },
242
243
244     get_col_groupbys: function () {
245         return _.pluck(this.pivot.cols.groupby, 'field');
246     },
247
248     get_current_measures: function () {
249         return _.pluck(this.pivot.measures, 'field');
250     },
251
252     // ----------------------------------------------------------------------
253     // UI code
254     // ----------------------------------------------------------------------
255     events: {
256         'click .graph_mode_selection label' : 'mode_selection',
257         'click .graph_measure_selection li' : 'measure_selection',
258         'click .graph_options_selection label' : 'option_selection',
259         'click .graph_heatmap label' : 'heatmap_mode_selection',
260         'click .web_graph_click' : 'header_cell_clicked',
261         'click a.field-selection' : 'field_selection',
262     },
263
264     mode_selection: function (event) {
265         event.preventDefault();
266         var mode = event.currentTarget.getAttribute('data-mode');
267         this.set_mode(mode);
268     },
269
270     measure_selection: function (event) {
271         event.preventDefault();
272         event.stopPropagation();
273         var measure_field = event.target.getAttribute('data-choice');
274         var measure = {
275             field: measure_field,
276             type: this.fields[measure_field].type,
277             string: this.fields[measure_field].string
278         };
279
280         this.pivot.toggle_measure(measure).then(this.proxy('display_data'));
281         this.put_measure_checkmarks();
282     },
283
284     put_measure_checkmarks: function () {
285         var self = this,
286             measures_li = this.$('.graph_measure_selection a');
287         measures_li.removeClass('oe_selected');
288         _.each(this.measure_list, function (measure, index) {
289             if (_.findWhere(self.pivot.measures, measure)) {
290                 measures_li.eq(index).addClass('oe_selected');
291             }
292         });
293
294     },
295
296     option_selection: function (event) {
297         event.preventDefault();
298         switch (event.currentTarget.getAttribute('data-choice')) {
299             case 'swap_axis':
300                 this.swap_axis();
301                 break;
302             case 'expand_all':
303                 this.pivot.expand_all().then(this.proxy('display_data'));
304                 break;
305             case 'update_values':
306                 this.pivot.update_data().then(this.proxy('display_data'));
307                 break;
308             case 'export_data':
309                 this.export_xls();
310                 break;
311         }
312     },
313
314     heatmap_mode_selection: function (event) {
315         event.preventDefault();
316         var mode = event.currentTarget.getAttribute('data-mode');
317         if (this.heatmap_mode === mode) {
318             event.stopPropagation();
319             this.set_heatmap_mode('none');
320         } else {
321             this.set_heatmap_mode(mode);
322         }
323     },
324
325     header_cell_clicked: function (event) {
326         event.preventDefault();
327         event.stopPropagation();
328         var id = event.target.getAttribute('data-id'),
329             header = this.pivot.get_header(id),
330             self = this;
331
332         if (header.expanded) {
333             if (header.root === this.pivot.rows) {
334                 this.fold_row(header, event);
335             } else {
336                 this.fold_col(header);
337             }
338             return;
339         }
340         if (header.path.length < header.root.groupby.length) {
341             this.$row_clicked = $(event.target).closest('tr');
342             this.expand(id);
343             return;
344         }
345         if (!this.groupby_fields.length) {
346             return;
347         }
348
349         var fields = _.map(this.groupby_fields, function (field) {
350                 return {id: field.field, value: field.string, type:self.fields[field.field.split(':')[0]].type};
351         });
352         if (this.dropdown) {
353             this.dropdown.remove();
354         }
355         this.dropdown = $(QWeb.render('field_selection', {fields:fields, header_id:id}));
356         $(event.target).after(this.dropdown);
357         this.dropdown.css({
358             position:'absolute',
359             left:event.originalEvent.layerX,
360         });
361         this.$('.field-selection').next('.dropdown-menu').first().toggle();        
362     },
363
364     field_selection: function (event) {
365         var id = event.target.getAttribute('data-id'),
366             field_id = event.target.getAttribute('data-field-id'),
367             interval,
368             groupby = this.create_field_value(field_id);
369         event.preventDefault();
370         if (this.fields[field_id].type === 'date' || this.fields[field_id].type === 'datetime') {
371             interval = event.target.getAttribute('data-interval');
372             groupby.field =  groupby.field + ':' + interval;
373         }
374         this.expand(id, groupby);
375     },
376
377     // ----------------------------------------------------------------------
378     // Pivot Table integration
379     // ----------------------------------------------------------------------
380     expand: function (header_id, groupby) {
381         var self = this,
382             header = this.pivot.get_header(header_id),
383             update_groupby = !!groupby;
384         
385         groupby = groupby || header.root.groupby[header.path.length];
386
387         this.pivot.expand(header_id, groupby).then(function () {
388             if (header.root === self.pivot.rows) {
389                 // expanding rows can be done by only inserting in the dom
390                 // console.log(event.target);
391                 var rows = self.build_rows(header.children);
392                 var doc_fragment = $(document.createDocumentFragment());
393                 rows.map(function (row) {
394                     doc_fragment.append(self.draw_row(row, 0));
395                 });
396                 self.$row_clicked.after(doc_fragment);
397             } else {
398                 // expanding cols will redraw the full table
399                 self.display_data();                
400             }
401             if (update_groupby && self.graph_view) {
402                 self.graph_view.register_groupby(self.pivot.rows.groupby, self.pivot.cols.groupby);
403             }
404         });
405
406     },
407
408     fold_row: function (header, event) {
409         var rows_before = this.pivot.rows.headers.length,
410             update_groupby = this.pivot.fold(header),
411             rows_after = this.pivot.rows.headers.length,
412             rows_removed = rows_before - rows_after;
413
414         if (rows_after === 1) {
415             // probably faster to redraw the unique row instead of removing everything
416             this.display_data();
417         } else {
418             var $row = $(event.target).parent().parent();
419             $row.nextAll().slice(0,rows_removed).remove();
420         }
421         if (update_groupby && this.graph_view) {
422             this.graph_view.register_groupby(this.pivot.rows.groupby, this.pivot.cols.groupby);
423         }
424     },
425
426     fold_col: function (header) {
427         var update_groupby = this.pivot.fold(header);
428         
429         this.display_data();
430         if (update_groupby && this.graph_view) {
431             this.graph_view.register_groupby(this.pivot.rows.groupby, this.pivot.cols.groupby);
432         }
433     },
434
435     swap_axis: function () {
436         this.pivot.swap_axis();
437         this.display_data();
438         this.graph_view.register_groupby(this.pivot.rows.groupby, this.pivot.cols.groupby);
439     },
440
441     // ----------------------------------------------------------------------
442     // Convert Pivot data structure into table structure :
443     //      compute rows, cols, colors, cell width, cell height, ...
444     // ----------------------------------------------------------------------
445     build_table: function(raw) {
446         return {
447             headers: this.build_headers(),
448             measure_row: this.build_measure_row(),
449             rows: this.build_rows(this.pivot.rows.headers,raw),
450             nbr_measures: this.pivot.measures.length,
451             title: this.title,
452         };
453     },
454
455     build_headers: function () {
456         var pivot = this.pivot,
457             nbr_measures = pivot.measures.length,
458             height = _.max(_.map(pivot.cols.headers, function(g) {return g.path.length;})) + 1,
459             rows = [];
460
461         _.each(pivot.cols.headers, function (col) {
462             var cell_width = nbr_measures * (col.expanded ? pivot.get_ancestor_leaves(col).length : 1),
463                 cell_height = col.expanded ? 1 : height - col.path.length,
464                 cell = {width: cell_width, height: cell_height, title: col.title, id: col.id, expanded: col.expanded};
465             if (rows[col.path.length]) {
466                 rows[col.path.length].push(cell);
467             } else {
468                 rows[col.path.length] = [cell];
469             }
470         });
471
472         if (pivot.get_cols_leaves().length > 1) {
473             rows[0].push({width: nbr_measures, height: height, title: ' ', id: pivot.main_col().id });
474         }
475         if (pivot.cols.headers.length === 1) {
476             rows = [[{width: nbr_measures, height: 1, title: _t('Total'), id: pivot.main_col().id, expanded: false}]];
477         }
478         return rows;
479     },
480
481     build_measure_row: function () {
482         var nbr_leaves = this.pivot.get_cols_leaves().length,
483             nbr_cols = nbr_leaves + ((nbr_leaves > 1) ? 1 : 0),
484             result = [],
485             add_total = this.pivot.get_cols_leaves().length > 1,
486             i, m;
487         for (i = 0; i < nbr_cols; i++) {
488             for (m = 0; m < this.pivot.measures.length; m++) {
489                 result.push({
490                     text:this.pivot.measures[m].string,
491                     is_bold: add_total && (i === nbr_cols - 1)
492                 });
493             }
494         }
495         return result;
496     },
497
498     make_cell: function (row, col, value, index, raw) {
499         var formatted_value = raw && !_.isUndefined(value) ? value : openerp.web.format_value(value, {type:this.pivot.measures[index].type}),
500             cell = {value:formatted_value};
501
502         if (this.heatmap_mode === 'none') { return cell; }
503         var total = (this.heatmap_mode === 'both') ? this.pivot.get_total()[index]
504                   : (this.heatmap_mode === 'row')  ? this.pivot.get_total(row)[index]
505                   : this.pivot.get_total(col)[index];
506         var color = Math.floor(90 + 165*(total - Math.abs(value))/total);
507         if (color < 255) {
508             cell.color = color;
509         }
510         return cell;
511     },
512
513     build_rows: function (headers, raw) {
514         var self = this,
515             pivot = this.pivot,
516             m, i, j, k, cell, row;
517
518         var rows = [];
519         var cells, pivot_cells, values;
520
521         var nbr_of_rows = headers.length;
522         var col_headers = pivot.get_cols_leaves();
523
524         for (i = 0; i < nbr_of_rows; i++) {
525             row = headers[i];
526             cells = [];
527             pivot_cells = [];
528             for (j = 0; j < pivot.cells.length; j++) {
529                 if (pivot.cells[j].x == row.id || pivot.cells[j].y == row.id) {
530                     pivot_cells.push(pivot.cells[j]);
531                 }              
532             }
533
534             for (j = 0; j < col_headers.length; j++) {
535                 values = undefined;
536                 for (k = 0; k < pivot_cells.length; k++) {
537                     if (pivot_cells[k].x == col_headers[j].id || pivot_cells[k].y == col_headers[j].id) {
538                         values = pivot_cells[k].values;
539                         break;
540                     }               
541                 }
542                 if (!values) { values = new Array(pivot.measures.length);}
543                 for (m = 0; m < pivot.measures.length; m++) {
544                     cells.push(self.make_cell(row,col_headers[j],values[m], m, raw));
545                 }
546             }
547             if (col_headers.length > 1) {
548                 var totals = pivot.get_total(row);
549                 for (m = 0; m < pivot.measures.length; m++) {
550                     cell = self.make_cell(row, pivot.cols.headers[0], totals[m], m, raw);
551                     cell.is_bold = 'true';
552                     cells.push(cell);
553                 }
554             }
555             rows.push({
556                 id: row.id,
557                 indent: row.path.length,
558                 title: row.title,
559                 expanded: row.expanded,
560                 cells: cells,
561             });
562         }
563
564         return rows;
565     },
566
567     // ----------------------------------------------------------------------
568     // Main display method
569     // ----------------------------------------------------------------------
570     display_data: function () {
571         var scroll = $(window).scrollTop();
572         this.$('.graph_main_content svg').remove();
573         this.$('.graph_main_content div').remove();
574         this.table.empty();
575         this.table.toggleClass('heatmap', this.heatmap_mode !== 'none');
576         this.$('.graph_options_selection label').last().toggleClass('disabled', this.pivot.no_data);
577         this.width = this.$el.width();
578         this.height = Math.min(Math.max(document.documentElement.clientHeight - 116 - 60, 250), Math.round(0.8*this.$el.width()));
579
580         this.$('.graph_header').toggle(this.visible_ui);
581         if (this.pivot.no_data) {
582             this.$('.graph_main_content').append($(QWeb.render('graph_no_data')));
583         } else {
584             if (this.mode === 'pivot') {
585                 this.draw_table();
586                 $(window).scrollTop(scroll);
587             } else {
588                 this.$('.graph_main_content').append($('<div><svg>'));
589                 this.svg = this.$('.graph_main_content svg')[0];
590                 this[this.mode]();
591             }
592         }
593     },
594
595     // ----------------------------------------------------------------------
596     // Drawing the table
597     // ----------------------------------------------------------------------
598     draw_table: function () {
599         var custom_gbs = this.graph_view.get_custom_filter_groupbys(),
600             frozen_rows = custom_gbs.groupby.length,
601             frozen_cols = custom_gbs.col_groupby.length;
602
603         var table = this.build_table();
604         var doc_fragment = $(document.createDocumentFragment());
605         this.draw_headers(table.headers, doc_fragment, frozen_cols);
606         this.draw_measure_row(table.measure_row, doc_fragment);
607         this.draw_rows(table.rows, doc_fragment, frozen_rows);
608         this.table.append(doc_fragment);
609     },
610
611     make_header_cell: function (header, frozen) {
612         var cell = (_.has(header, 'cells') ? $('<td>') : $('<th>'))
613                         .addClass('graph_border')
614                         .attr('rowspan', header.height)
615                         .attr('colspan', header.width);
616         var $content = $('<span>').attr('href','#')
617                                  .text(' ' + (header.title || _t('Undefined')))
618                                  .css('margin-left', header.indent*30 + 'px')
619                                  .attr('data-id', header.id);
620         if (_.has(header, 'expanded')) {
621             if (('indent' in header) && header.indent >= frozen) {
622                 $content.addClass(header.expanded ? 'fa fa-minus-square' : 'fa fa-plus-square');
623                 $content.addClass('web_graph_click');
624             }
625             if (!('indent' in header) && header.lvl >= frozen) {
626                 $content.addClass(header.expanded ? 'fa fa-minus-square' : 'fa fa-plus-square');
627                 $content.addClass('web_graph_click');
628             }
629         } else {
630             $content.css('font-weight', 'bold');
631         }
632         return cell.append($content);
633     },
634
635     draw_headers: function (headers, doc_fragment, frozen_cols) {
636         var make_cell = this.make_header_cell,
637             $empty_cell = $('<th>').attr('rowspan', headers.length),
638             $thead = $('<thead>');
639
640         _.each(headers, function (row, lvl) {
641             var $row = $('<tr>');
642             _.each(row, function (header) {
643                 header.lvl = lvl;
644                 $row.append(make_cell(header, frozen_cols));
645             });
646             $thead.append($row);
647         });
648         $thead.children(':first').prepend($empty_cell);
649         doc_fragment.append($thead);
650         this.$thead = $thead;
651     },
652     
653     draw_measure_row: function (measure_row) {
654         var $row = $('<tr>').append('<th>');
655         _.each(measure_row, function (cell) {
656             var $cell = $('<th>').addClass('measure_row').text(cell.text);
657             if (cell.is_bold) {$cell.css('font-weight', 'bold');}
658             $row.append($cell);
659         });
660         this.$thead.append($row);
661     },
662     
663     draw_row: function (row, frozen_rows) {
664         var $row = $('<tr>')
665             .attr('data-indent', row.indent)
666             .append(this.make_header_cell(row, frozen_rows));
667         
668         var cells_length = row.cells.length;
669         var cells_list = [];
670         var cell, hcell;
671
672         for (var j = 0; j < cells_length; j++) {
673             cell = row.cells[j];
674             hcell = '<td';
675             if (cell.is_bold || cell.color) {
676                 hcell += ' style="';
677                 if (cell.is_bold) hcell += 'font-weight: bold;';
678                 if (cell.color) hcell += 'background-color:' + $.Color(255, cell.color, cell.color) + ';';
679                 hcell += '"';
680             }
681             hcell += '>' + cell.value + '</td>';
682             cells_list[j] = hcell;
683         }
684         return $row.append(cells_list.join(''));
685     },
686
687     draw_rows: function (rows, doc_fragment, frozen_rows) {
688         var rows_length = rows.length,
689             $tbody = $('<tbody>');
690
691         doc_fragment.append($tbody);
692         for (var i = 0; i < rows_length; i++) {
693             $tbody.append(this.draw_row(rows[i], frozen_rows));
694         }
695     },
696
697     // ----------------------------------------------------------------------
698     // Drawing charts code
699     // ----------------------------------------------------------------------
700     bar: function () {
701         var self = this,
702             dim_x = this.pivot.rows.groupby.length,
703             dim_y = this.pivot.cols.groupby.length,
704             show_controls = (this.width > 400 && this.height > 300 && dim_x + dim_y >=2),
705             data;
706
707         // No groupby 
708         if ((dim_x === 0) && (dim_y === 0)) {
709             data = [{key: _t('Total'), values:[{
710                 x: _t('Total'),
711                 y: this.pivot.get_total()[0],
712             }]}];
713         // Only column groupbys 
714         } else if ((dim_x === 0) && (dim_y >= 1)){
715             data =  _.map(this.pivot.get_cols_with_depth(1), function (header) {
716                 return {
717                     key: header.title,
718                     values: [{x:header.title, y: self.pivot.get_total(header)[0]}]
719                 };
720             });
721         // Just 1 row groupby 
722         } else if ((dim_x === 1) && (dim_y === 0))  {
723             data = _.map(this.pivot.main_row().children, function (pt) {
724                 var value = self.pivot.get_total(pt)[0],
725                     title = (pt.title !== undefined) ? pt.title : _t('Undefined');
726                 return {x: title, y: value};
727             });
728             data = [{key: self.pivot.measures[0].string, values:data}];
729         // 1 row groupby and some col groupbys
730         } else if ((dim_x === 1) && (dim_y >= 1))  {
731             data = _.map(this.pivot.get_cols_with_depth(1), function (colhdr) {
732                 var values = _.map(self.pivot.get_rows_with_depth(1), function (header) {
733                     return {
734                         x: header.title || _t('Undefined'),
735                         y: self.pivot.get_values(header.id, colhdr.id)[0] || 0
736                     };
737                 });
738                 return {key: colhdr.title || _t('Undefined'), values: values};
739             });
740         // At least two row groupby
741         } else {
742             var keys = _.uniq(_.map(this.pivot.get_rows_with_depth(2), function (hdr) {
743                 return hdr.title || _t('Undefined');
744             }));
745             data = _.map(keys, function (key) {
746                 var values = _.map(self.pivot.get_rows_with_depth(1), function (hdr) {
747                     var subhdr = _.find(hdr.children, function (child) {
748                         return ((child.title === key) || ((child.title === undefined) && (key === _t('Undefined'))));
749                     });
750                     return {
751                         x: hdr.title || _t('Undefined'),
752                         y: (subhdr) ? self.pivot.get_total(subhdr)[0] : 0
753                     };
754                 });
755                 return {key:key, values: values};
756             });
757         }
758
759         nv.addGraph(function () {
760           var chart = nv.models.multiBarChart()
761                 .reduceXTicks(false)
762                 .stacked(self.bar_ui === 'stack')
763                 .showControls(show_controls);
764
765             if (self.width / data[0].values.length < 80) {
766                 chart.rotateLabels(-15);
767                 chart.reduceXTicks(true);
768                 chart.margin({bottom:40});
769             }
770
771             d3.select(self.svg)
772                 .datum(data)
773                 .attr('width', self.width)
774                 .attr('height', self.height)
775                 .call(chart);
776
777             nv.utils.windowResize(chart.update);
778             return chart;
779         });
780
781     },
782
783     line: function () {
784         var self = this,
785             dim_x = this.pivot.rows.groupby.length,
786             dim_y = this.pivot.cols.groupby.length;
787
788         var rows = this.pivot.get_rows_with_depth(dim_x),
789             labels = _.pluck(rows, 'title');
790
791         var data = _.map(this.pivot.get_cols_leaves(), function (col) {
792             var values = _.map(rows, function (row, index) {
793                 return {x: index, y: self.pivot.get_values(row.id,col.id)[0] || 0};
794             });
795             var title = _.map(col.path, function (p) {
796                 return p || _t('Undefined');
797             }).join('/');
798             if (dim_y === 0) {
799                 title = self.pivot.measures[0].string;
800             }
801             return {values: values, key: title};
802         });
803
804         nv.addGraph(function () {
805             var chart = nv.models.lineChart()
806                 .x(function (d,u) { return u; });
807
808             chart.xAxis.tickFormat(function (d,u) {return labels[d];});
809
810             d3.select(self.svg)
811                 .attr('width', self.width)
812                 .attr('height', self.height)
813                 .datum(data)
814                 .call(chart);
815
816             return chart;
817           });
818     },
819
820     pie: function () {
821         var self = this,
822             dim_x = this.pivot.rows.groupby.length;
823         var data = _.map(this.pivot.get_rows_leaves(), function (row) {
824             var title = _.map(row.path, function (p) {
825                 return p || _t('Undefined');
826             }).join('/');
827             if (dim_x === 0) {
828                 title = self.measure_label;
829             }
830             return {x: title, y: self.pivot.get_total(row)[0]};
831         });
832
833         nv.addGraph(function () {
834             var chart = nv.models.pieChart()
835                 .width(self.width)
836                 .height(self.height)
837                 .color(d3.scale.category10().range());
838
839             d3.select(self.svg)
840                 .datum(data)
841                 .transition().duration(1200)
842                 .attr('width', self.width)
843                 .attr('height', self.height)
844                 .call(chart);
845
846             nv.utils.windowResize(chart.update);
847             return chart;
848         });
849     },
850
851     // ----------------------------------------------------------------------
852     // Controller stuff...
853     // ----------------------------------------------------------------------
854     export_xls: function() {
855         var c = openerp.webclient.crashmanager;
856         openerp.web.blockUI();
857         this.session.get_file({
858             url: '/web_graph/export_xls',
859             data: {data: JSON.stringify(this.build_table(true))},
860             complete: openerp.web.unblockUI,
861             error: c.rpc_error.bind(c)
862         });
863     },
864
865 });
866
867 // Utility function: returns true if the beginning of array2 is array1 and
868 // if array1 is not array2
869 function is_strict_beginning_of (array1, array2) {
870     if (array1.length >= array2.length) { return false; }
871     var result = true;
872     for (var i = 0; i < array1.length; i++) {
873         if (!_.isEqual(array1[i], array2[i])) { return false;}
874     }
875     return result;
876 }
877 })();