1 openerp.web_kanban = function (instance) {
3 var _t = instance.web._t,
4 _lt = instance.web._lt;
5 var QWeb = instance.web.qweb;
6 instance.web.views.add('kanban', 'instance.web_kanban.KanbanView');
8 instance.web_kanban.KanbanView = instance.web.View.extend({
9 template: "KanbanView",
10 display_name: _lt('Kanban'),
11 default_nr_columns: 1,
13 quick_create_class: "instance.web_kanban.QuickCreate",
14 number_of_color_schemes: 10,
15 init: function (parent, dataset, view_id, options) {
16 this._super(parent, dataset, view_id, options);
18 _.defaults(this.options, {
19 "quick_creatable": true,
21 "create_text": undefined,
22 "read_only_mode": false,
23 "confirm_on_delete": true,
25 this.fields_view = {};
26 this.fields_keys = [];
28 this.group_by_field = {};
29 this.grouped_by_m2o = false;
37 this.group_operators = ['avg', 'max', 'min', 'sum', 'count'];
38 this.qweb = new QWeb2.Engine();
39 this.qweb.debug = instance.session.debug;
40 this.qweb.default_dict = _.clone(QWeb.default_dict);
41 this.has_been_loaded = $.Deferred();
42 this.search_domain = this.search_context = this.search_group_by = null;
43 this.currently_dragging = {};
44 this.limit = options.limit || 40;
45 this.add_group_mutex = new $.Mutex();
46 if (!this.options.$buttons || !this.options.$buttons.length) {
47 this.options.$buttons = false;
50 view_loading: function(r) {
51 return this.load_kanban(r);
55 this._super.apply(this, arguments);
56 this.$el.on('click', '.oe_kanban_dummy_cell', function() {
58 self.$buttons.find('.oe_kanban_add_column').openerpBounce();
63 this._super.apply(this, arguments);
64 $('html').off('click.kanban');
66 load_kanban: function(data) {
67 this.fields_view = data;
69 // use default order if defined in xml description
70 var default_order = this.fields_view.arch.attrs.default_order,
71 unsorted = !this.dataset._sort.length;
72 if (unsorted && default_order) {
73 this.dataset.set_sort(default_order.split(','));
75 this.$el.addClass(this.fields_view.arch.attrs['class']);
76 this.$buttons = $(QWeb.render("KanbanView.buttons", {'widget': this}));
77 if (this.options.$buttons) {
78 this.$buttons.appendTo(this.options.$buttons);
80 this.$('.oe_kanban_buttons').replaceWith(this.$buttons);
83 .on('click', 'button.oe_kanban_button_new', this.do_add_record)
84 .on('click', '.oe_kanban_add_column', this.do_add_group);
85 this.$groups = this.$el.find('.oe_kanban_groups tr');
86 this.fields_keys = _.keys(this.fields_view.fields);
87 this.add_qweb_template();
88 this.has_been_loaded.resolve();
89 this.trigger('kanban_view_loaded', data);
92 _is_quick_create_enabled: function() {
93 if (!this.options.quick_creatable || !this.is_action_enabled('create'))
95 if (this.fields_view.arch.attrs.quick_create !== undefined)
96 return JSON.parse(this.fields_view.arch.attrs.quick_create);
97 return !! this.group_by;
99 is_action_enabled: function(action) {
100 if (action === 'create' && !this.options.creatable)
102 return this._super(action);
105 * select the nodes into the xml and send to extract_aggregates the nodes with TagName="field"
107 add_qweb_template: function() {
108 for (var i=0, ii=this.fields_view.arch.children.length; i < ii; i++) {
109 var child = this.fields_view.arch.children[i];
110 if (child.tag === "templates") {
111 this.transform_qweb_template(child);
112 this.qweb.add_template(instance.web.json_node_to_xml(child));
114 } else if (child.tag === 'field') {
115 this.extract_aggregates(child);
119 /* extract_aggregates
120 * extract the agggregates from the nodes (TagName="field")
122 extract_aggregates: function(node) {
123 for (var j = 0, jj = this.group_operators.length; j < jj; j++) {
124 if (node.attrs[this.group_operators[j]]) {
125 this.aggregates[node.attrs.name] = node.attrs[this.group_operators[j]];
130 transform_qweb_template: function(node) {
131 var qweb_add_if = function(node, condition) {
132 if (node.attrs[QWeb.prefix + '-if']) {
133 condition = _.str.sprintf("(%s) and (%s)", node.attrs[QWeb.prefix + '-if'], condition);
135 node.attrs[QWeb.prefix + '-if'] = condition;
138 if (node.tag && node.attrs.modifiers) {
139 var modifiers = JSON.parse(node.attrs.modifiers || '{}');
140 if (modifiers.invisible) {
141 qweb_add_if(node, _.str.sprintf("!kanban_compute_domain(%s)", JSON.stringify(modifiers.invisible)));
146 var ftype = this.fields_view.fields[node.attrs.name].type;
147 ftype = node.attrs.widget ? node.attrs.widget : ftype;
148 if (ftype === 'many2many') {
149 if (_.indexOf(this.many2manys, node.attrs.name) < 0) {
150 this.many2manys.push(node.attrs.name);
153 node.attrs['class'] = (node.attrs['class'] || '') + ' oe_form_field oe_tags';
154 } else if (instance.web_kanban.fields_registry.contains(ftype)) {
155 // do nothing, the kanban record will handle it
157 node.tag = QWeb.prefix;
158 node.attrs[QWeb.prefix + '-esc'] = 'record.' + node.attrs['name'] + '.value';
163 var type = node.attrs.type || '';
164 if (_.indexOf('action,object,edit,open,delete,url'.split(','), type) !== -1) {
165 _.each(node.attrs, function(v, k) {
166 if (_.indexOf('icon,type,name,args,string,context,states,kanban_states'.split(','), k) != -1) {
167 node.attrs['data-' + k] = v;
168 delete(node.attrs[k]);
171 if (node.attrs['data-string']) {
172 node.attrs.title = node.attrs['data-string'];
174 if (node.attrs['data-icon']) {
178 src: instance.session.prefix + '/web/static/src/img/icons/' + node.attrs['data-icon'] + '.png',
184 if (node.tag == 'a' && node.attrs['data-type'] != "url") {
185 node.attrs.href = '#';
187 node.attrs.type = 'button';
189 node.attrs['class'] = (node.attrs['class'] || '') + ' oe_kanban_action oe_kanban_action_' + node.tag;
194 for (var i = 0, ii = node.children.length; i < ii; i++) {
195 this.transform_qweb_template(node.children[i]);
199 do_add_record: function() {
200 this.dataset.index = null;
201 this.do_switch_view('form');
203 do_add_group: function() {
206 name: _t("Add column"),
207 res_model: self.group_by_field.relation,
208 views: [[false, 'form']],
209 type: 'ir.actions.act_window',
211 context: self.dataset.get_context(),
213 action_buttons: true,
216 var am = instance.webclient.action_manager;
217 var form = am.dialog_widget.views.form.controller;
218 form.on("on_button_cancel", am.dialog, am.dialog.close);
219 form.on('record_created', self, function(r) {
220 (new instance.web.DataSet(self, self.group_by_field.relation)).name_get([r]).done(function(new_record) {
222 var domain = self.dataset.domain.slice(0);
223 domain.push([self.group_by, '=', new_record[0][0]]);
224 var dataset = new instance.web.DataSetSearch(self, self.dataset.model, self.dataset.get_context(), domain);
229 value: new_record[0],
233 var new_group = new instance.web_kanban.KanbanGroup(self, [], datagroup, dataset);
234 self.do_add_groups([new_group]).done(function() {
235 $(window).scrollTo(self.groups.slice(-1)[0].$el, { axis: 'x' });
240 do_search: function(domain, context, group_by) {
242 this.search_domain = domain;
243 this.search_context = context;
244 this.search_group_by = group_by;
245 return $.when(this.has_been_loaded).then(function() {
246 self.group_by = group_by.length ? group_by[0] : self.fields_view.arch.attrs.default_group_by;
247 self.group_by_field = self.fields_view.fields[self.group_by] || {};
248 self.grouped_by_m2o = (self.group_by_field.type === 'many2one');
249 self.$buttons.find('.oe_alternative').toggle(self.grouped_by_m2o);
250 self.$el.toggleClass('oe_kanban_grouped_by_m2o', self.grouped_by_m2o);
251 var grouping_fields = self.group_by ? [self.group_by].concat(_.keys(self.aggregates)) : undefined;
252 if (!_.isEmpty(grouping_fields)) {
253 // ensure group_by fields are read.
254 self.fields_keys = _.unique(self.fields_keys.concat(grouping_fields));
256 var grouping = new instance.web.Model(self.dataset.model, context, domain).query(self.fields_keys).group_by(grouping_fields);
257 return self.alive($.when(grouping)).then(function(groups) {
258 self.remove_no_result();
260 return self.do_process_groups(groups);
262 return self.do_process_dataset();
267 do_process_groups: function(groups) {
269 this.$el.find('table:first').show();
270 this.$el.removeClass('oe_kanban_ungrouped').addClass('oe_kanban_grouped');
271 return this.add_group_mutex.exec(function() {
272 self.do_clear_groups();
273 self.dataset.ids = [];
274 if (!groups.length) {
279 var remaining = groups.length - 1,
281 return $.when.apply(null, _.map(groups, function (group, index) {
282 var def = $.when([]);
283 var dataset = new instance.web.DataSetSearch(self, self.dataset.model,
284 new instance.web.CompoundContext(self.dataset.get_context(), group.model.context()), group.model.domain());
285 if (group.attributes.length >= 1) {
286 def = dataset.read_slice(self.fields_keys.concat(['__last_update']), { 'limit': self.limit });
288 return def.then(function(records) {
289 self.nb_records += records.length;
290 self.dataset.ids.push.apply(self.dataset.ids, dataset.ids);
291 groups_array[index] = new instance.web_kanban.KanbanGroup(self, records, group, dataset);
292 if (self.dataset.index >= records.length){
293 self.dataset.index = self.dataset.size() ? 0 : null;
296 return self.do_add_groups(groups_array);
299 })).then(function () {
300 if(!self.nb_records) {
303 self.trigger('kanban_groups_processed');
307 do_process_dataset: function() {
309 this.$el.find('table:first').show();
310 this.$el.removeClass('oe_kanban_grouped').addClass('oe_kanban_ungrouped');
311 var def = $.Deferred();
312 this.add_group_mutex.exec(function() {
313 self.do_clear_groups();
314 self.dataset.read_slice(self.fields_keys.concat(['__last_update']), { 'limit': self.limit }).done(function(records) {
315 var kgroup = new instance.web_kanban.KanbanGroup(self, records, null, self.dataset);
316 if (!_.isEmpty(self.dataset.ids) && (self.dataset.index === null || self.dataset.index >= self.dataset.ids.length)) {
317 self.dataset.index = 0;
318 } else if (_.isEmpty(self.dataset.ids)){
319 self.dataset.index = null;
321 self.do_add_groups([kgroup]).done(function() {
322 if (_.isEmpty(records)) {
325 self.trigger('kanban_dataset_processed');
328 }).done(null, function() {
334 do_reload: function() {
335 this.do_search(this.search_domain, this.search_context, this.search_group_by);
337 do_clear_groups: function() {
338 var groups = this.groups.slice(0);
340 _.each(groups, function(group) {
344 do_add_groups: function(groups) {
346 var $parent = this.$el.parent();
348 _.each(groups, function(group) {
349 self.groups[group.undefined_title ? 'unshift' : 'push'](group);
351 var $last_td = self.$el.find('.oe_kanban_groups_headers td:last');
352 var groups_started = _.map(this.groups, function(group) {
353 if (!group.is_started) {
354 group.on("add_record", self, function () {
355 self.remove_no_result();
357 return group.insertBefore($last_td);
360 return $.when.apply(null, groups_started).done(function () {
361 self.on_groups_started();
362 self.$el.appendTo($parent);
363 _.each(self.groups, function(group) {
364 group.compute_cards_auto_height();
368 on_groups_started: function() {
370 if (this.group_by || this.fields_keys.indexOf("sequence") !== -1) {
371 // Kanban cards drag'n'drop
372 var prev_widget, is_folded, record, $columns;
374 $columns = this.$el.find('.oe_kanban_column .oe_kanban_column_cards, .oe_kanban_column .oe_kanban_folded_column_cards');
376 $columns = this.$el.find('.oe_kanban_column_cards');
379 handle : '.oe_kanban_draghandle',
380 start: function(event, ui) {
381 self.currently_dragging.index = ui.item.parent().children('.oe_kanban_record').index(ui.item);
382 self.currently_dragging.group = prev_widget = ui.item.parents('.oe_kanban_column:first').data('widget');
383 ui.item.find('*').on('click.prevent', function(ev) {
386 record = ui.item.data('widget');
387 record.$el.bind('mouseup',function(ev,ui){
391 record.$el.unbind('mouseup');
393 ui.placeholder.height(ui.item.height());
395 over: function(event, ui) {
396 var parent = $(event.target).parent();
397 prev_widget.highlight(false);
398 is_folded = parent.hasClass('oe_kanban_group_folded');
400 var widget = parent.data('widget');
401 widget.highlight(true);
402 prev_widget = widget;
406 stop: function(event, ui) {
407 prev_widget.highlight(false);
408 var old_index = self.currently_dragging.index;
409 var new_index = ui.item.parent().children('.oe_kanban_record').index(ui.item);
410 var old_group = self.currently_dragging.group;
411 var new_group = ui.item.parents('.oe_kanban_column:first').data('widget');
412 if (!(old_group.title === new_group.title && old_group.value === new_group.value && old_index == new_index)) {
413 self.on_record_moved(record, old_group, old_index, new_group, new_index);
415 setTimeout(function() {
416 // A bit hacky but could not find a better solution for Firefox (problem not present in chrome)
417 // http://stackoverflow.com/questions/274843/preventing-javascript-click-event-with-scriptaculous-drag-and-drop
418 ui.item.find('*').off('click.prevent');
423 // Keep connectWith out of the sortable initialization for performance sake:
424 // http://www.planbox.com/blog/development/coding/jquery-ui-sortable-slow-to-bind.html
425 $columns.sortable({ connectWith: $columns });
427 // Kanban groups drag'n'drop
429 if (this.grouped_by_m2o) {
430 this.$('.oe_kanban_groups_headers').sortable({
431 items: '.oe_kanban_group_header',
436 start: function(event, ui) {
437 start_index = ui.item.index();
438 self.$('.oe_kanban_record, .oe_kanban_quick_create').css({ visibility: 'hidden' });
440 stop: function(event, ui) {
441 var stop_index = ui.item.index();
442 if (start_index !== stop_index) {
443 var $start_column = self.$('.oe_kanban_groups_records .oe_kanban_column').eq(start_index);
444 var $stop_column = self.$('.oe_kanban_groups_records .oe_kanban_column').eq(stop_index);
445 var method = (start_index > stop_index) ? 'insertBefore' : 'insertAfter';
446 $start_column[method]($stop_column);
447 var tmp_group = self.groups.splice(start_index, 1)[0];
448 self.groups.splice(stop_index, 0, tmp_group);
449 var new_sequence = _.pluck(self.groups, 'value');
450 (new instance.web.DataSet(self, self.group_by_field.relation)).resequence(new_sequence).done(function(r) {
452 console.error("Kanban: could not resequence model '%s'. Probably no 'sequence' field.", self.group_by_field.relation);
456 self.$('.oe_kanban_record, .oe_kanban_quick_create').css({ visibility: 'visible' });
461 this.$el.find('.oe_kanban_draghandle').removeClass('oe_kanban_draghandle');
463 this.postprocess_m2m_tags();
465 on_record_moved : function(record, old_group, old_index, new_group, new_index) {
467 record.$el.find('[title]').tooltip('destroy');
468 $(old_group.$el).add(new_group.$el).find('.oe_kanban_aggregates, .oe_kanban_group_length').hide();
469 if (old_group === new_group) {
470 new_group.records.splice(old_index, 1);
471 new_group.records.splice(new_index, 0, record);
472 new_group.do_save_sequences();
474 old_group.records.splice(old_index, 1);
475 new_group.records.splice(new_index, 0, record);
476 record.group = new_group;
478 data[this.group_by] = new_group.value;
479 this.dataset.write(record.id, data, {}).done(function() {
481 new_group.do_save_sequences();
482 if (new_group.state.folded) {
483 new_group.do_action_toggle_fold();
484 record.prependTo(new_group.$records.find('.oe_kanban_column_cards'));
486 }).fail(function(error, evt) {
487 evt.preventDefault();
488 alert(_t("An error has occured while moving the record to this group: ") + error.data.message);
489 self.do_reload(); // TODO: use draggable + sortable in order to cancel the dragging when the rcp fails
494 do_show: function() {
495 if (this.options.$buttons) {
496 this.$buttons.show();
498 this.do_push_state({});
499 return this._super();
501 do_hide: function () {
503 this.$buttons.hide();
505 return this._super();
507 open_record: function(id, editable) {
508 if (this.dataset.select_id(id)) {
509 this.do_switch_view('form', null, { mode: editable ? "edit" : undefined });
511 this.do_warn("Kanban: could not find id#" + id);
514 no_result: function() {
516 if (this.groups.group_by
517 || !this.options.action
518 || (!this.options.action.help && !this.options.action.get_empty_list_help)) {
521 this.$el.css("position", "relative");
522 $(QWeb.render('KanbanView.nocontent', { content : this.options.action.get_empty_list_help || this.options.action.help})).insertBefore(this.$('table:first'));
523 this.$el.find('.oe_view_nocontent').click(function() {
524 self.$buttons.openerpBounce();
527 remove_no_result: function() {
528 this.$el.css("position", "");
529 this.$el.find('.oe_view_nocontent').remove();
533 * postprocessing of fields type many2many
534 * make the rpc request for all ids/model and insert value inside .oe_tags fields
536 postprocess_m2m_tags: function() {
538 if (!this.many2manys.length) {
542 this.groups.forEach(function(group) {
543 group.records.forEach(function(record) {
544 self.many2manys.forEach(function(name) {
545 var field = record.record[name];
546 var $el = record.$('.oe_form_field.oe_tags[name=' + name + ']').empty();
547 if (!relations[field.relation]) {
548 relations[field.relation] = { ids: [], elements: {}};
550 var rel = relations[field.relation];
551 field.raw_value.forEach(function(id) {
553 if (!rel.elements[id]) {
554 rel.elements[id] = [];
556 rel.elements[id].push($el[0]);
561 _.each(relations, function(rel, rel_name) {
562 var dataset = new instance.web.DataSetSearch(self, rel_name, self.dataset.get_context());
563 dataset.name_get(_.uniq(rel.ids)).done(function(result) {
564 result.forEach(function(nameget) {
565 $(rel.elements[nameget[0]]).append('<span class="oe_tag">' + _.str.escapeHTML(nameget[1]) + '</span>');
573 function get_class(name) {
574 return new instance.web.Registry({'tmp' : name}).get_object("tmp");
577 instance.web_kanban.KanbanGroup = instance.web.Widget.extend({
578 template: 'KanbanView.group_header',
579 init: function (parent, records, group, dataset) {
582 this.$has_been_started = $.Deferred();
585 this.dataset = dataset;
586 this.dataset_offset = 0;
587 this.aggregates = {};
588 this.value = this.title = null;
590 this.value = group.get('value');
591 this.title = group.get('value');
592 if (this.value instanceof Array) {
593 this.title = this.value[1];
594 this.value = this.value[0];
596 var field = this.view.group_by_field;
597 if (!_.isEmpty(field)) {
599 this.title = instance.web.format_value(group.get('value'), field, false);
602 _.each(this.view.aggregates, function(value, key) {
603 self.aggregates[value] = instance.web.format_value(group.get('aggregates')[key], {type: 'float'});
607 if (this.title === false) {
608 this.title = _t('Undefined');
609 this.undefined_title = true;
611 var key = this.view.group_by + '-' + this.value;
612 if (!this.view.state.groups[key]) {
613 this.view.state.groups[key] = {
614 folded: group ? group.get('folded') : false
617 this.state = this.view.state.groups[key];
618 this.$records = null;
621 this.$has_been_started.done(function() {
622 self.do_add_records(records);
627 if (! self.view.group_by) {
628 self.$el.addClass("oe_kanban_no_group");
629 self.quick = new (get_class(self.view.quick_create_class))(this, self.dataset, {}, false)
630 .on('added', self, self.proxy('quick_created'));
631 self.quick.replace($(".oe_kanban_no_group_qc_placeholder"));
633 this.$records = $(QWeb.render('KanbanView.group_records_container', { widget : this}));
634 this.$records.insertBefore(this.view.$el.find('.oe_kanban_groups_records td:last'));
636 this.$el.on('click', '.oe_kanban_group_dropdown li a', function(ev) {
637 var fn = 'do_action_' + $(ev.target).data().action;
638 if (typeof(self[fn]) === 'function') {
639 self[fn]($(ev.target));
643 this.$el.find('.oe_kanban_add').click(function () {
644 if (self.view.quick) {
645 self.view.quick.trigger('close');
650 self.view.$el.find('.oe_view_nocontent').hide();
652 ctx['default_' + self.view.group_by] = self.value;
653 self.quick = new (get_class(self.view.quick_create_class))(this, self.dataset, ctx, true)
654 .on('added', self, self.proxy('quick_created'))
655 .on('close', self, function() {
656 self.view.$el.find('.oe_view_nocontent').show();
657 this.quick.destroy();
658 delete self.view.quick;
661 self.quick.appendTo($(".oe_kanban_group_list_header", self.$records));
663 self.view.quick = self.quick;
665 // Add bounce effect on image '+' of kanban header when click on empty space of kanban grouped column.
666 this.$records.on('click', '.oe_kanban_show_more', this.do_show_more);
667 if (this.state.folded) {
668 this.do_toggle_fold();
670 this.$el.data('widget', this);
671 this.$records.data('widget', this);
672 this.$has_been_started.resolve();
673 var add_btn = this.$el.find('.oe_kanban_add');
674 add_btn.tooltip({delay: { show: 500, hide:1000 }});
675 this.$records.find(".oe_kanban_column_cards").click(function (ev) {
676 if (ev.target == ev.currentTarget) {
677 if (!self.state.folded) {
678 add_btn.openerpBounce();
682 this.is_started = true;
683 var def_tooltip = this.fetch_tooltip();
684 return $.when(def_tooltip);
686 fetch_tooltip: function() {
689 var field_name = this.view.group_by;
690 var field = this.view.group_by_field;
691 var field_desc = null;
692 var recurse = function(node) {
693 if (node.tag === "field" && node.attrs.name === field_name) {
697 _.each(node.children, function(child) {
698 if (field_desc === null)
702 recurse(this.view.fields_view.arch);
705 var options = instance.web.py_eval(field_desc.attrs.options || '{}')
706 if (! options.tooltip_on_group_by)
711 return (new instance.web.Model(field.relation)).query([options.tooltip_on_group_by])
712 .filter([["id", "=", this.value]]).first().then(function(res) {
713 self.tooltip = res[options.tooltip_on_group_by];
714 self.$(".oe_kanban_group_title_text").attr("title", self.tooltip || self.title || "").tooltip();
718 compute_cards_auto_height: function() {
719 // oe_kanban_no_auto_height is an empty class used to disable this feature
720 if (!this.view.group_by) {
723 _.each(this.records, function(r) {
724 var $e = r.$el.children(':first:not(.oe_kanban_no_auto_height)').css('min-height', 0);
727 min_height = Math.max(min_height, $e.outerHeight());
730 $(els).css('min-height', min_height);
733 destroy: function() {
736 this.$records.remove();
739 do_show_more: function(evt) {
741 var ids = self.view.dataset.ids.splice(0);
742 return this.dataset.read_slice(this.view.fields_keys.concat(['__last_update']), {
743 'limit': self.view.limit,
744 'offset': self.dataset_offset += self.view.limit
745 }).then(function(records) {
746 self.view.dataset.ids = ids.concat(self.dataset.ids);
747 self.do_add_records(records);
748 self.compute_cards_auto_height();
749 self.view.postprocess_m2m_tags();
753 do_add_records: function(records, prepend) {
755 var $list_header = this.$records.find('.oe_kanban_group_list_header');
756 var $show_more = this.$records.find('.oe_kanban_show_more');
757 var $cards = this.$records.find('.oe_kanban_column_cards');
759 _.each(records, function(record) {
760 var rec = new instance.web_kanban.KanbanRecord(self, record);
762 rec.appendTo($cards);
763 self.records.push(rec);
765 rec.prependTo($cards);
766 self.records.unshift(rec);
769 if ($show_more.length) {
770 var size = this.dataset.size();
771 $show_more.toggle(this.records.length < size).find('.oe_kanban_remaining').text(size - this.records.length);
774 remove_record: function(id, remove_from_dataset) {
775 for (var i = 0; i < this.records.length; i++) {
776 if (this.records[i]['id'] === id) {
777 this.records.splice(i, 1);
782 do_toggle_fold: function(compute_width) {
783 this.$el.add(this.$records).toggleClass('oe_kanban_group_folded');
784 this.state.folded = this.$el.is('.oe_kanban_group_folded');
785 this.$("ul.oe_kanban_group_dropdown li a[data-action=toggle_fold]").text((this.state.folded) ? _t("Unfold") : _t("Fold"));
787 do_action_toggle_fold: function() {
788 this.do_toggle_fold();
790 do_action_edit: function() {
794 name: _t("Edit column"),
795 res_model: self.view.group_by_field.relation,
796 views: [[false, 'form']],
797 type: 'ir.actions.act_window',
800 action_buttons: true,
803 var am = instance.webclient.action_manager;
804 var form = am.dialog_widget.views.form.controller;
805 form.on("on_button_cancel", am.dialog, function() { return am.dialog.$dialog_box.modal('hide'); });
806 form.on('record_saved', self, function() {
807 am.dialog.$dialog_box.modal('hide');
808 self.view.do_reload();
811 do_action_delete: function() {
813 if (confirm(_t("Are you sure to remove this column ?"))) {
814 (new instance.web.DataSet(self, self.view.group_by_field.relation)).unlink([self.value]).done(function(r) {
815 self.view.do_reload();
819 do_save_sequences: function() {
821 if (_.indexOf(this.view.fields_keys, 'sequence') > -1) {
822 var new_sequence = _.pluck(this.records, 'id');
823 self.view.dataset.resequence(new_sequence);
827 * Handles a newly created record
829 * @param {id} id of the newly created record
831 quick_created: function (record) {
832 var id = record, self = this;
833 self.view.remove_no_result();
834 self.trigger("add_record");
835 this.dataset.read_ids([id], this.view.fields_keys)
836 .done(function (records) {
837 self.view.dataset.ids.push(id);
838 self.do_add_records(records, true);
841 highlight: function(show){
843 this.$el.addClass('oe_kanban_column_higlight');
844 this.$records.addClass('oe_kanban_column_higlight');
846 this.$el.removeClass('oe_kanban_column_higlight');
847 this.$records.removeClass('oe_kanban_column_higlight');
852 instance.web_kanban.KanbanRecord = instance.web.Widget.extend({
853 template: 'KanbanView.record',
854 init: function (parent, record) {
857 this.view = parent.view;
859 this.set_record(record);
860 if (!this.view.state.records[this.id]) {
861 this.view.state.records[this.id] = {
865 this.state = this.view.state.records[this.id];
868 set_record: function(record) {
872 _.each(record, function(v, k) {
877 this.record = this.transform_record(record);
884 init_content: function() {
886 self.sub_widgets = [];
887 this.$("[data-field_id]").each(function() {
888 self.add_widget($(this));
890 this.$el.data('widget', this);
893 transform_record: function(record) {
896 _.each(record, function(value, name) {
897 var r = _.clone(self.view.fields_view.fields[name] || {});
898 if ((r.type === 'date' || r.type === 'datetime') && value) {
899 r.raw_value = instance.web.auto_str_to_date(value);
903 r.value = instance.web.format_value(value, r);
904 new_record[name] = r;
908 renderElement: function() {
909 this.qweb_context = {
913 read_only_mode: this.view.options.read_only_mode,
915 for (var p in this) {
916 if (_.str.startsWith(p, 'kanban_')) {
917 this.qweb_context[p] = _.bind(this[p], this);
920 var $el = instance.web.qweb.render(this.template, {
922 'content': this.view.qweb.render('kanban-box', this.qweb_context)
924 this.replaceElement($el);
925 this.replace_fields();
927 replace_fields: function() {
929 this.$("field").each(function() {
930 var $field = $(this);
931 var $nfield = $("<span></span");
932 var id = _.uniqueId("kanbanfield");
933 self.fields[id] = $field;
934 $nfield.attr("data-field_id", id);
935 $field.replaceWith($nfield);
938 add_widget: function($node) {
939 var $orig = this.fields[$node.data("field_id")];
940 var field = this.record[$orig.attr("name")];
941 var type = field.type;
942 type = $orig.attr("widget") ? $orig.attr("widget") : type;
943 var obj = instance.web_kanban.fields_registry.get_object(type);
944 var widget = new obj(this, field, $orig);
945 this.sub_widgets.push(widget);
946 widget.replace($node);
948 bind_events: function() {
950 this.setup_color_picker();
951 this.$el.find('[title]').each(function(){
953 delay: { show: 500, hide: 0},
955 var template = $(this).attr('tooltip');
956 if (!self.view.qweb.has_template(template)) {
959 return self.view.qweb.render(template, self.qweb_context);
964 // If no draghandle is found, make the whole card as draghandle (provided one can edit)
965 if (!this.$el.find('.oe_kanban_draghandle').length) {
966 this.$el.children(':first')
967 .toggleClass('oe_kanban_draghandle', this.view.is_action_enabled('edit'));
970 this.$el.find('.oe_kanban_action').click(function(ev) {
972 var $action = $(this),
973 type = $action.data('type') || 'button',
974 method = 'do_action_' + (type === 'action' ? 'object' : type);
975 if ((type === 'edit' || type === 'delete') && ! self.view.is_action_enabled(type)) {
976 self.view.open_record(self.id, true);
977 } else if (_.str.startsWith(type, 'switch_')) {
978 self.view.do_switch_view(type.substr(7));
979 } else if (typeof self[method] === 'function') {
980 self[method]($action);
982 self.do_warn("Kanban: no action for type : " + type);
986 if (this.$el.find('.oe_kanban_global_click,.oe_kanban_global_click_edit').length) {
987 this.$el.on('click', function(ev) {
988 if (!ev.isTrigger && !$._data(ev.target, 'events')) {
990 var elem = ev.target;
994 var events = $._data(elem, 'events');
995 if (elem == ev.currentTarget) {
1000 if (events && events.click) {
1001 // do not trigger global click if one child has a click event registered
1005 if (trigger && events && events.click) {
1006 _.each(events.click, function(click_event) {
1007 if (click_event.selector) {
1008 // For each parent of original target, check if a
1009 // delegated click is bound to any previously found children
1010 _.each(children, function(child) {
1011 if ($(child).is(click_event.selector)) {
1018 elem = elem.parentElement;
1021 self.on_card_clicked(ev);
1027 /* actions when user click on the block with a specific class
1028 * open on normal view : oe_kanban_global_click
1029 * open on form/edit view : oe_kanban_global_click_edit
1031 on_card_clicked: function(ev) {
1032 if (this.$el.find('.oe_kanban_global_click').size() > 0 && this.$el.find('.oe_kanban_global_click').data('routing')) {
1033 instance.web.redirect(this.$el.find('.oe_kanban_global_click').data('routing') + "/" + this.id);
1035 else if (this.$el.find('.oe_kanban_global_click_edit').size()>0)
1036 this.do_action_edit();
1038 this.do_action_open();
1040 setup_color_picker: function() {
1042 var $el = this.$el.find('ul.oe_kanban_colorpicker');
1044 $el.html(QWeb.render('KanbanColorPicker', {
1047 $el.on('click', 'a', function(ev) {
1048 ev.preventDefault();
1049 var color_field = $(this).parents('.oe_kanban_colorpicker').first().data('field') || 'color';
1051 data[color_field] = $(this).data('color');
1052 self.view.dataset.write(self.id, data, {}).done(function() {
1053 self.record[color_field] = $(this).data('color');
1059 do_action_delete: function($action) {
1062 return $.when(self.view.dataset.unlink([self.id])).done(function() {
1063 self.group.remove_record(self.id);
1067 if (this.view.options.confirm_on_delete) {
1068 if (confirm(_t("Are you sure you want to delete this record ?"))) {
1074 do_action_edit: function($action) {
1075 this.view.open_record(this.id, true);
1077 do_action_open: function($action) {
1078 this.view.open_record(this.id);
1080 do_action_object: function ($action) {
1081 var button_attrs = $action.data();
1082 this.view.do_execute_action(button_attrs, this.view.dataset, this.id, this.do_reload);
1084 do_action_url: function($action) {
1085 return instance.web.redirect($action.attr("href"));
1087 do_reload: function() {
1089 this.view.dataset.read_ids([this.id], this.view.fields_keys.concat(['__last_update'])).done(function(records) {
1090 _.each(self.sub_widgets, function(el) {
1093 self.sub_widgets = [];
1094 if (records.length) {
1095 self.set_record(records[0]);
1096 self.renderElement();
1097 self.init_content();
1098 self.group.compute_cards_auto_height();
1099 self.view.postprocess_m2m_tags();
1105 kanban_getcolor: function(variable) {
1107 switch (typeof(variable)) {
1109 for (var i=0, ii=variable.length; i<ii; i++) {
1110 index += variable.charCodeAt(i);
1114 index = Math.round(variable);
1119 var color = (index % this.view.number_of_color_schemes);
1122 kanban_color: function(variable) {
1123 var color = this.kanban_getcolor(variable);
1124 return color === '' ? '' : 'oe_kanban_color_' + color;
1126 kanban_image: function(model, field, id, cache, options) {
1127 options = options || {};
1129 if (this.record[field] && this.record[field].value && !instance.web.form.is_bin_size(this.record[field].value)) {
1130 url = 'data:image/png;base64,' + this.record[field].value;
1131 } else if (this.record[field] && ! this.record[field].value) {
1132 url = "/web/static/src/img/placeholder.png";
1134 id = JSON.stringify(id);
1135 if (options.preview_image)
1136 field = options.preview_image;
1137 url = this.session.url('/web/binary/image', {model: model, field: field, id: id});
1138 if (cache !== undefined) {
1139 // Set the cache duration in seconds.
1140 url += '&cache=' + parseInt(cache, 10);
1145 kanban_text_ellipsis: function(s, size) {
1149 } else if (s.length <= size) {
1152 return s.substr(0, size) + '...';
1155 kanban_compute_domain: function(domain) {
1156 return instance.web.form.compute_domain(domain, this.values);
1161 * Quick creation view.
1163 * Triggers a single event "added" with a single parameter "name", which is the
1164 * name entered by the user
1169 instance.web_kanban.QuickCreate = instance.web.Widget.extend({
1170 template: 'KanbanView.quick_create',
1173 * close_btn: If true, the widget will display a "Close" button able to trigger
1176 init: function(parent, dataset, context, buttons) {
1177 this._super(parent);
1178 this._dataset = dataset;
1179 this._buttons = buttons || false;
1180 this._context = context || {};
1182 start: function () {
1184 self.$input = this.$el.find('input');
1185 self.$input.keyup(function(event){
1186 if(event.keyCode == 13){
1190 $(".oe_kanban_quick_create").focusout(function (e) {
1191 var val = self.$el.find('input').val();
1192 if (/^\s*$/.test(val)) { self.trigger('close'); }
1193 e.stopImmediatePropagation();
1195 $(".oe_kanban_quick_create_add", this.$el).click(function () {
1199 $(".oe_kanban_quick_create_close", this.$el).click(function (ev) {
1200 ev.preventDefault();
1201 self.trigger('close');
1203 self.$input.keyup(function(e) {
1204 if (e.keyCode == 27 && self._buttons) {
1205 self.trigger('close');
1210 this.$el.find('input').focus();
1213 * Handles user event from nested quick creation view
1215 quick_add: function () {
1217 var val = this.$input.val();
1218 if (/^\s*$/.test(val)) { this.$el.remove(); return; }
1220 'name_create', [val, new instance.web.CompoundContext(
1221 this._dataset.get_context(), this._context)])
1222 .then(function(record) {
1223 self.$input.val("");
1224 self.trigger('added', record[0]);
1225 }, function(error, event) {
1226 event.preventDefault();
1227 return self.slow_create();
1230 slow_create: function() {
1232 var pop = new instance.web.form.SelectCreatePopup(this);
1234 self._dataset.model,
1236 title: _t("Create: ") + (this.string || this.name),
1237 initial_view: "form",
1238 disable_multiple_selection: true
1241 {"default_name": self.$input.val()}
1243 pop.on("elements_selected", self, function(element_ids) {
1244 self.$input.val("");
1245 self.trigger('added', element_ids[0]);
1251 * Interface to be implemented by kanban fields.
1254 instance.web_kanban.FieldInterface = {
1257 - parent: The widget's parent.
1258 - field: A dictionary giving details about the field, including the current field's value in the
1260 - $node: The field <field> tag as it appears in the view, encapsulated in a jQuery object.
1262 init: function(parent, field, $node) {},
1266 * Abstract class for classes implementing FieldInterface.
1269 * - value: useful property to hold the value of the field. By default, the constructor
1270 * sets value property.
1273 instance.web_kanban.AbstractField = instance.web.Widget.extend(instance.web_kanban.FieldInterface, {
1275 Constructor that saves the field and $node parameters and sets the "value" property.
1277 init: function(parent, field, $node) {
1278 this._super(parent);
1281 this.options = instance.web.py_eval(this.$node.attr("options") || '{}');
1282 this.set("value", field.raw_value);
1286 instance.web_kanban.Priority = instance.web_kanban.AbstractField.extend({
1287 init: function(parent, field, $node) {
1288 this._super.apply(this, arguments);
1289 this.name = $node.attr('name')
1290 this.parent = parent;
1292 prepare_priority: function() {
1294 var selection = this.field.selection || [];
1295 var init_value = selection && selection[0][0] || 0;
1296 var data = _.map(selection.slice(1), function(element, index) {
1298 'value': element[0],
1300 'click_value': element[0],
1302 if (index == 0 && self.get('value') == element[0]) {
1303 value['click_value'] = init_value;
1309 renderElement: function() {
1311 this.record_id = self.parent.id;
1312 this.priorities = self.prepare_priority();
1313 this.$el = $(QWeb.render("Priority", {'widget': this}));
1314 this.$el.find('li').click(self.do_action.bind(self));
1316 do_action: function(e) {
1318 var li = $(e.target).closest( "li" );
1321 value[self.name] = String(li.data('value'));
1322 return self.parent.view.dataset._model.call('write', [[self.record_id], value, self.parent.view.dataset.get_context()]).done(self.reload_record.bind(self.parent));
1325 reload_record: function() {
1330 instance.web_kanban.KanbanSelection = instance.web_kanban.AbstractField.extend({
1331 init: function(parent, field, $node) {
1332 this._super.apply(this, arguments);
1333 this.name = $node.attr('name')
1334 this.parent = parent;
1336 prepare_dropdown_selection: function() {
1338 _.map(this.field.selection || [], function(res) {
1342 'state_name': res[1],
1344 if (res[0] == 'normal') { value['state_class'] = 'oe_kanban_status'; }
1345 else if (res[0] == 'done') { value['state_class'] = 'oe_kanban_status oe_kanban_status_green'; }
1346 else { value['state_class'] = 'oe_kanban_status oe_kanban_status_red'; }
1351 renderElement: function() {
1353 this.record_id = self.parent.id;
1354 this.states = self.prepare_dropdown_selection();;
1355 this.$el = $(QWeb.render("KanbanSelection", {'widget': self}));
1356 this.$el.find('li').click(self.do_action.bind(self));
1358 do_action: function(e) {
1360 var li = $(e.target).closest( "li" );
1363 value[self.name] = String(li.data('value'));
1364 return self.parent.view.dataset._model.call('write', [[self.record_id], value, self.parent.view.dataset.get_context()]).done(self.reload_record.bind(self.parent));
1367 reload_record: function() {
1372 instance.web_kanban.fields_registry = new instance.web.Registry({});
1373 instance.web_kanban.fields_registry.add('priority','instance.web_kanban.Priority');
1374 instance.web_kanban.fields_registry.add('kanban_state_selection','instance.web_kanban.KanbanSelection');
1377 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: