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) {
14 var _t = instance.web._t,
15 _lt = instance.web._lt,
16 QWeb = instance.web.qweb;
18 function get_class(name) {
19 return new instance.web.Registry({'tmp' : name}).get_object("tmp");
22 function get_fc_defaultOptions() {
23 shortTimeformat = moment._locale._longDateFormat.LT;
24 var dateFormat = instance.web.normalize_format(_t.database.parameters.date_format);
26 weekNumberTitle: _t("W"),
27 allDayText: _t("All day"),
34 monthNames: moment.months(),
35 monthNamesShort: moment.monthsShort(),
36 dayNames: moment.weekdays(),
37 dayNamesShort: moment.weekdaysShort(),
38 firstDay: moment._locale._week.dow,
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
49 week: dateFormat + "{ '—'"+ dateFormat,
54 week: 'ddd ' + dateFormat,
55 day: 'dddd ' + dateFormat,
63 function is_virtual_id(id) {
64 return typeof id === "string" && id.indexOf('-') >= 0;
67 function isNullOrUndef(value) {
68 return _.isUndefined(value) || _.isNull(value);
71 instance.web.views.add('calendar', 'instance.web_calendar.CalendarView');
73 instance.web_calendar.CalendarView = instance.web.View.extend({
74 template: "CalendarView",
75 display_name: _lt('Calendar'),
76 quick_create_instance: 'instance.web_calendar.QuickCreate',
78 init: function (parent, dataset, view_id, options) {
80 this.ready = $.Deferred();
81 this.set_default_options(options);
82 this.dataset = dataset;
83 this.model = dataset.model;
84 this.fields_view = {};
85 this.view_id = view_id;
86 this.view_type = 'calendar';
88 this.range_start = null;
89 this.range_stop = null;
90 this.selected_filters = [];
92 this.shown = $.Deferred();
95 set_default_options: function(options) {
97 _.defaults(this.options, {
98 confirm_on_delete: true
102 destroy: function() {
103 this.$calendar.fullCalendar('destroy');
104 if (this.$small_calendar) {
105 this.$small_calendar.datepicker('destroy');
107 this._super.apply(this, arguments);
110 view_loading: function (fv) {
111 /* xml view calendar options */
112 var attrs = fv.arch.attrs,
114 this.fields_view = fv;
115 this.$calendar = this.$el.find(".oe_calendar_widget");
117 this.info_fields = [];
120 this.$buttons = $(QWeb.render("CalendarView.buttons", {'widget': this}));
121 if (this.options.$buttons) {
122 this.$buttons.appendTo(this.options.$buttons);
124 this.$el.find('.oe_calendar_buttons').replaceWith(this.$buttons);
127 this.$buttons.on('click', 'button.oe_calendar_button_new', function () {
128 self.dataset.index = null;
129 self.do_switch_view('form');
132 if (!attrs.date_start) {
133 throw new Error(_t("Calendar view has not defined 'date_start' attribute."));
136 this.$el.addClass(attrs['class']);
138 this.name = fv.name || attrs.string;
139 this.view_id = fv.view_id;
141 this.mode = attrs.mode; // one of month, week or day
142 this.date_start = attrs.date_start; // Field name of starting date field
143 this.date_delay = attrs.date_delay; // duration
144 this.date_stop = attrs.date_stop;
145 this.all_day = attrs.all_day;
146 this.how_display_event = '';
147 this.attendee_people = attrs.attendee;
149 if (!isNullOrUndef(attrs.quick_create_instance)) {
150 self.quick_create_instance = 'instance.' + attrs.quick_create_instance;
153 //if quick_add = False, we don't allow quick_add
154 //if quick_add = not specified in view, we use the default quick_create_instance
155 //if quick_add = is NOT False and IS specified in view, we this one for quick_create_instance'
157 this.quick_add_pop = (isNullOrUndef(attrs.quick_add) || _.str.toBoolElse(attrs.quick_add, true));
158 if (this.quick_add_pop && !isNullOrUndef(attrs.quick_add)) {
159 self.quick_create_instance = 'instance.' + attrs.quick_add;
161 // The display format which will be used to display the event where fields are between "[" and "]"
162 if (!isNullOrUndef(attrs.display)) {
163 this.how_display_event = attrs.display; // String with [FIELD]
166 // 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
167 if (isNullOrUndef(attrs.event_open_popup) || !_.str.toBoolElse(attrs.event_open_popup, true)) {
168 this.open_popup_action = false;
170 this.open_popup_action = attrs.event_open_popup;
172 // If this field is set to true, we will use the calendar_friends model as filter and not the color field.
173 this.useContacts = (!isNullOrUndef(attrs.use_contacts) && _.str.toBool(attrs.use_contacts)) && (!isNullOrUndef(self.options.$sidebar));
175 // 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
176 // The color is the color of the attendee, so don't need to show again that it will be present
177 this.colorIsAttendee = (!(isNullOrUndef(attrs.color_is_attendee) || !_.str.toBoolElse(attrs.color_is_attendee, true))) && (!isNullOrUndef(self.options.$sidebar));
179 // if we have not sidebar, (eg: Dashboard), we don't use the filter "coworkers"
180 if (isNullOrUndef(self.options.$sidebar)) {
181 this.useContacts = false;
182 this.colorIsAttendee = false;
183 this.attendee_people = undefined;
187 Will be more logic to do it in futur, but see below to stay Retro-compatible
189 if (isNull(attrs.avatar_model)) {
190 this.avatar_model = 'res.partner';
193 if (attrs.avatar_model == 'False') {
194 this.avatar_model = null;
197 this.avatar_model = attrs.avatar_model;
201 if (isNullOrUndef(attrs.avatar_model)) {
202 this.avatar_model = null;
204 this.avatar_model = attrs.avatar_model;
207 if (isNullOrUndef(attrs.avatar_title)) {
208 this.avatar_title = this.avatar_model;
210 this.avatar_title = attrs.avatar_title;
213 if (isNullOrUndef(attrs.avatar_filter)) {
214 this.avatar_filter = this.avatar_model;
216 this.avatar_filter = attrs.avatar_filter;
219 this.color_field = attrs.color;
221 if (this.color_field && this.selected_filters.length === 0) {
223 if ((default_filter = this.dataset.context['calendar_default_' + this.color_field])) {
224 this.selected_filters.push(default_filter + '');
228 this.fields = fv.fields;
230 for (var fld = 0; fld < fv.arch.children.length; fld++) {
231 this.info_fields.push(fv.arch.children[fld].attrs.name);
234 self.shown.done(this._do_show_init.bind(this));
235 var edit_check = new instance.web.Model(this.dataset.model)
236 .call("check_access_rights", ["write", false])
237 .then(function (write_right) {
238 self.write_right = write_right;
240 var init = new instance.web.Model(this.dataset.model)
241 .call("check_access_rights", ["create", false])
242 .then(function (create_right) {
243 self.create_right = create_right;
244 self.ready.resolve();
245 self.trigger('calendar_view_loaded', fv);
247 return $.when(edit_check, init);
249 _do_show_init: function () {
251 this.init_calendar().then(function() {
252 $(window).trigger('resize');
253 self.trigger('calendar_view_loaded', self.fields_view);
256 get_fc_init_options: function () {
257 //Documentation here : http://arshaw.com/fullcalendar/docs/
259 return $.extend({}, get_fc_defaultOptions(), {
261 defaultView: (this.mode == "month")?"month":
262 (this.mode == "week"?"agendaWeek":
263 (this.mode == "day"?"agendaDay":"month")),
265 left: 'prev,next today',
267 right: 'month,agendaWeek,agendaDay'
269 selectable: !this.options.read_only_mode && this.create_right,
271 editable: !this.options.read_only_mode,
276 eventDrop: function (event, _day_delta, _minute_delta, _all_day, _revertFunc) {
277 var data = self.get_event_data(event);
278 self.proxy('update_record')(event._id, data); // we don't revert the event, but update it.
280 eventResize: function (event, _day_delta, _minute_delta, _revertFunc) {
281 var data = self.get_event_data(event);
282 self.proxy('update_record')(event._id, data);
284 eventRender: function (event, element, view) {
285 element.find('.fc-event-title').html(event.title);
287 eventAfterRender: function (event, element, view) {
288 if ((view.name !== 'month') && (((event.end-event.start)/60000)<=30)) {
289 //if duration is too small, we see the html code of img
290 var current_title = $(element.find('.fc-event-time')).text();
291 var new_title = current_title.substr(0,current_title.indexOf("<img")>0?current_title.indexOf("<img"):current_title.length);
292 element.find('.fc-event-time').html(new_title);
295 eventClick: function (event) { self.open_event(event._id,event.title); },
296 select: function (start_date, end_date, all_day, _js_event, _view) {
297 var data_template = self.get_event_data({
302 self.open_quick_create(data_template);
312 calendarMiniChanged: function (context) {
313 return function(datum,obj) {
314 var curView = context.$calendar.fullCalendar( 'getView');
315 var curDate = new Date(obj.currentYear , obj.currentMonth, obj.currentDay);
317 if (curView.name == "agendaWeek") {
318 if (curDate <= curView.end && curDate >= curView.start) {
319 context.$calendar.fullCalendar('changeView','agendaDay');
322 else if (curView.name != "agendaDay" || (curView.name == "agendaDay" && moment(curDate).diff(moment(curView.start))===0)) {
323 context.$calendar.fullCalendar('changeView','agendaWeek');
325 context.$calendar.fullCalendar('gotoDate', obj.currentYear , obj.currentMonth, obj.currentDay);
329 init_calendar: function() {
332 if (!this.sidebar && this.options.$sidebar) {
333 translate = get_fc_defaultOptions();
334 this.sidebar = new instance.web_calendar.Sidebar(this);
335 this.sidebar.appendTo(this.$el.find('.oe_calendar_sidebar_container'));
337 this.$small_calendar = self.$el.find(".oe_calendar_mini");
338 this.$small_calendar.datepicker({
339 onSelect: self.calendarMiniChanged(self),
340 dayNamesMin : translate.dayNamesShort,
341 monthNames: translate.monthNamesShort,
342 firstDay: translate.firstDay,
347 self.$calendar.fullCalendar(self.get_fc_init_options());
351 extraSideBar: function() {
354 open_quick_create: function(data_template) {
355 if (!isNullOrUndef(this.quick)) {
356 return this.quick.trigger('close');
358 var QuickCreate = get_class(this.quick_create_instance);
360 this.options.disable_quick_create = this.options.disable_quick_create || !this.quick_add_pop;
362 this.quick = new QuickCreate(this, this.dataset, true, this.options, data_template);
363 this.quick.on('added', this, this.quick_created)
364 .on('slowadded', this, this.slow_created)
365 .on('close', this, function() {
366 this.quick.destroy();
368 this.$calendar.fullCalendar('unselect');
370 this.quick.replace(this.$el.find('.oe_calendar_qc_placeholder'));
376 * Refresh one fullcalendar event identified by it's 'id' by reading OpenERP record state.
377 * If event was not existent in fullcalendar, it'll be created.
379 refresh_event: function(id) {
381 if (is_virtual_id(id)) {
382 // Should avoid "refreshing" a virtual ID because it can't
383 // really be modified so it should never be refreshed. As upon
384 // edition, a NEW event with a non-virtual id will be created.
385 console.warn("Unwise use of refresh_event on a virtual ID.");
387 this.dataset.read_ids([id], _.keys(this.fields)).done(function (incomplete_records) {
388 self.perform_necessary_name_gets(incomplete_records).then(function(records) {
389 // Event boundaries were already changed by fullcalendar, but we need to reload them:
390 var new_event = self.event_data_transform(records[0]);
392 var event_objs = self.$calendar.fullCalendar('clientEvents', id);
393 if (event_objs.length == 1) { // Already existing obj to update
394 var event_obj = event_objs[0];
396 _(new_event).each(function (value, key) {
397 event_obj[key] = value;
399 self.$calendar.fullCalendar('updateEvent', event_obj);
400 } else { // New event object to create
401 self.$calendar.fullCalendar('renderEvent', new_event);
402 // By forcing attribution of this event to this source, we
403 // make sure that the event will be removed when the source
404 // will be removed (which occurs at each do_search)
405 self.$calendar.fullCalendar('clientEvents', id)[0].source = self.event_source;
411 get_color: function(key) {
412 if (this.color_map[key]) {
413 return this.color_map[key];
415 var index = (((_.keys(this.color_map).length + 1) * 5) % 24) + 1;
416 this.color_map[key] = index;
422 * In o2m case, records from dataset won't have names attached to their *2o values.
423 * We should make sure this is the case.
425 perform_necessary_name_gets: function(evts) {
426 var def = $.Deferred();
429 _(this.info_fields).each(function (fieldname) {
430 if (!_(["many2one", "one2one"]).contains(
431 self.fields[fieldname].type))
433 to_get[fieldname] = [];
434 _(evts).each(function (evt) {
435 var value = evt[fieldname];
436 if (value === false || (value instanceof Array)) {
439 to_get[fieldname].push(value);
441 if (to_get[fieldname].length === 0) {
442 delete to_get[fieldname];
445 var defs = _(to_get).map(function (ids, fieldname) {
446 return (new instance.web.Model(self.fields[fieldname].relation))
447 .call('name_get', ids).then(function (vals) {
448 return [fieldname, vals];
452 $.when.apply(this, defs).then(function() {
453 var values = arguments;
454 _(values).each(function(value) {
455 var fieldname = value[0];
456 var name_gets = value[1];
457 _(name_gets).each(function(name_get) {
459 .filter(function (e) {return e[fieldname] == name_get[0];})
460 .each(function(evt) {
461 evt[fieldname] = name_get;
471 * Transform OpenERP event object to fullcalendar event object
473 event_data_transform: function(evt) {
476 var date_delay = evt[this.date_delay] || 1.0,
477 all_day = this.all_day ? evt[this.all_day] : false,
478 res_computed_text = '',
483 date_start = instance.web.auto_str_to_date(evt[this.date_start]);
484 date_stop = this.date_stop ? instance.web.auto_str_to_date(evt[this.date_stop]) : null;
487 date_start = instance.web.auto_str_to_date(evt[this.date_start].split(' ')[0],'start');
488 date_stop = this.date_stop ? instance.web.auto_str_to_date(evt[this.date_stop].split(' ')[0],'start') : null;
491 if (this.info_fields) {
493 res_computed_text = this.how_display_event;
495 _.each(this.info_fields, function (fieldname) {
496 var value = evt[fieldname];
497 if (_.contains(["many2one", "one2one"], self.fields[fieldname].type)) {
498 if (value === false) {
499 temp_ret[fieldname] = null;
501 else if (value instanceof Array) {
502 temp_ret[fieldname] = value[1]; // no name_get to make
505 throw new Error("Incomplete data received from dataset for record " + evt.id);
508 else if (_.contains(["one2many","many2many"], self.fields[fieldname].type)) {
509 if (value === false) {
510 temp_ret[fieldname] = null;
512 else if (value instanceof Array) {
513 temp_ret[fieldname] = value; // if x2many, keep all id !
516 throw new Error("Incomplete data received from dataset for record " + evt.id);
520 temp_ret[fieldname] = value;
522 res_computed_text = res_computed_text.replace("["+fieldname+"]",temp_ret[fieldname]);
526 if (res_computed_text.length) {
527 the_title = res_computed_text;
531 _.each(temp_ret, function(val,key) { res_text.push(val); });
532 the_title = res_text.join(', ');
534 the_title = _.escape(the_title);
537 the_title_avatar = '';
539 if (! _.isUndefined(this.attendee_people)) {
540 var MAX_ATTENDEES = 3;
541 var attendee_showed = 0;
542 var attendee_other = '';
544 _.each(temp_ret[this.attendee_people],
545 function (the_attendee_people) {
546 attendees.push(the_attendee_people);
547 attendee_showed += 1;
548 if (attendee_showed<= MAX_ATTENDEES) {
549 if (self.avatar_model !== null) {
550 the_title_avatar += '<img title="' + self.all_attendees[the_attendee_people] + '" class="attendee_head" \
551 src="/web/binary/image?model=' + self.avatar_model + '&field=image_small&id=' + the_attendee_people + '"></img>';
554 if (!self.colorIsAttendee || the_attendee_people != temp_ret[self.color_field]) {
555 tempColor = (self.all_filters[the_attendee_people] !== undefined)
556 ? self.all_filters[the_attendee_people].color
557 : (self.all_filters[-1] ? self.all_filters[-1].color : 1);
558 the_title_avatar += '<i class="fa fa-user attendee_head color_'+tempColor+'" title="' + self.all_attendees[the_attendee_people] + '" ></i>';
559 }//else don't add myself
563 attendee_other += self.all_attendees[the_attendee_people] +", ";
567 if (attendee_other.length>2) {
568 the_title_avatar += '<span class="attendee_head" title="' + attendee_other.slice(0, -2) + '">+</span>';
570 the_title = the_title_avatar + the_title;
574 if (!date_stop && date_delay) {
575 var m_start = moment(date_start).add(date_delay,'hours');
576 date_stop = m_start.toDate();
579 'start': moment(date_start).format('YYYY-MM-DD HH:mm:ss'),
580 'end': moment(date_stop).format('YYYY-MM-DD HH:mm:ss'),
582 'allDay': (this.fields[this.date_start].type == 'date' || (this.all_day && evt[this.all_day]) || false),
584 'attendees':attendees
586 if (!self.useContacts || self.all_filters[evt[this.color_field]] !== undefined) {
587 if (this.color_field && evt[this.color_field]) {
588 var color_key = evt[this.color_field];
589 if (typeof color_key === "object") {
590 color_key = color_key[0];
592 r.className = 'cal_opacity calendar_color_'+ this.get_color(color_key);
595 else { // if form all, get color -1
596 r.className = 'cal_opacity calendar_color_'+ self.all_filters[-1].color;
602 * Transform fullcalendar event object to OpenERP Data object
604 get_event_data: function(event) {
606 // Normalize event_end without changing fullcalendars event.
611 var event_end = event.end;
612 //Bug when we move an all_day event from week or day view, we don't have a dateend or duration...
613 if (event_end == null) {
614 var m_date = moment(event.start).add(2, 'hours');
615 event_end = m_date.toDate();
619 // Sometimes fullcalendar doesn't give any event.end.
620 if (event_end == null || _.isUndefined(event_end)) {
621 event_end = new Date(event.start);
624 date_start_day = new Date(Date.UTC(event.start.getFullYear(),event.start.getMonth(),event.start.getDate()));
625 date_stop_day = new Date(Date.UTC(event_end.getFullYear(),event_end.getMonth(),event_end.getDate()));
628 date_start_day = new Date(event.start.getFullYear(),event.start.getMonth(),event.start.getDate(),7);
629 date_stop_day = new Date(event_end.getFullYear(),event_end.getMonth(),event_end.getDate(),19);
631 data[this.date_start] = instance.web.datetime_to_str(date_start_day);
632 if (this.date_stop) {
633 data[this.date_stop] = instance.web.datetime_to_str(date_stop_day);
635 diff_seconds = Math.round((date_stop_day.getTime() - date_start_day.getTime()) / 1000);
639 data[this.date_start] = instance.web.datetime_to_str(event.start);
640 if (this.date_stop) {
641 data[this.date_stop] = instance.web.datetime_to_str(event_end);
643 diff_seconds = Math.round((event_end.getTime() - event.start.getTime()) / 1000);
647 data[this.all_day] = event.allDay;
650 if (this.date_delay) {
652 data[this.date_delay] = diff_seconds / 3600;
657 do_search: function (domain, context, _group_by) {
659 this.shown.done(function () {
660 self._do_search(domain, context, _group_by);
663 _do_search: function(domain, context, _group_by) {
665 if (! self.all_filters) {
666 self.all_filters = {}
669 if (! _.isUndefined(this.event_source)) {
670 this.$calendar.fullCalendar('removeEventSource', this.event_source);
672 this.event_source = {
673 events: function(start, end, callback) {
674 var current_event_source = self.event_source;
675 self.dataset.read_slice(_.keys(self.fields), {
677 domain: self.get_range_domain(domain, start, end),
679 }).done(function(events) {
680 if (self.dataset.index === null) {
682 self.dataset.index = 0;
684 } else if (self.dataset.index >= events.length) {
685 self.dataset.index = events.length ? 0 : null;
688 if (self.event_source !== current_event_source) {
689 console.log("Consecutive ``do_search`` called. Cancelling.");
693 if (!self.useContacts) { // If we use all peoples displayed in the current month as filter in sidebars
697 self.now_filter_ids = [];
699 _.each(events, function (e) {
700 filter_value = e[self.color_field][0];
701 if (!self.all_filters[e[self.color_field][0]]) {
704 label: e[self.color_field][1],
705 color: self.get_color(filter_value),
706 avatar_model: (_.str.toBoolElse(self.avatar_filter, true) ? self.avatar_filter : false ),
709 self.all_filters[e[self.color_field][0]] = filter_item;
711 if (! _.contains(self.now_filter_ids, filter_value)) {
712 self.now_filter_ids.push(filter_value);
717 self.sidebar.filter.events_loaded();
718 self.sidebar.filter.set_filters();
720 events = $.map(events, function (e) {
721 if (_.contains(self.now_filter_ids,e[self.color_field][0]) && self.all_filters[e[self.color_field][0]].is_checked) {
729 else { //WE USE CONTACT
730 if (self.attendee_people !== undefined) {
731 //if we don't filter on 'Everybody's Calendar
732 if (!self.all_filters[-1] || !self.all_filters[-1].is_checked) {
733 var checked_filter = $.map(self.all_filters, function(o) { if (o.is_checked) { return o.value; }});
734 // If we filter on contacts... we keep only events from coworkers
735 events = $.map(events, function (e) {
736 if (_.intersection(checked_filter,e[self.attendee_people]).length) {
747 var all_attendees = $.map(events, function (e) { return e[self.attendee_people]; });
748 all_attendees = _.chain(all_attendees).flatten().uniq().value();
750 self.all_attendees = {};
751 if (self.avatar_title !== null) {
752 new instance.web.Model(self.avatar_title).query(["name"]).filter([["id", "in", all_attendees]]).all().then(function(result) {
753 _.each(result, function(item) {
754 self.all_attendees[item.id] = item.name;
757 return self.perform_necessary_name_gets(events).then(callback);
761 _.each(all_attendees,function(item){
762 self.all_attendees[item] = '';
764 return self.perform_necessary_name_gets(events).then(callback);
768 eventDataTransform: function (event) {
769 return self.event_data_transform(event);
772 this.$calendar.fullCalendar('addEventSource', this.event_source);
775 * Build OpenERP Domain to filter object by this.date_start field
776 * between given start, end dates.
778 get_range_domain: function(domain, start, end) {
779 var format = instance.web.date_to_str;
781 extend_domain = [[this.date_start, '>=', format(start)],
782 [this.date_start, '<=', format(end)]];
784 if (this.date_stop) {
786 extend_domain.splice(0,0,'|','|','&');
790 [this.date_start, '<=', format(start)],
791 [this.date_stop, '>=', format(start)],
793 [this.date_start, '<=', format(end)],
794 [this.date_stop, '>=', format(start)]
796 //final -> (A & B) | (C & D) | (E & F) -> | | & A B & C D & E F
798 return new instance.web.CompoundDomain(domain, extend_domain);
802 * Updates record identified by ``id`` with values in object ``data``
804 update_record: function(id, data) {
806 delete(data.name); // Cannot modify actual name yet
807 var index = this.dataset.get_id_index(id);
808 if (index !== null) {
809 event_id = this.dataset.ids[index];
810 this.dataset.write(event_id, data, {}).done(function() {
811 if (is_virtual_id(event_id)) {
812 // this is a virtual ID and so this will create a new event
813 // with an unknown id for us.
814 self.$calendar.fullCalendar('refetchEvents');
816 // classical event that we can refresh
817 self.refresh_event(event_id);
823 open_event: function(id, title) {
825 if (! this.open_popup_action) {
826 var index = this.dataset.get_id_index(id);
827 this.dataset.index = index;
828 if (this.write_right) {
829 this.do_switch_view('form', null, { mode: "edit" });
831 this.do_switch_view('form', null, { mode: "view" });
835 var pop = new instance.web.form.FormOpenPopup(this);
836 var id_cast = parseInt(id).toString() == id ? parseInt(id) : id;
837 pop.show_element(this.dataset.model, id_cast, this.dataset.get_context(), {
838 title: _.str.sprintf(_t("View: %s"),title),
839 view_id: +this.open_popup_action,
845 var form_controller = pop.view_form;
846 form_controller.on("load_record", self, function(){
847 button_delete = _.str.sprintf("<button class='oe_button oe_bold delme'><span> %s </span></button>",_t("Delete"));
848 button_edit = _.str.sprintf("<button class='oe_button oe_bold editme oe_highlight'><span> %s </span></button>",_t("Edit Event"));
850 pop.$el.closest(".modal").find(".modal-footer").prepend(button_delete);
851 pop.$el.closest(".modal").find(".modal-footer").prepend(button_edit);
855 $('.oe_form_button_cancel').trigger('click');
856 self.remove_event(id);
861 $('.oe_form_button_cancel').trigger('click');
862 self.dataset.index = self.dataset.get_id_index(id);
863 self.do_switch_view('form', null, { mode: "edit" });
871 do_show: function() {
873 this.$buttons.show();
875 this.do_push_state({});
876 this.shown.resolve();
877 return this._super();
879 do_hide: function () {
881 this.$buttons.hide();
883 return this._super();
885 is_action_enabled: function(action) {
886 if (action === 'create' && !this.options.creatable) {
889 return this._super(action);
893 * Handles a newly created record
895 * @param {id} id of the newly created record
897 quick_created: function (id) {
900 * it's of the most utter importance NOT to use inplace
901 * modification on this.dataset.ids as reference to this
902 * data is spread out everywhere in the various widget.
903 * Some of these reference includes values that should
904 * trigger action upon modification.
906 this.dataset.ids = this.dataset.ids.concat([id]);
907 this.dataset.trigger("dataset_changed", id);
908 this.refresh_event(id);
910 slow_created: function () {
911 // refresh all view, because maybe some recurrents item
914 // force filter refresh
915 self.sidebar.filter.is_loaded = false;
917 self.$calendar.fullCalendar('refetchEvents');
920 remove_event: function(id) {
923 return $.when(self.dataset.unlink([id])).then(function() {
924 self.$calendar.fullCalendar('removeEvents', id);
927 if (this.options.confirm_on_delete) {
928 if (confirm(_t("Are you sure you want to delete this record ?"))) {
938 * Quick creation view.
940 * Triggers a single event "added" with a single parameter "name", which is the
941 * name entered by the user
946 instance.web_calendar.QuickCreate = instance.web.Widget.extend({
947 template: 'CalendarView.quick_create',
949 init: function(parent, dataset, buttons, options, data_template) {
951 this.dataset = dataset;
952 this._buttons = buttons || false;
953 this.options = options;
955 // Can hold data pre-set from where you clicked on agenda
956 this.data_template = data_template || {};
958 get_title: function () {
959 var parent = this.getParent();
960 if (_.isUndefined(parent)) {
963 var title = (_.isUndefined(parent.field_widget)) ?
964 (parent.string || parent.name) :
965 parent.field_widget.string || parent.field_widget.name || '';
966 return _t("Create: ") + title;
971 if (this.options.disable_quick_create) {
977 self.$input = this.$el.find('input');
978 self.$input.keyup(function enterHandler (event) {
979 if(event.keyCode == 13){
980 self.$input.off('keyup', enterHandler);
981 if (!self.quick_add()){
982 self.$input.on('keyup', enterHandler);
987 var submit = this.$el.find(".oe_calendar_quick_create_add");
988 submit.click(function clickHandler() {
989 submit.off('click', clickHandler);
990 if (!self.quick_add()){
991 submit.on('click', clickHandler); }
994 this.$el.find(".oe_calendar_quick_create_edit").click(function () {
998 this.$el.find(".oe_calendar_quick_create_close").click(function (ev) {
1000 self.trigger('close');
1002 self.$input.keyup(function enterHandler (e) {
1003 if (e.keyCode == 27 && self._buttons) {
1004 self.trigger('close');
1007 self.$el.dialog({ title: this.get_title()});
1008 self.on('added', self, function() {
1009 self.trigger('close');
1012 self.$el.on('dialogclose', self, function() {
1013 self.trigger('close');
1018 this.$el.find('input').focus();
1022 * Gathers data from the quick create dialog a launch quick_create(data) method
1024 quick_add: function() {
1025 var val = this.$input.val();
1026 if (/^\s*$/.test(val)) {
1029 return this.quick_create({'name': val}).always(function() { return true; });
1032 slow_add: function() {
1033 var val = this.$input.val();
1034 this.slow_create({'name': val});
1038 * Handles saving data coming from quick create box
1040 quick_create: function(data, options) {
1042 return this.dataset.create($.extend({}, this.data_template, data), options)
1043 .then(function(id) {
1044 self.trigger('added', id);
1045 self.$input.val("");
1046 }).fail(function(r, event) {
1047 event.preventDefault();
1048 // This will occurs if there are some more fields required
1049 self.slow_create(data);
1054 * Show full form popup
1056 get_form_popup_infos: function() {
1057 var parent = this.getParent();
1062 if (!_.isUndefined(parent) && !(_.isUndefined(parent.ViewManager))) {
1063 infos.view_id = parent.ViewManager.get_view_id('form');
1067 slow_create: function(data) {
1068 //if all day, we could reset time to display 00:00:00
1071 var def = $.Deferred();
1073 var created = false;
1075 _.each($.extend({}, this.data_template, data), function(val, field_name) {
1076 defaults['default_' + field_name] = val;
1079 var pop_infos = self.get_form_popup_infos();
1080 var pop = new instance.web.form.FormOpenPopup(this);
1081 var context = new instance.web.CompoundContext(this.dataset.context, defaults);
1082 pop.show_element(this.dataset.model, null, this.dataset.get_context(defaults), {
1083 title: this.get_title(),
1084 disable_multiple_selection: true,
1085 view_id: pop_infos.view_id,
1086 // Ensuring we use ``self.dataset`` and DO NOT create a new one.
1087 create_function: function(data, options) {
1088 return self.dataset.create(data, options).done(function(r) {
1089 }).fail(function (r, event) {
1090 if (!r.data.message) { //else manage by openerp
1095 read_function: function(id, fields, options) {
1096 return self.dataset.read_ids.apply(self.dataset, arguments).done(function() {
1097 }).fail(function (r, event) {
1098 if (!r.data.message) { //else manage by openerp
1104 pop.on('closed', self, function() {
1105 // ``self.trigger('close')`` would itself destroy all child element including
1106 // the slow create popup, which would then re-trigger recursively the 'closed' signal.
1107 // Thus, here, we use a deferred and its state to cut the endless recurrence.
1108 if (def.state() === "pending") {
1112 pop.on('create_completed', self, function(id) {
1114 self.trigger('slowadded');
1116 def.then(function() {
1118 var parent = self.getParent();
1119 parent.$calendar.fullCalendar('refetchEvents');
1121 self.trigger('close');
1132 function widget_calendar_lazy_init() {
1133 if (instance.web.form.Many2ManyCalendarView) {
1137 instance.web_calendar.FieldCalendarView = instance.web_calendar.CalendarView.extend({
1139 init: function (parent) {
1140 this._super.apply(this, arguments);
1141 // Warning: this means only a field_widget should instanciate this Class
1142 this.field_widget = parent;
1145 view_loading: function (fv) {
1147 return $.when(this._super.apply(this, arguments)).then(function() {
1148 self.on('event_rendered', this, function (event, element, view) {
1154 // In forms, we could be hidden in a notebook. Thus we couldn't
1155 // render correctly fullcalendar so we try to detect when we are
1156 // not visible to wait for when we will be visible.
1157 init_calendar: function() {
1158 if (this.$calendar.width() !== 0) { // visible
1159 return this._super();
1161 // find all parents tabs.
1162 var def = $.Deferred();
1164 this.$calendar.parents(".ui-tabs").on('tabsactivate', this, function() {
1165 if (self.$calendar.width() !== 0) { // visible
1166 self.$calendar.fullCalendar(self.get_fc_init_options());
1175 instance.web_calendar.BufferedDataSet = instance.web.BufferedDataSet.extend({
1178 * Adds verification on possible missing fields for the sole purpose of
1179 * O2M dataset being compatible with the ``slow_create`` detection of
1180 * missing fields... which is as simple to try to write and upon failure
1181 * go to ``slow_create``. Current BufferedDataSet would'nt fail because
1182 * they do not send data to the server at create time.
1184 create: function (data, options) {
1185 var def = $.Deferred();
1187 var create = this._super;
1188 if (_.isUndefined(this.required_fields)) {
1189 this.required_fields = (new instance.web.Model(this.model))
1190 .call('fields_get').then(function (fields_def) {
1191 return _(fields_def).chain()
1192 // equiv to .pairs()
1193 .map(function (value, key) { return [key, value]; })
1194 // equiv to .omit(self.field_widget.field.relation_field)
1195 .filter(function (pair) { return pair[0] !== self.field_widget.field.relation_field; })
1196 .filter(function (pair) { return pair[1].required; })
1197 .map(function (pair) { return pair[0]; })
1201 $.when(this.required_fields).then(function (required_fields) {
1202 var missing_fields = _(required_fields).filter(function (v) {
1203 return _.isUndefined(data[v]);
1205 var default_get = (missing_fields.length !== 0) ?
1206 self.default_get(missing_fields) : [];
1207 $.when(default_get).then(function (defaults) {
1209 // Remove all fields that have a default from the missing fields.
1210 missing_fields = _(missing_fields).filter(function (f) {
1211 return _.isUndefined(defaults[f]);
1213 if (missing_fields.length !== 0) {
1216 _t("Missing required fields %s"), missing_fields.join(", ")),
1220 create.apply(self, [data, options]).then(function (result) {
1221 def.resolve(result);
1229 instance.web_calendar.fields_dataset = new instance.web.Registry({
1230 'many2many': 'instance.web.DataSetStatic',
1231 'one2many': 'instance.web_calendar.BufferedDataSet',
1235 function get_field_dataset_class(type) {
1236 var obj = instance.web_calendar.fields_dataset.get_any([type]);
1238 throw new Error(_.str.sprintf(_t("Dataset for type '%s' is not defined."), type));
1241 // Override definition of legacy datasets to add field_widget context
1243 init: function (parent) {
1244 this._super.apply(this, arguments);
1245 this.field_widget = parent;
1247 get_context: function() {
1248 this.context = this.field_widget.build_context();
1249 return this.context;
1255 * Common part to manage any field using calendar view
1257 instance.web_calendar.FieldCalendar = instance.web.form.AbstractField.extend({
1259 disable_utility_classes: true,
1260 calendar_view_class: 'instance.web_calendar.FieldCalendarView',
1262 init: function(field_manager, node) {
1263 this._super(field_manager, node);
1264 widget_calendar_lazy_init();
1265 this.is_loaded = $.Deferred();
1266 this.initial_is_loaded = this.is_loaded;
1270 // This dataset will use current widget to '.build_context()'.
1271 var field_type = field_manager.fields_view.fields[node.attrs.name].type;
1272 this.dataset = new (get_field_dataset_class(field_type))(
1273 this, this.field.relation);
1275 this.dataset.on('unlink', this, function(_ids) {
1276 this.dataset.trigger('dataset_changed');
1279 // quick_create widget instance will be attached when spawned
1280 this.quick_create = null;
1282 this.no_rerender = true;
1287 this._super.apply(this, arguments);
1292 self.on("change:effective_readonly", self, function() {
1293 self.is_loaded = self.is_loaded.then(function() {
1294 self.calendar_view.destroy();
1295 return $.when(self.load_view()).done(function() {
1296 self.render_value();
1302 load_view: function() {
1304 var calendar_view_class = get_class(this.calendar_view_class);
1305 this.calendar_view = new calendar_view_class(this, this.dataset, false, $.extend({
1306 'create_text': _t("Add"),
1307 'creatable': self.get("effective_readonly") ? false : true,
1308 'quick_creatable': self.get("effective_readonly") ? false : true,
1309 'read_only_mode': self.get("effective_readonly") ? true : false,
1310 'confirm_on_delete': false,
1312 var embedded = (this.field.views || {}).calendar;
1314 this.calendar_view.set_embedded_view(embedded);
1316 var loaded = $.Deferred();
1317 this.calendar_view.on("calendar_view_loaded", self, function() {
1318 self.initial_is_loaded.resolve();
1321 this.calendar_view.on('switch_mode', this, this.open_popup);
1322 $.async_when().done(function () {
1323 self.calendar_view.appendTo(self.$el);
1328 render_value: function() {
1330 this.dataset.set_ids(this.get("value"));
1331 this.is_loaded = this.is_loaded.then(function() {
1332 return self.calendar_view.do_search(self.build_domain(), self.dataset.get_context(), []);
1336 open_popup: function(type, unused) {
1337 if (type !== "form") { return; }
1338 if (this.dataset.index == null) {
1339 if (typeof this.open_popup_add === "function") {
1340 this.open_popup_add();
1343 if (typeof this.open_popup_edit === "function") {
1344 this.open_popup_edit();
1349 open_popup_add: function() {
1350 throw new Error("Not Implemented");
1353 open_popup_edit: function() {
1354 var id = this.dataset.ids[this.dataset.index];
1356 var pop = (new instance.web.form.FormOpenPopup(this));
1357 pop.show_element(this.field.relation, id, this.build_context(), {
1358 title: _t("Open: ") + this.string,
1359 write_function: function(id, data, _options) {
1360 return self.dataset.write(id, data, {}).done(function() {
1361 // Note that dataset will trigger itself the
1362 // ``dataset_changed`` signal
1363 self.calendar_view.refresh_event(id);
1366 read_function: function(id, fields, options) {
1367 return self.dataset.read_ids.apply(self.dataset, arguments).done(function() {
1368 }).fail(function (r, event) {
1373 alternative_form_view: this.field.views ? this.field.views.form : undefined,
1374 parent_view: this.view,
1375 child_name: this.name,
1376 readonly: this.get("effective_readonly")
1381 instance.web_calendar.Sidebar = instance.web.Widget.extend({
1382 template: 'CalendarView.sidebar',
1386 this.filter = new instance.web_calendar.SidebarFilter(this, this.getParent());
1387 this.filter.appendTo(this.$el.find('.oe_calendar_filter'));
1390 instance.web_calendar.SidebarFilter = instance.web.Widget.extend({
1392 'change input:checkbox': 'filter_click'
1394 init: function(parent, view) {
1395 this._super(parent);
1398 set_filters: function() {
1400 _.forEach(self.view.all_filters, function(o) {
1401 if (_.contains(self.view.now_filter_ids, o.value)) {
1402 self.$('div.oe_calendar_responsible input[value=' + o.value + ']').prop('checked',o.is_checked);
1406 events_loaded: function(filters) {
1408 if (filters == null) {
1410 _.forEach(self.view.all_filters, function(o) {
1411 if (_.contains(self.view.now_filter_ids, o.value)) {
1416 this.$el.html(QWeb.render('CalendarView.sidebar.responsible', { filters: filters }));
1418 filter_click: function(e) {
1420 if (self.view.all_filters[0] && e.target.value == self.view.all_filters[0].value) {
1421 self.view.all_filters[0].is_checked = e.target.checked;
1423 self.view.all_filters[parseInt(e.target.value)].is_checked = e.target.checked;
1425 self.view.$calendar.fullCalendar('refetchEvents');