1 /*---------------------------------------------------------
3 *---------------------------------------------------------*/
5 _.str.toBoolElse = function (str, elseValues, trueValues, falseValues) {
6 var ret = _.str.toBool(str, trueValues, falseValues);
7 if (_.isUndefined(ret)) {
13 openerp.web_calendar = function(instance) {
15 var _t = instance.web._t,
16 _lt = instance.web._lt,
17 QWeb = instance.web.qweb;
19 function get_class(name) {
20 return new instance.web.Registry({'tmp' : name}).get_object("tmp");
23 function get_fc_defaultOptions() {
24 shortTimeformat = Date.CultureInfo.formatPatterns.shortTime;
26 weekNumberTitle: _t("W"),
27 allDayText: _t("All day"),
34 monthNames: Date.CultureInfo.monthNames,
35 monthNamesShort: Date.CultureInfo.abbreviatedMonthNames,
36 dayNames: Date.CultureInfo.dayNames,
37 dayNamesShort: Date.CultureInfo.abbreviatedDayNames,
38 firstDay: Date.CultureInfo.firstDayOfWeek,
40 axisFormat : shortTimeformat.replace(/:mm/,'(:mm)'),
42 // for agendaWeek and agendaDay
43 agenda: shortTimeformat + '{ - ' + shortTimeformat + '}', // 5:00 - 6:30
44 // for all other views
45 '': shortTimeformat.replace(/:mm/,'(:mm)') // 7pm
53 function is_virtual_id(id) {
54 return typeof id === "string" && id.indexOf('-') >= 0;
57 function isNullOrUndef(value) {
58 return _.isUndefined(value) || _.isNull(value);
61 instance.web.views.add('calendar', 'instance.web_calendar.CalendarView');
63 instance.web_calendar.CalendarView = instance.web.View.extend({
64 template: "CalendarView",
65 display_name: _lt('Calendar'),
66 quick_create_instance: 'instance.web_calendar.QuickCreate',
68 init: function (parent, dataset, view_id, options) {
70 this.ready = $.Deferred();
71 this.set_default_options(options);
72 this.dataset = dataset;
73 this.model = dataset.model;
74 this.fields_view = {};
75 this.view_id = view_id;
76 this.view_type = 'calendar';
78 this.range_start = null;
79 this.range_stop = null;
80 this.selected_filters = [];
83 set_default_options: function(options) {
85 _.defaults(this.options, {
86 confirm_on_delete: true
91 this.$calendar.fullCalendar('destroy');
92 if (this.$small_calendar) {
93 this.$small_calendar.datepicker('destroy');
95 this._super.apply(this, arguments);
98 view_loading: function (fv) {
99 /* xml view calendar options */
100 var attrs = fv.arch.attrs,
102 this.fields_view = fv;
103 this.$calendar = this.$el.find(".oe_calendar_widget");
105 this.info_fields = [];
108 this.$buttons = $(QWeb.render("CalendarView.buttons", {'widget': this}));
109 if (this.options.$buttons) {
110 this.$buttons.appendTo(this.options.$buttons);
112 this.$el.find('.oe_calendar_buttons').replaceWith(this.$buttons);
115 this.$buttons.on('click', 'button.oe_calendar_button_new', function () {
116 self.dataset.index = null;
117 self.do_switch_view('form');
120 if (!attrs.date_start) {
121 throw new Error(_t("Calendar view has not defined 'date_start' attribute."));
124 this.$el.addClass(attrs['class']);
126 this.name = fv.name || attrs.string;
127 this.view_id = fv.view_id;
129 this.mode = attrs.mode; // one of month, week or day
130 this.date_start = attrs.date_start; // Field name of starting date field
131 this.date_delay = attrs.date_delay; // duration
132 this.date_stop = attrs.date_stop;
133 this.all_day = attrs.all_day;
134 this.how_display_event = '';
135 this.attendee_people = attrs.attendee;
137 if (!isNullOrUndef(attrs.quick_create_instance)) {
138 self.quick_create_instance = 'instance.' + attrs.quick_create_instance;
141 //if quick_add = False, we don't allow quick_add
142 //if quick_add = not specified in view, we use the default quick_create_instance
143 //if quick_add = is NOT False and IS specified in view, we this one for quick_create_instance'
145 this.quick_add_pop = (isNullOrUndef(attrs.quick_add) || _.str.toBoolElse(attrs.quick_add, true));
146 if (this.quick_add_pop && !isNullOrUndef(attrs.quick_add)) {
147 self.quick_create_instance = 'instance.' + attrs.quick_add;
149 // The display format which will be used to display the event where fields are between "[" and "]"
150 if (!isNullOrUndef(attrs.display)) {
151 this.how_display_event = attrs.display; // String with [FIELD]
154 // If this field is set ot true, we don't open the event in form view, but in a popup with the view_id passed by this parameter
155 if (isNullOrUndef(attrs.event_open_popup) || !_.str.toBoolElse(attrs.event_open_popup, true)) {
156 this.open_popup_action = false;
158 this.open_popup_action = attrs.event_open_popup;
160 // If this field is set to true, we will use the calendar_friends model as filter and not the color field.
161 this.useContacts = (!isNullOrUndef(attrs.use_contacts) && _.str.toBool(attrs.use_contacts)) && (!isNullOrUndef(self.options.$sidebar));
163 // If this field is set ot true, we don't add itself as an attendee when we use attendee_people to add each attendee icon on an event
164 // The color is the color of the attendee, so don't need to show again that it will be present
165 this.colorIsAttendee = (!(isNullOrUndef(attrs.color_is_attendee) || !_.str.toBoolElse(attrs.color_is_attendee, true))) && (!isNullOrUndef(self.options.$sidebar));
167 // if we have not sidebar, (eg: Dashboard), we don't use the filter "coworkers"
168 if (isNullOrUndef(self.options.$sidebar)) {
169 this.useContacts = false;
170 this.colorIsAttendee = false;
171 this.attendee_people = undefined;
175 Will be more logic to do it in futur, but see below to stay Retro-compatible
177 if (isNull(attrs.avatar_model)) {
178 this.avatar_model = 'res.partner';
181 if (attrs.avatar_model == 'False') {
182 this.avatar_model = null;
185 this.avatar_model = attrs.avatar_model;
189 if (isNullOrUndef(attrs.avatar_model)) {
190 this.avatar_model = null;
192 this.avatar_model = attrs.avatar_model;
195 if (isNullOrUndef(attrs.avatar_title)) {
196 this.avatar_title = this.avatar_model;
198 this.avatar_title = attrs.avatar_title;
200 this.color_field = attrs.color;
202 if (this.color_field && this.selected_filters.length === 0) {
204 if ((default_filter = this.dataset.context['calendar_default_' + this.color_field])) {
205 this.selected_filters.push(default_filter + '');
209 this.fields = fv.fields;
211 for (var fld = 0; fld < fv.arch.children.length; fld++) {
212 this.info_fields.push(fv.arch.children[fld].attrs.name);
215 var edit_check = new instance.web.Model(this.dataset.model)
216 .call("check_access_rights", ["write", false])
217 .then(function (write_right) {
218 self.write_right = write_right;
220 var init = new instance.web.Model(this.dataset.model)
221 .call("check_access_rights", ["create", false])
222 .then(function (create_right) {
223 self.create_right = create_right;
224 self.init_calendar().then(function() {
225 $(window).trigger('resize');
226 self.trigger('calendar_view_loaded', fv);
227 self.ready.resolve();
230 return $.when(edit_check, init);
233 get_fc_init_options: function () {
234 //Documentation here : http://arshaw.com/fullcalendar/docs/
236 return $.extend({}, get_fc_defaultOptions(), {
238 defaultView: (this.mode == "month")?"month":
239 (this.mode == "week"?"agendaWeek":
240 (this.mode == "day"?"agendaDay":"month")),
242 left: 'prev,next today',
244 right: 'month,agendaWeek,agendaDay'
246 selectable: !this.options.read_only_mode && this.create_right,
248 editable: !this.options.read_only_mode,
253 eventDrop: function (event, _day_delta, _minute_delta, _all_day, _revertFunc) {
254 var data = self.get_event_data(event);
255 self.proxy('update_record')(event._id, data); // we don't revert the event, but update it.
257 eventResize: function (event, _day_delta, _minute_delta, _revertFunc) {
258 var data = self.get_event_data(event);
259 self.proxy('update_record')(event._id, data);
261 eventRender: function (event, element, view) {
262 element.find('.fc-event-title').html(event.title);
264 eventAfterRender: function (event, element, view) {
265 if ((view.name !== 'month') && (((event.end-event.start)/60000)<=30)) {
266 //if duration is too small, we see the html code of img
267 var current_title = $(element.find('.fc-event-time')).text();
268 var new_title = current_title.substr(0,current_title.indexOf("<img")>0?current_title.indexOf("<img"):current_title.length);
269 element.find('.fc-event-time').html(new_title);
272 eventClick: function (event) { self.open_event(event._id,event.title); },
273 select: function (start_date, end_date, all_day, _js_event, _view) {
274 var data_template = self.get_event_data({
279 self.open_quick_create(data_template);
289 calendarMiniChanged: function (context) {
290 return function(datum,obj) {
291 var curView = context.$calendar.fullCalendar( 'getView');
292 var curDate = new Date(obj.currentYear , obj.currentMonth, obj.currentDay);
294 if (curView.name == "agendaWeek") {
295 if (curDate <= curView.end && curDate >= curView.start) {
296 context.$calendar.fullCalendar('changeView','agendaDay');
299 else if (curView.name != "agendaDay" || (curView.name == "agendaDay" && curDate.compareTo(curView.start)===0)) {
300 context.$calendar.fullCalendar('changeView','agendaWeek');
302 context.$calendar.fullCalendar('gotoDate', obj.currentYear , obj.currentMonth, obj.currentDay);
306 init_calendar: function() {
309 if (!this.sidebar && this.options.$sidebar) {
310 translate = get_fc_defaultOptions();
311 this.sidebar = new instance.web_calendar.Sidebar(this);
312 this.sidebar.appendTo(this.$el.find('.oe_calendar_sidebar_container'));
314 this.$small_calendar = self.$el.find(".oe_calendar_mini");
315 this.$small_calendar.datepicker({
316 onSelect: self.calendarMiniChanged(self),
317 dayNamesMin : translate.dayNamesShort,
318 monthNames: translate.monthNamesShort,
319 firstDay: translate.firstDay,
323 if (this.useContacts) {
326 new instance.web.Model("res.users").query(["partner_id"]).filter([["id", "=",this.dataset.context.uid]]).first()
329 var sidebar_items = {};
330 var filter_value = result.partner_id[0];
333 label: result.partner_id[1] + _lt(" [Me]"),
334 color: self.get_color(filter_value),
335 avatar_model: self.avatar_model,
339 sidebar_items[filter_value] = filter_item ;
342 label: _lt("Everybody's calendars"),
343 color: self.get_color(-1),
344 avatar_model: self.avatar_model,
347 sidebar_items[-1] = filter_item ;
348 //Get my coworkers/contacts
349 new instance.web.Model("calendar.contacts").query(["partner_id"]).filter([["user_id", "=",self.dataset.context.uid]]).all().then(function(result) {
350 _.each(result, function(item) {
351 filter_value = item.partner_id[0];
354 label: item.partner_id[1],
355 color: self.get_color(filter_value),
356 avatar_model: self.avatar_model,
359 sidebar_items[filter_value] = filter_item ;
362 self.all_filters = sidebar_items;
363 self.now_filter_ids = $.map(self.all_filters, function(o) { return o.value; });
365 self.sidebar.filter.events_loaded(self.all_filters);
366 self.sidebar.filter.set_filters();
368 self.sidebar.filter.addUpdateButton();
369 }).done(function () {
370 self.$calendar.fullCalendar('refetchEvents');
377 self.$calendar.fullCalendar(self.get_fc_init_options());
381 extraSideBar: function() {
384 open_quick_create: function(data_template) {
385 if (!isNullOrUndef(this.quick)) {
386 return this.quick.trigger('close');
388 var QuickCreate = get_class(this.quick_create_instance);
390 this.options.disable_quick_create = this.options.disable_quick_create || !this.quick_add_pop;
392 this.quick = new QuickCreate(this, this.dataset, true, this.options, data_template);
393 this.quick.on('added', this, this.quick_created)
394 .on('slowadded', this, this.slow_created)
395 .on('close', this, function() {
396 this.quick.destroy();
398 this.$calendar.fullCalendar('unselect');
400 this.quick.replace(this.$el.find('.oe_calendar_qc_placeholder'));
406 * Refresh one fullcalendar event identified by it's 'id' by reading OpenERP record state.
407 * If event was not existent in fullcalendar, it'll be created.
409 refresh_event: function(id) {
411 if (is_virtual_id(id)) {
412 // Should avoid "refreshing" a virtual ID because it can't
413 // really be modified so it should never be refreshed. As upon
414 // edition, a NEW event with a non-virtual id will be created.
415 console.warn("Unwise use of refresh_event on a virtual ID.");
417 this.dataset.read_ids([id], _.keys(this.fields)).done(function (incomplete_records) {
418 self.perform_necessary_name_gets(incomplete_records).then(function(records) {
419 // Event boundaries were already changed by fullcalendar, but we need to reload them:
420 var new_event = self.event_data_transform(records[0]);
422 var event_objs = self.$calendar.fullCalendar('clientEvents', id);
423 if (event_objs.length == 1) { // Already existing obj to update
424 var event_obj = event_objs[0];
426 _(new_event).each(function (value, key) {
427 event_obj[key] = value;
429 self.$calendar.fullCalendar('updateEvent', event_obj);
430 } else { // New event object to create
431 self.$calendar.fullCalendar('renderEvent', new_event);
432 // By forcing attribution of this event to this source, we
433 // make sure that the event will be removed when the source
434 // will be removed (which occurs at each do_search)
435 self.$calendar.fullCalendar('clientEvents', id)[0].source = self.event_source;
441 get_color: function(key) {
442 if (this.color_map[key]) {
443 return this.color_map[key];
445 var index = (((_.keys(this.color_map).length + 1) * 5) % 24) + 1;
446 this.color_map[key] = index;
452 * In o2m case, records from dataset won't have names attached to their *2o values.
453 * We should make sure this is the case.
455 perform_necessary_name_gets: function(evts) {
456 var def = $.Deferred();
459 _(this.info_fields).each(function (fieldname) {
460 if (!_(["many2one", "one2one"]).contains(
461 self.fields[fieldname].type))
463 to_get[fieldname] = [];
464 _(evts).each(function (evt) {
465 var value = evt[fieldname];
466 if (value === false || (value instanceof Array)) {
469 to_get[fieldname].push(value);
471 if (to_get[fieldname].length === 0) {
472 delete to_get[fieldname];
475 var defs = _(to_get).map(function (ids, fieldname) {
476 return (new instance.web.Model(self.fields[fieldname].relation))
477 .call('name_get', ids).then(function (vals) {
478 return [fieldname, vals];
482 $.when.apply(this, defs).then(function() {
483 var values = arguments;
484 _(values).each(function(value) {
485 var fieldname = value[0];
486 var name_gets = value[1];
487 _(name_gets).each(function(name_get) {
489 .filter(function (e) {return e[fieldname] == name_get[0];})
490 .each(function(evt) {
491 evt[fieldname] = name_get;
501 * Transform OpenERP event object to fullcalendar event object
503 event_data_transform: function(evt) {
506 var date_delay = evt[this.date_delay] || 1.0,
507 all_day = this.all_day ? evt[this.all_day] : false,
508 res_computed_text = '',
513 date_start = instance.web.auto_str_to_date(evt[this.date_start]);
514 date_stop = this.date_stop ? instance.web.auto_str_to_date(evt[this.date_stop]) : null;
517 date_start = instance.web.auto_str_to_date(evt[this.date_start].split(' ')[0],'date');
518 date_stop = this.date_stop ? instance.web.auto_str_to_date(evt[this.date_stop].split(' ')[0],'date').addMinutes(-1) : null;
521 if (this.info_fields) {
523 res_computed_text = this.how_display_event;
525 _.each(this.info_fields, function (fieldname) {
526 var value = evt[fieldname];
527 if (_.contains(["many2one", "one2one"], self.fields[fieldname].type)) {
528 if (value === false) {
529 temp_ret[fieldname] = null;
531 else if (value instanceof Array) {
532 temp_ret[fieldname] = value[1]; // no name_get to make
535 throw new Error("Incomplete data received from dataset for record " + evt.id);
538 else if (_.contains(["one2many","many2many"], self.fields[fieldname].type)) {
539 if (value === false) {
540 temp_ret[fieldname] = null;
542 else if (value instanceof Array) {
543 temp_ret[fieldname] = value; // if x2many, keep all id !
546 throw new Error("Incomplete data received from dataset for record " + evt.id);
550 temp_ret[fieldname] = value;
552 res_computed_text = res_computed_text.replace("["+fieldname+"]",temp_ret[fieldname]);
556 if (res_computed_text.length) {
557 the_title = res_computed_text;
561 _.each(temp_ret, function(val,key) { res_text.push(val); });
562 the_title = res_text.join(', ');
564 the_title = _.escape(the_title);
567 the_title_avatar = '';
569 if (! _.isUndefined(this.attendee_people)) {
570 var MAX_ATTENDEES = 3;
571 var attendee_showed = 0;
572 var attendee_other = '';
574 _.each(temp_ret[this.attendee_people],
575 function (the_attendee_people) {
576 attendees.push(the_attendee_people);
577 attendee_showed += 1;
578 if (attendee_showed<= MAX_ATTENDEES) {
579 if (self.avatar_model !== null) {
580 the_title_avatar += '<img title="' + self.all_attendees[the_attendee_people] + '" class="attendee_head" \
581 src="/web/binary/image?model=' + self.avatar_model + '&field=image_small&id=' + the_attendee_people + '"></img>';
584 if (!self.colorIsAttendee || the_attendee_people != temp_ret[self.color_field]) {
585 tempColor = (self.all_filters[the_attendee_people] !== undefined)
586 ? self.all_filters[the_attendee_people].color
587 : self.all_filters[-1].color;
588 the_title_avatar += '<i class="fa fa-user attendee_head color_'+tempColor+'" title="' + self.all_attendees[the_attendee_people] + '" ></i>';
589 }//else don't add myself
593 attendee_other += self.all_attendees[the_attendee_people] +", ";
597 if (attendee_other.length>2) {
598 the_title_avatar += '<span class="attendee_head" title="' + attendee_other.slice(0, -2) + '">+</span>';
600 the_title = the_title_avatar + the_title;
604 if (!date_stop && date_delay) {
605 date_stop = date_start.clone().addHours(date_delay);
608 'start': date_start.toString('yyyy-MM-dd HH:mm:ss'),
609 'end': date_stop.toString('yyyy-MM-dd HH:mm:ss'),
611 'allDay': (this.fields[this.date_start].type == 'date' || (this.all_day && evt[this.all_day]) || false),
613 'attendees':attendees
615 if (!self.useContacts || self.all_filters[evt[this.color_field]] !== undefined) {
616 if (this.color_field && evt[this.color_field]) {
617 var color_key = evt[this.color_field];
618 if (typeof color_key === "object") {
619 color_key = color_key[0];
621 r.className = 'cal_opacity calendar_color_'+ this.get_color(color_key);
624 else { // if form all, get color -1
625 r.className = 'cal_opacity calendar_color_'+ self.all_filters[-1].color;
631 * Transform fullcalendar event object to OpenERP Data object
633 get_event_data: function(event) {
635 // Normalize event_end without changing fullcalendars event.
640 var event_end = event.end;
641 //Bug when we move an all_day event from week or day view, we don't have a dateend or duration...
642 if (event_end == null) {
643 event_end = new Date(event.start).addHours(2);
647 // Sometimes fullcalendar doesn't give any event.end.
648 if (event_end == null || _.isUndefined(event_end)) {
649 event_end = new Date(event.start);
652 event_end = (new Date(event_end.getTime())).addDays(1);
653 date_start_day = new Date(event.start.getFullYear(),event.start.getMonth(),event.start.getDate(),12);
654 date_stop_day = new Date(event_end.getFullYear(),event_end.getMonth(),event_end.getDate(),12);
657 date_start_day = new Date(event.start.getFullYear(),event.start.getMonth(),event.start.getDate(),7);
658 date_stop_day = new Date(event_end.getFullYear(),event_end.getMonth(),event_end.getDate(),19);
660 diff_seconds = Math.round((date_stop_day.getTime() - date_start_day.getTime()) / 1000);
664 data[this.date_start] = event.start;
665 if (this.date_stop) {
666 data[this.date_stop] = event_end;
668 diff_seconds = Math.round((event_end.getTime() - event.start.getTime()) / 1000);
672 data[this.all_day] = event.allDay;
675 if (this.date_delay) {
677 data[this.date_delay] = diff_seconds / 3600;
682 do_search: function(domain, context, _group_by) {
684 if (! self.all_filters) {
685 self.all_filters = {}
688 if (! _.isUndefined(this.event_source)) {
689 this.$calendar.fullCalendar('removeEventSource', this.event_source);
691 this.event_source = {
692 events: function(start, end, callback) {
693 var current_event_source = self.event_source;
694 self.dataset.read_slice(_.keys(self.fields), {
696 domain: self.get_range_domain(domain, start, end),
698 }).done(function(events) {
700 if (self.event_source !== current_event_source) {
701 console.log("Consecutive ``do_search`` called. Cancelling.");
705 if (!self.useContacts) { // If we use all peoples displayed in the current month as filter in sidebars
710 self.now_filter_ids = [];
712 _.each(events, function (e) {
713 filter_value = e[self.color_field][0];
714 if (!self.all_filters[e[self.color_field][0]]) {
717 label: e[self.color_field][1],
718 color: self.get_color(filter_value),
719 avatar_model: self.avatar_model,
722 self.all_filters[e[self.color_field][0]] = filter_item;
724 if (! _.contains(self.now_filter_ids, filter_value)) {
725 self.now_filter_ids.push(filter_value);
730 self.sidebar.filter.events_loaded();
731 self.sidebar.filter.set_filters();
733 events = $.map(events, function (e) {
734 if (_.contains(self.now_filter_ids,e[self.color_field][0]) && self.all_filters[e[self.color_field][0]].is_checked) {
740 return self.perform_necessary_name_gets(events).then(callback);
742 else { //WE USE CONTACT
743 if (self.attendee_people !== undefined) {
744 //if we don't filter on 'Everybody's Calendar
745 if (!self.all_filters[-1] || !self.all_filters[-1].is_checked) {
746 var checked_filter = $.map(self.all_filters, function(o) { if (o.is_checked) { return o.value; }});
747 // If we filter on contacts... we keep only events from coworkers
748 events = $.map(events, function (e) {
749 if (_.intersection(checked_filter,e[self.attendee_people]).length) {
757 var all_attendees = $.map(events, function (e) { return e[self.attendee_people]; });
758 all_attendees = _.chain(all_attendees).flatten().uniq().value();
760 self.all_attendees = {};
761 if (self.avatar_title !== null) {
762 new instance.web.Model(self.avatar_title).query(["name"]).filter([["id", "in", all_attendees]]).all().then(function(result) {
763 _.each(result, function(item) {
764 self.all_attendees[item.id] = item.name;
767 return self.perform_necessary_name_gets(events).then(callback);
771 _.each(all_attendees,function(item){
772 self.all_attendees[item] = '';
774 return self.perform_necessary_name_gets(events).then(callback);
779 eventDataTransform: function (event) {
780 return self.event_data_transform(event);
783 this.$calendar.fullCalendar('addEventSource', this.event_source);
786 * Build OpenERP Domain to filter object by this.date_start field
787 * between given start, end dates.
789 get_range_domain: function(domain, start, end) {
790 var format = instance.web.date_to_str;
792 extend_domain = [[this.date_start, '>=', format(start.clone())],
793 [this.date_start, '<=', format(end.clone())]];
795 if (this.date_stop) {
797 extend_domain.splice(0,0,'|','|','&');
801 [this.date_start, '<=', format(start.clone())],
802 [this.date_stop, '>=', format(start.clone())],
804 [this.date_start, '<=', format(end.clone())],
805 [this.date_stop, '>=', format(start.clone())]
807 //final -> (A & B) | (C & D) | (E & F) -> | | & A B & C D & E F
809 return new instance.web.CompoundDomain(domain, extend_domain);
813 * Updates record identified by ``id`` with values in object ``data``
815 update_record: function(id, data) {
817 delete(data.name); // Cannot modify actual name yet
818 var index = this.dataset.get_id_index(id);
819 if (index !== null) {
820 event_id = this.dataset.ids[index];
821 this.dataset.write(event_id, data, {}).done(function() {
822 if (is_virtual_id(event_id)) {
823 // this is a virtual ID and so this will create a new event
824 // with an unknown id for us.
825 self.$calendar.fullCalendar('refetchEvents');
827 // classical event that we can refresh
828 self.refresh_event(event_id);
834 open_event: function(id, title) {
836 if (! this.open_popup_action) {
837 var index = this.dataset.get_id_index(id);
838 this.dataset.index = index;
839 if (this.write_right) {
840 this.do_switch_view('form', null, { mode: "edit" });
842 this.do_switch_view('form', null, { mode: "view" });
846 var pop = new instance.web.form.FormOpenPopup(this);
847 pop.show_element(this.dataset.model, id, this.dataset.get_context(), {
848 title: _.str.sprintf(_t("View: %s"),title),
849 view_id: +this.open_popup_action,
855 var form_controller = pop.view_form;
856 form_controller.on("load_record", self, function(){
857 button_delete = _.str.sprintf("<button class='oe_button oe_bold delme'><span> %s </span></button>",_t("Delete"));
858 button_edit = _.str.sprintf("<button class='oe_button oe_bold editme oe_highlight'><span> %s </span></button>",_t("Edit Event"));
861 pop.$el.closest(".ui-dialog").find(".ui-dialog-buttonpane").prepend(button_delete);
862 pop.$el.closest(".ui-dialog").find(".ui-dialog-buttonpane").prepend(button_edit);
866 $('.oe_form_button_cancel').trigger('click');
867 self.remove_event(id);
872 $('.oe_form_button_cancel').trigger('click');
873 self.dataset.index = self.dataset.get_id_index(id);
874 self.do_switch_view('form', null, { mode: "edit" });
882 do_show: function() {
884 this.$buttons.show();
886 this.do_push_state({});
887 return this._super();
889 do_hide: function () {
891 this.$buttons.hide();
893 return this._super();
895 is_action_enabled: function(action) {
896 if (action === 'create' && !this.options.creatable) {
899 return this._super(action);
903 * Handles a newly created record
905 * @param {id} id of the newly created record
907 quick_created: function (id) {
910 * it's of the most utter importance NOT to use inplace
911 * modification on this.dataset.ids as reference to this
912 * data is spread out everywhere in the various widget.
913 * Some of these reference includes values that should
914 * trigger action upon modification.
916 this.dataset.ids = this.dataset.ids.concat([id]);
917 this.dataset.trigger("dataset_changed", id);
918 this.refresh_event(id);
920 slow_created: function () {
921 // refresh all view, because maybe some recurrents item
924 // force filter refresh
925 self.sidebar.filter.is_loaded = false;
927 self.$calendar.fullCalendar('refetchEvents');
930 remove_event: function(id) {
933 return $.when(self.dataset.unlink([id])).then(function() {
934 self.$calendar.fullCalendar('removeEvents', id);
937 if (this.options.confirm_on_delete) {
938 if (confirm(_t("Are you sure you want to delete this record ?"))) {
948 * Quick creation view.
950 * Triggers a single event "added" with a single parameter "name", which is the
951 * name entered by the user
956 instance.web_calendar.QuickCreate = instance.web.Widget.extend({
957 template: 'CalendarView.quick_create',
959 init: function(parent, dataset, buttons, options, data_template) {
961 this.dataset = dataset;
962 this._buttons = buttons || false;
963 this.options = options;
965 // Can hold data pre-set from where you clicked on agenda
966 this.data_template = data_template || {};
968 get_title: function () {
969 var parent = this.getParent();
970 if (_.isUndefined(parent)) {
973 var title = (_.isUndefined(parent.field_widget)) ?
974 (parent.string || parent.name) :
975 parent.field_widget.string || parent.field_widget.name || '';
976 return _t("Create: ") + title;
981 if (this.options.disable_quick_create) {
987 self.$input = this.$el.find('input');
988 self.$input.keyup(function enterHandler (event) {
989 if(event.keyCode == 13){
990 self.$input.off('keyup', enterHandler);
991 if (!self.quick_add()){
992 self.$input.on('keyup', enterHandler);
997 var submit = this.$el.find(".oe_calendar_quick_create_add");
998 submit.click(function clickHandler() {
999 submit.off('click', clickHandler);
1000 if (!self.quick_add()){
1001 submit.on('click', clickHandler); }
1004 this.$el.find(".oe_calendar_quick_create_edit").click(function () {
1008 this.$el.find(".oe_calendar_quick_create_close").click(function (ev) {
1009 ev.preventDefault();
1010 self.trigger('close');
1012 self.$input.keyup(function enterHandler (e) {
1013 if (e.keyCode == 27 && self._buttons) {
1014 self.trigger('close');
1017 self.$el.dialog({ title: this.get_title()});
1018 self.on('added', self, function() {
1019 self.trigger('close');
1022 self.$el.on('dialogclose', self, function() {
1023 self.trigger('close');
1028 this.$el.find('input').focus();
1032 * Gathers data from the quick create dialog a launch quick_create(data) method
1034 quick_add: function() {
1035 var val = this.$input.val();
1036 if (/^\s*$/.test(val)) {
1039 return this.quick_create({'name': val}).always(function() { return true; });
1042 slow_add: function() {
1043 var val = this.$input.val();
1044 this.slow_create({'name': val});
1048 * Handles saving data coming from quick create box
1050 quick_create: function(data, options) {
1052 return this.dataset.create($.extend({}, this.data_template, data), options)
1053 .then(function(id) {
1054 self.trigger('added', id);
1055 self.$input.val("");
1056 }).fail(function(r, event) {
1057 event.preventDefault();
1058 // This will occurs if there are some more fields required
1059 self.slow_create(data);
1064 * Show full form popup
1066 get_form_popup_infos: function() {
1067 var parent = this.getParent();
1072 if (!_.isUndefined(parent) && !(_.isUndefined(parent.ViewManager))) {
1073 infos.view_id = parent.ViewManager.get_view_id('form');
1077 slow_create: function(data) {
1078 //if all day, we could reset time to display 00:00:00
1081 var def = $.Deferred();
1084 _.each($.extend({}, this.data_template, data), function(val, field_name) {
1085 defaults['default_' + field_name] = val;
1088 var pop_infos = self.get_form_popup_infos();
1089 var pop = new instance.web.form.FormOpenPopup(this);
1090 var context = new instance.web.CompoundContext(this.dataset.context, defaults);
1091 pop.show_element(this.dataset.model, null, this.dataset.get_context(defaults), {
1092 title: this.get_title(),
1093 disable_multiple_selection: true,
1094 view_id: pop_infos.view_id,
1095 // Ensuring we use ``self.dataset`` and DO NOT create a new one.
1096 create_function: function(data, options) {
1097 return self.dataset.create(data, options).done(function(r) {
1098 }).fail(function (r, event) {
1099 if (!r.data.message) { //else manage by openerp
1104 read_function: function(id, fields, options) {
1105 return self.dataset.read_ids.apply(self.dataset, arguments).done(function() {
1106 }).fail(function (r, event) {
1107 if (!r.data.message) { //else manage by openerp
1113 pop.on('closed', self, function() {
1114 // ``self.trigger('close')`` would itself destroy all child element including
1115 // the slow create popup, which would then re-trigger recursively the 'closed' signal.
1116 // Thus, here, we use a deferred and its state to cut the endless recurrence.
1117 if (def.state() === "pending") {
1121 pop.on('create_completed', self, function(id) {
1122 self.trigger('slowadded');
1124 def.then(function() {
1125 self.trigger('close');
1136 function widget_calendar_lazy_init() {
1137 if (instance.web.form.Many2ManyCalendarView) {
1141 instance.web_calendar.FieldCalendarView = instance.web_calendar.CalendarView.extend({
1143 init: function (parent) {
1144 this._super.apply(this, arguments);
1145 // Warning: this means only a field_widget should instanciate this Class
1146 this.field_widget = parent;
1149 view_loading: function (fv) {
1151 return $.when(this._super.apply(this, arguments)).then(function() {
1152 self.on('event_rendered', this, function (event, element, view) {
1158 // In forms, we could be hidden in a notebook. Thus we couldn't
1159 // render correctly fullcalendar so we try to detect when we are
1160 // not visible to wait for when we will be visible.
1161 init_calendar: function() {
1162 if (this.$calendar.width() !== 0) { // visible
1163 return this._super();
1165 // find all parents tabs.
1166 var def = $.Deferred();
1168 this.$calendar.parents(".ui-tabs").on('tabsactivate', this, function() {
1169 if (self.$calendar.width() !== 0) { // visible
1170 self.$calendar.fullCalendar(self.get_fc_init_options());
1179 instance.web_calendar.BufferedDataSet = instance.web.BufferedDataSet.extend({
1182 * Adds verification on possible missing fields for the sole purpose of
1183 * O2M dataset being compatible with the ``slow_create`` detection of
1184 * missing fields... which is as simple to try to write and upon failure
1185 * go to ``slow_create``. Current BufferedDataSet would'nt fail because
1186 * they do not send data to the server at create time.
1188 create: function (data, options) {
1189 var def = $.Deferred();
1191 var create = this._super;
1192 if (_.isUndefined(this.required_fields)) {
1193 this.required_fields = (new instance.web.Model(this.model))
1194 .call('fields_get').then(function (fields_def) {
1195 return _(fields_def).chain()
1196 // equiv to .pairs()
1197 .map(function (value, key) { return [key, value]; })
1198 // equiv to .omit(self.field_widget.field.relation_field)
1199 .filter(function (pair) { return pair[0] !== self.field_widget.field.relation_field; })
1200 .filter(function (pair) { return pair[1].required; })
1201 .map(function (pair) { return pair[0]; })
1205 $.when(this.required_fields).then(function (required_fields) {
1206 var missing_fields = _(required_fields).filter(function (v) {
1207 return _.isUndefined(data[v]);
1209 var default_get = (missing_fields.length !== 0) ?
1210 self.default_get(missing_fields) : [];
1211 $.when(default_get).then(function (defaults) {
1213 // Remove all fields that have a default from the missing fields.
1214 missing_fields = _(missing_fields).filter(function (f) {
1215 return _.isUndefined(defaults[f]);
1217 if (missing_fields.length !== 0) {
1220 _t("Missing required fields %s"), missing_fields.join(", ")),
1224 create.apply(self, [data, options]).then(function (result) {
1225 def.resolve(result);
1233 instance.web_calendar.fields_dataset = new instance.web.Registry({
1234 'many2many': 'instance.web.DataSetStatic',
1235 'one2many': 'instance.web_calendar.BufferedDataSet',
1239 function get_field_dataset_class(type) {
1240 var obj = instance.web_calendar.fields_dataset.get_any([type]);
1242 throw new Error(_.str.sprintf(_t("Dataset for type '%s' is not defined."), type));
1245 // Override definition of legacy datasets to add field_widget context
1247 init: function (parent) {
1248 this._super.apply(this, arguments);
1249 this.field_widget = parent;
1251 get_context: function() {
1252 this.context = this.field_widget.build_context();
1253 return this.context;
1259 * Common part to manage any field using calendar view
1261 instance.web_calendar.FieldCalendar = instance.web.form.AbstractField.extend({
1263 disable_utility_classes: true,
1264 calendar_view_class: 'instance.web_calendar.FieldCalendarView',
1266 init: function(field_manager, node) {
1267 this._super(field_manager, node);
1268 widget_calendar_lazy_init();
1269 this.is_loaded = $.Deferred();
1270 this.initial_is_loaded = this.is_loaded;
1274 // This dataset will use current widget to '.build_context()'.
1275 var field_type = field_manager.fields_view.fields[node.attrs.name].type;
1276 this.dataset = new (get_field_dataset_class(field_type))(
1277 this, this.field.relation);
1279 this.dataset.on('unlink', this, function(_ids) {
1280 this.dataset.trigger('dataset_changed');
1283 // quick_create widget instance will be attached when spawned
1284 this.quick_create = null;
1286 this.no_rerender = true;
1291 this._super.apply(this, arguments);
1296 self.on("change:effective_readonly", self, function() {
1297 self.is_loaded = self.is_loaded.then(function() {
1298 self.calendar_view.destroy();
1299 return $.when(self.load_view()).done(function() {
1300 self.render_value();
1306 load_view: function() {
1308 var calendar_view_class = get_class(this.calendar_view_class);
1309 this.calendar_view = new calendar_view_class(this, this.dataset, false, $.extend({
1310 'create_text': _t("Add"),
1311 'creatable': self.get("effective_readonly") ? false : true,
1312 'quick_creatable': self.get("effective_readonly") ? false : true,
1313 'read_only_mode': self.get("effective_readonly") ? true : false,
1314 'confirm_on_delete': false,
1316 var embedded = (this.field.views || {}).calendar;
1318 this.calendar_view.set_embedded_view(embedded);
1320 var loaded = $.Deferred();
1321 this.calendar_view.on("calendar_view_loaded", self, function() {
1322 self.initial_is_loaded.resolve();
1325 this.calendar_view.on('switch_mode', this, this.open_popup);
1326 $.async_when().done(function () {
1327 self.calendar_view.appendTo(self.$el);
1332 render_value: function() {
1334 this.dataset.set_ids(this.get("value"));
1335 this.is_loaded = this.is_loaded.then(function() {
1336 return self.calendar_view.do_search(self.build_domain(), self.dataset.get_context(), []);
1340 open_popup: function(type, unused) {
1341 if (type !== "form") { return; }
1342 if (this.dataset.index == null) {
1343 if (typeof this.open_popup_add === "function") {
1344 this.open_popup_add();
1347 if (typeof this.open_popup_edit === "function") {
1348 this.open_popup_edit();
1353 open_popup_add: function() {
1354 throw new Error("Not Implemented");
1357 open_popup_edit: function() {
1358 var id = this.dataset.ids[this.dataset.index];
1360 var pop = (new instance.web.form.FormOpenPopup(this));
1361 pop.show_element(this.field.relation, id, this.build_context(), {
1362 title: _t("Open: ") + this.string,
1363 write_function: function(id, data, _options) {
1364 return self.dataset.write(id, data, {}).done(function() {
1365 // Note that dataset will trigger itself the
1366 // ``dataset_changed`` signal
1367 self.calendar_view.refresh_event(id);
1370 read_function: function(id, fields, options) {
1371 return self.dataset.read_ids.apply(self.dataset, arguments).done(function() {
1372 }).fail(function (r, event) {
1377 alternative_form_view: this.field.views ? this.field.views.form : undefined,
1378 parent_view: this.view,
1379 child_name: this.name,
1380 readonly: this.get("effective_readonly")
1385 instance.web_calendar.Sidebar = instance.web.Widget.extend({
1386 template: 'CalendarView.sidebar',
1390 this.filter = new instance.web_calendar.SidebarFilter(this, this.getParent());
1391 this.filter.appendTo(this.$el.find('.oe_calendar_filter'));
1394 instance.web_calendar.SidebarFilter = instance.web.Widget.extend({
1396 'change input:checkbox': 'filter_click'
1398 init: function(parent, view) {
1399 this._super(parent);
1402 set_filters: function() {
1404 _.forEach(self.view.all_filters, function(o) {
1405 if (_.contains(self.view.now_filter_ids, o.value)) {
1406 self.$('div.oe_calendar_responsible input[value=' + o.value + ']').prop('checked',o.is_checked);
1410 events_loaded: function(filters) {
1412 if (filters == null) {
1414 _.forEach(self.view.all_filters, function(o) {
1415 if (_.contains(self.view.now_filter_ids, o.value)) {
1420 this.$el.html(QWeb.render('CalendarView.sidebar.responsible', { filters: filters }));
1422 filter_click: function(e) {
1424 self.view.all_filters[parseInt(e.target.value)].is_checked = e.target.checked;
1425 self.view.$calendar.fullCalendar('refetchEvents');
1427 addUpdateButton: function() {
1429 this.$('div.oe_calendar_all_responsibles').append(QWeb.render('CalendarView.sidebar.button_add_contact'));
1430 this.$(".add_contacts_link_btn").on('click', function() {
1431 self.rpc("/web/action/load", {
1432 action_id: "calendar.action_calendar_contacts"
1433 }).then( function(result) { return self.do_action(result); });