Ejemplo n.º 1
0
ecore.define('google_calendar.google_calendar', function (require) {
"use strict";

var core = require('web.core');
var Dialog = require('web.Dialog');
var framework = require('web.framework');
var pyeval = require('web.pyeval');
var CalendarView = require('web_calendar.CalendarView');

var _t = core._t;
var QWeb = core.qweb;

CalendarView.include({
    view_loading: function(r) {
        var self = this;
        this.$el.on('click', '.o_google_sync_button', function() {
            self.sync_calendar(r);
        });
        return this._super(r);
    },
    sync_calendar: function(res, button) {
        var self = this;
        var context = pyeval.eval('context');
        this.$google_button.prop('disabled', true);

        this.rpc('/google_calendar/sync_data', {
            arch: res.arch,
            fields: res.fields,
            model: res.model,
            fromurl: window.location.href,
            local_context: context,
        }).done(function(o) {
            if (o.status === "need_auth") {
                Dialog.alert(self, _t("You will be redirected to Google to authorize access to your calendar!"), {
                    confirm_callback: function() {
                        framework.redirect(o.url);
                    },
                    title: _t('Redirection'),
                });
            } else if (o.status === "need_config_from_admin") {
                if (!_.isUndefined(o.action) && parseInt(o.action)) {
                    Dialog.confirm(self, _t("The Google Synchronization needs to be configured before you can use it, do you want to do it now?"), {
                        confirm_callback: function() {
                            self.do_action(o.action);
                        },
                        title: _t('Configuration'),
                    });
                } else {
                    Dialog.alert(self, _t("An administrator needs to configure Google Synchronization before you can use it!"), {
                        title: _t('Configuration'),
                    });
                }
            } else if (o.status === "need_refresh") {
                self.$calendar.fullCalendar('refetchEvents');
            } else if (o.status === "need_reset") {
                var confirm_text1 = _t("The account you are trying to synchronize (%s) is not the same as the last one used (%s)!");
                var confirm_text2 = _t("In order to do this, you first need to disconnect all existing events from the old account.");
                var confirm_text3 = _t("Do you want to do this now?");
                var text = _.str.sprintf(confirm_text1 + "\n" + confirm_text2 + "\n\n" + confirm_text3, o.info.new_name, o.info.old_name);
                Dialog.confirm(self, text, {
                    confirm_callback: function() {
                        self.rpc('/google_calendar/remove_references', {
                            model: res.model,
                            local_context: context,
                        }).done(function(o) {
                            if (o.status === "OK") {
                                Dialog.alert(self, _t("All events have been disconnected from your previous account. You can now restart the synchronization"), {
                                    title: _t('Event disconnection success'),
                                });
                            } else if (o.status === "KO") {
                                Dialog.alert(self, _t("An error occured while disconnecting events from your previous account. Please retry or contact your administrator."), {
                                    title: _t('Event disconnection error'),
                                });
                            } // else NOP
                        });
                    },
                    title: _t('Accounts'),
                });
            }
        }).always(function(o) { self.$google_button.prop('disabled', false); });
    },
    extraSideBar: function() {
        var self = this;
        var result = this._super();
        this.$google_button = $();
        if (this.dataset.model === "calendar.event") {
            return result.then(function() {
                this.$google_button = $('<button/>', {type: 'button', html: _t("Sync with <b>Google</b>")})
                                    .addClass('o_google_sync_button oe_button btn btn-sm btn-default')
                                    .prepend($('<img/>', {
                                        src: "/google_calendar/static/src/img/calendar_32.png",
                                    }))
                                    .prependTo(self.$('.o_calendar_filter'));
            });
        }
        return result;
    },
});

});
Ejemplo n.º 2
0
odoo.define('base_calendar.base_calendar', function (require) {
"use strict";

var core = require('web.core');
var data = require('web.data');
var form_common = require('web.form_common');
var Model = require('web.DataModel');
var WebClient = require('web.WebClient');
var CalendarView = require('web_calendar.CalendarView');
var widgets = require('web_calendar.widgets');

var FieldMany2ManyTags = core.form_widget_registry.get('many2many_tags');
var _t = core._t;
var _lt = core._lt;
var QWeb = core.qweb;


function reload_favorite_list(result) {
    var self = result;
    var current = result;
    if (result.view) {
        self = result.view;
    }
    new Model("res.users")
    .query(["partner_id"])
    .filter([["id", "=",self.dataset.context.uid]])
    .first()
    .done(function(result) {
        var sidebar_items = {};
        var filter_value = result.partner_id[0];
        var filter_item = {
            value: filter_value,
            label: result.partner_id[1] + _lt(" [Me]"),
            color: self.get_color(filter_value),
            avatar_model: self.avatar_model,
            is_checked: true,
            is_remove: false,
        };

        sidebar_items[0] = filter_item ;
        filter_item = {
                value: -1,
                label: _lt("Everybody's calendars"),
                color: self.get_color(-1),
                avatar_model: self.avatar_model,
                is_checked: false
            };
        sidebar_items[-1] = filter_item ;
        //Get my coworkers/contacts
        new Model("calendar.contacts").query(["partner_id"]).filter([["user_id", "=",self.dataset.context.uid]]).all().then(function(result) {
            _.each(result, function(item) {
                filter_value = item.partner_id[0];
                filter_item = {
                    value: filter_value,
                    label: item.partner_id[1],
                    color: self.get_color(filter_value),
                    avatar_model: self.avatar_model,
                    is_checked: true
                };
                sidebar_items[filter_value] = filter_item ;
            });
            self.all_filters = sidebar_items;
            self.now_filter_ids = $.map(self.all_filters, function(o) { return o.value; });
            
            self.sidebar.filter.events_loaded(self.all_filters);
            self.sidebar.filter.set_filters();
            self.sidebar.filter.set_distroy_filters();
            self.sidebar.filter.addInputBox();
            self.sidebar.filter.destroy_filter();
        }).done(function () {
            self.$calendar.fullCalendar('refetchEvents');
            if (current.ir_model_m2o) {
                current.ir_model_m2o.set_value(false);
            }
        });
    });
}

CalendarView.include({
    extraSideBar: function(){
        this._super();
        if (this.useContacts){
            new reload_favorite_list(this);
        }
    }
});

widgets.SidebarFilter.include({
    set_distroy_filters: function() {
        var self = this;
        // When mouse-enter the favorite list it will show the 'X' for removing partner from the favorite list.
        if (self.view.useContacts){
            self.$('.oe_calendar_all_responsibles').on('mouseenter mouseleave', function(e) {
                self.$('.oe_remove_follower').toggleClass('hidden', e.type == 'mouseleave');
            });
        }
    },
    addInputBox: function() {
        var self = this;
        if (this.dfm)
            return;
        this.dfm = new form_common.DefaultFieldManager(self);
        this.dfm.extend_field_desc({
            partner_id: {
                relation: "res.partner",
            },
        });
        var FieldMany2One = core.form_widget_registry.get('many2one');
        this.ir_model_m2o = new FieldMany2One(self.dfm, {
            attrs: {
                class: 'oe_add_input_box',
                name: "partner_id",
                type: "many2one",
                options: '{"no_open": True}',
                placeholder: _t("Add Favorite Calendar"),
            },
        });
        this.ir_model_m2o.insertAfter($('div.oe_calendar_filter'));
        this.ir_model_m2o.on('change:value', self, function() { 
            self.add_filter();
        });
    },
    add_filter: function() {
        var self = this;
        new Model("res.users")
        .query(["partner_id"])
        .filter([["id", "=",this.view.dataset.context.uid]])
        .first()
        .done(function(result){
            $.map(self.ir_model_m2o.display_value, function(element,index) {
                if (result.partner_id[0] != index){
                    self.ds_message = new data.DataSetSearch(self, 'calendar.contacts');
                    self.ds_message.call("create", [{'partner_id': index}]);
                }
            });
        });
        new reload_favorite_list(this);
    },
    destroy_filter: function(e) {
        var self= this;
        this.$(".oe_remove_follower").on('click', function(e) {
            self.ds_message = new data.DataSetSearch(self, 'calendar.contacts');
            if (! confirm(_t("Do you really want to delete this filter from favorite?"))) { return false; }
            var id = $(e.currentTarget)[0].dataset.id;
            self.ds_message.call('search', [[['partner_id', '=', parseInt(id)]]]).then(function(record){
                return self.ds_message.unlink(record);
            }).done(function() {
                new reload_favorite_list(self);
            });
        });
    },
});

WebClient.include({
    get_notif_box: function(me) {
        return $(me).closest(".ui-notify-message-style");
    },
    get_next_notif: function() {
        var self= this;
        this.rpc("/calendar/notify")
        .done(
            function(result) {
                _.each(result,  function(res) {
                    setTimeout(function() {
                        //If notification not already displayed, we add button and action on it
                        if (!($.find(".eid_"+res.event_id)).length) {
                            res.title = QWeb.render('notify_title', {'title': res.title, 'id' : res.event_id});
                            res.message += QWeb.render("notify_footer");
                            var a = self.do_notify(res.title,res.message,true);
                            
                            $(".link2event").on('click', function() {
                                self.rpc("/web/action/load", {
                                    action_id: "calendar.action_calendar_event_notify",
                                }).then( function(r) {
                                    r.res_id = res.event_id;
                                    return self.action_manager.do_action(r);
                                });
                            });
                            a.element.find(".link2recall").on('click',function() {
                                self.get_notif_box(this).find('.ui-notify-close').trigger("click");
                            });
                            a.element.find(".link2showed").on('click',function() {
                                self.get_notif_box(this).find('.ui-notify-close').trigger("click");
                                self.rpc("/calendar/notify_ack");
                            });
                        }
                        //If notification already displayed in the past, we remove the css attribute which hide this notification
                        else if (self.get_notif_box($.find(".eid_"+res.event_id)).attr("style") !== ""){
                            self.get_notif_box($.find(".eid_"+res.event_id)).attr("style","");
                        }
                    },res.timer * 1000);
                });
            }
        )
        .fail(function (err, ev) {
            if (err.code === -32098) {
                // Prevent the CrashManager to display an error
                // in case of an xhr error not due to a server error
                ev.preventDefault();
            }
        });
    },
    check_notifications: function() {
        var self= this;
        self.get_next_notif();
        self.intervalNotif = setInterval(function(){
            self.get_next_notif();
        }, 5 * 60 * 1000 );
    },
    
    //Override the show_application of addons/web/static/src/js/chrome.js       
    show_application: function() {
        this._super();
        this.check_notifications();
    },
    //Override addons/web/static/src/js/chrome.js       
    on_logout: function() {
        this._super();
        clearInterval(this.intervalNotif);
    },
});

var Many2ManyAttendee = FieldMany2ManyTags.extend({
    tag_template: "Many2ManyAttendeeTag",
    get_render_data: function(ids){
        var dataset = new data.DataSetStatic(this, this.field.relation, this.build_context());
        return dataset.call('get_attendee_detail',[ids, this.getParent().datarecord.id || false]);
    }
});

core.form_widget_registry.add('many2manyattendee', Many2ManyAttendee);

});
Ejemplo n.º 3
0
odoo.define('base_calendar.base_calendar', function (require) {
"use strict";

var bus = require('bus.bus').bus;
var core = require('web.core');
var CalendarView = require('web_calendar.CalendarView');
var data = require('web.data');
var Dialog = require('web.Dialog');
var form_common = require('web.form_common');
var Model = require('web.DataModel');
var Notification = require('web.notification').Notification;
var session = require('web.session');
var WebClient = require('web.WebClient');
var widgets = require('web_calendar.widgets');

var FieldMany2ManyTags = core.form_widget_registry.get('many2many_tags');
var _t = core._t;
var _lt = core._lt;
var QWeb = core.qweb;

CalendarView.include({
    extraSideBar: function() {
        var result = this._super();
        if (this.useContacts) {
            return result.then(this.sidebar.filter.initialize_favorites.bind(this.sidebar.filter));
        }
        return result;
    },
    get_all_filters_ordered: function() {
        var filters = this._super();
        if (this.useContacts) {
            var filter_me = _.first(_.values(this.all_filters));
            var filter_all = this.all_filters[-1];
            filters = [].concat(filter_me, _.difference(filters, [filter_me, filter_all]), filter_all);
        }
        return filters;
    }
});

var FieldMany2One = core.form_widget_registry.get('many2one');
var SidebarFilterM2O = FieldMany2One.extend({
    get_search_blacklist: function () {
        return this._super.apply(this, arguments).concat(this.filter_ids);
    },
    set_filter_ids: function (filter_ids) {
        this.filter_ids = filter_ids;
    },
});

widgets.SidebarFilter.include({
    events: _.extend(widgets.SidebarFilter.prototype.events, {
        'click .o_remove_contact': 'on_remove_filter',
    }),

    init: function () {
        this._super.apply(this, arguments);
        this.ds_contacts = new data.DataSet(this, 'calendar.contacts', session.context);
    },
    initialize_favorites: function () {
        return this.load_favorite_list().then(this.initialize_m2o.bind(this));
    },
    initialize_m2o: function() {
        this.dfm = new form_common.DefaultFieldManager(this);
        if (!this.view.useContacts) {
            return;
        }
        this.dfm.extend_field_desc({
            partner_id: {
                relation: "res.partner",
            },
        });
        this.m2o = new SidebarFilterM2O(this.dfm, {
            attrs: {
                class: 'o_add_favorite_calendar',
                name: "partner_id",
                type: "many2one",
                options: '{"no_open": True}',
                placeholder: _t("Add Favorite Calendar"),
            },
        });
        this.m2o.set_filter_ids(_.pluck(this.view.all_filters, 'value'));
        this.m2o.appendTo(this.$el);
        var self = this;
        this.m2o.on('change:value', this, function() {
            // once selected, we reset the value to false.
            if (self.m2o.get_value()) {
                self.on_add_filter();
            }
        });
    },
    load_favorite_list: function () {
        var self = this;
        // Untick sidebar's filters if there is an active partner in the context
        var active_partner = (this.view.dataset.context.active_model === 'res.partner');
        return session.is_bound.then(function() {
            self.view.all_filters = {};
            self.view.now_filter_ids = [];
            self._add_filter(session.partner_id, session.name + _lt(" [Me]"), !active_partner);
            self._add_filter(-1, _lt("Everybody's calendars"), false, false);
            //Get my coworkers/contacts
            return new Model("calendar.contacts")
                .query(["partner_id"])
                .filter([["user_id", "=", session.uid]])
                .all()
                .then(function(result) {
                    _.each(result, function(item) {
                        self._add_filter(item.partner_id[0], item.partner_id[1], !active_partner, true);
                    });

                    self.view.now_filter_ids = _.pluck(self.view.all_filters, 'value');

                    self.render();
                });
        });
    },
    reload: function () {
        this.trigger_up('reload_events');
        this.render();
        this.m2o.set_filter_ids(_.pluck(this.view.all_filters, 'value'));
        this.m2o.set_value(false);
    },
    _add_filter: function (value, label, is_checked, can_be_removed) {
        this.view.all_filters[value] = {
            value: value,
            label: label,
            color: this.view.get_color(value),
            avatar_model: this.view.avatar_model,
            is_checked: is_checked || false,
            can_be_removed: can_be_removed || false,
        };
        if (is_checked) {
            this.view.now_filter_ids.push(value);
        }
    },
    _remove_filter: function (value) {
        delete this.view.all_filters[value];
        var index = this.view.now_filter_ids.indexOf(value);
        if (index >= 0) {
            this.view.now_filter_ids.splice(index, 1);
        }
    },
    on_add_filter: function() {
        var self = this;
        var defs = [];
        _.each(this.m2o.display_value, function(element, index) {
            if (session.partner_id !== index) {
                defs.push(self.ds_contacts.call("create", [{'partner_id': index}]).then(function () {
                    self._add_filter(parseInt(index), element, true, true);
                    self.reload();
                }));
            }
        });
        return $.when.apply(null, defs).then(this.reload.bind(this));
    },
    on_remove_filter: function(e) {
        var self = this;
        var id = $(e.currentTarget).data('id');

        Dialog.confirm(this, _t("Do you really want to delete this filter from favorites ?"), {
            confirm_callback: function() {
                self.ds_contacts.call('unlink_from_partner_id', [id]).then(function () {
                    self._remove_filter(id);
                    self.reload();
                });
            },
        });
    },
});

var CalendarNotification = Notification.extend({
    template: "CalendarNotification",

    init: function(parent, title, text, eid) {
        this._super(parent, title, text, true);
        this.eid = eid;

        this.events = _.extend(this.events || {}, {
            'click .link2event': function() {
                var self = this;

                this.rpc("/web/action/load", {
                    action_id: "calendar.action_calendar_event_notify",
                }).then(function(r) {
                    r.res_id = self.eid;
                    return self.do_action(r);
                });
            },

            'click .link2recall': function() {
                this.destroy(true);
            },

            'click .link2showed': function() {
                this.destroy(true);
                this.rpc("/calendar/notify_ack");
            },
        });
    },
});

WebClient.include({
    display_calendar_notif: function(notifications) {
        var self = this;
        var last_notif_timer = 0;

        // Clear previously set timeouts and destroy currently displayed calendar notifications
        clearTimeout(this.get_next_calendar_notif_timeout);
        _.each(this.calendar_notif_timeouts, clearTimeout);
        _.each(this.calendar_notif, function(notif) {
            if (!notif.isDestroyed()) {
                notif.destroy();
            }
        });
        this.calendar_notif_timeouts = {};
        this.calendar_notif = {};

        // For each notification, set a timeout to display it
        _.each(notifications, function(notif) {
            self.calendar_notif_timeouts[notif.event_id] = setTimeout(function() {
                var notification = new CalendarNotification(self.notification_manager, notif.title, notif.message, notif.event_id);
                self.notification_manager.display(notification);
                self.calendar_notif[notif.event_id] = notification;
            }, notif.timer * 1000);
            last_notif_timer = Math.max(last_notif_timer, notif.timer);
        });

        // Set a timeout to get the next notifications when the last one has been displayed
        if (last_notif_timer > 0) {
            this.get_next_calendar_notif_timeout = setTimeout(this.get_next_calendar_notif.bind(this), last_notif_timer * 1000);
        }
    },
    get_next_calendar_notif: function() {
        this.rpc("/calendar/notify", {}, {shadow: true})
            .done(this.display_calendar_notif.bind(this))
            .fail(function(err, ev) {
                if(err.code === -32098) {
                    // Prevent the CrashManager to display an error
                    // in case of an xhr error not due to a server error
                    ev.preventDefault();
                }
            });
    },
    show_application: function() {
        // An event is triggered on the bus each time a calendar event with alarm
        // in which the current user is involved is created, edited or deleted
        this.calendar_notif_timeouts = {};
        this.calendar_notif = {};
        bus.on('notification', this, function (notifications) {
            _.each(notifications, (function (notification) {
                if (notification[0][1] === 'calendar.alarm') {
                    this.display_calendar_notif(notification[1]);
                }
            }).bind(this));
        });
        return this._super.apply(this, arguments).then(this.get_next_calendar_notif.bind(this));
    },
});

var Many2ManyAttendee = FieldMany2ManyTags.extend({
    tag_template: "Many2ManyAttendeeTag",
    get_render_data: function (ids) {
        return this.dataset.call('get_attendee_detail', [ids, this.getParent().datarecord.id || false])
                           .then(process_data);

        function process_data(data) {
            return _.map(data, function (d) {
                return _.object(['id', 'display_name', 'status', 'color'], d);
            });
        }
    },
});

core.form_widget_registry.add('many2manyattendee', Many2ManyAttendee);


});
Ejemplo n.º 4
0
ecore.define('base_calendar.base_calendar', function (require) {
"use strict";

var core = require('web.core');
var CalendarView = require('web_calendar.CalendarView');
var data = require('web.data');
var Dialog = require('web.Dialog');
var form_common = require('web.form_common');
var Model = require('web.DataModel');
var Notification = require('web.notification').Notification;
var session = require('web.session');
var WebClient = require('web.WebClient');
var widgets = require('web_calendar.widgets');

var FieldMany2ManyTags = core.form_widget_registry.get('many2many_tags');
var _t = core._t;
var _lt = core._lt;
var QWeb = core.qweb;

function reload_favorite_list(result) {
    var self = result;
    var current = result;
    if (result.view) {
        self = result.view;
    }
    return new Model("res.users")
    .query(["partner_id"])
    .filter([["id", "=", self.dataset.context.uid]])
    .first()
    .done(function(result) {
        var sidebar_items = {};
        var filter_value = result.partner_id[0];
        var filter_item = {
            value: filter_value,
            label: result.partner_id[1] + _lt(" [Me]"),
            color: self.get_color(filter_value),
            avatar_model: self.avatar_model,
            is_checked: true,
            is_remove: false,
        };
        sidebar_items[filter_value] = filter_item ;
        
        filter_item = {
                value: -1,
                label: _lt("Everybody's calendars"),
                color: self.get_color(-1),
                avatar_model: self.avatar_model,
                is_checked: false
            };
        sidebar_items[-1] = filter_item ;
        //Get my coworkers/contacts
        new Model("calendar.contacts").query(["partner_id"]).filter([["user_id", "=",self.dataset.context.uid]]).all().then(function(result) {
            _.each(result, function(item) {
                filter_value = item.partner_id[0];
                filter_item = {
                    value: filter_value,
                    label: item.partner_id[1],
                    color: self.get_color(filter_value),
                    avatar_model: self.avatar_model,
                    is_checked: true
                };
                sidebar_items[filter_value] = filter_item ;
            });
            self.all_filters = sidebar_items;
            self.now_filter_ids = $.map(self.all_filters, function(o) { return o.value; });
            
            self.sidebar.filter.events_loaded(self.all_filters);
            self.sidebar.filter.set_filters();
            self.sidebar.filter.add_favorite_calendar();
            self.sidebar.filter.destroy_filter();
        }).done(function () {
            self.$calendar.fullCalendar('refetchEvents');
            if (current.ir_model_m2o) {
                current.ir_model_m2o.set_value(false);
            }
        });
    });
}

CalendarView.include({
    extraSideBar: function() {
        var result = this._super();
        if (this.useContacts) {
            return result.then(reload_favorite_list(this));
        }
        return result;
    }
});

widgets.SidebarFilter.include({
    events_loaded: function() {
        this._super.apply(this, arguments);
        this.reinitialize_m2o();
    },
    add_favorite_calendar: function() {
        if (this.dfm)
            return;
        this.initialize_m2o();
    },
    reinitialize_m2o: function() {
        if (this.dfm) {
            this.dfm.destroy();
            this.dfm = undefined;
        }
        this.initialize_m2o();
    },
    initialize_m2o: function() {
        var self = this;
        this.dfm = new form_common.DefaultFieldManager(self);
        this.dfm.extend_field_desc({
            partner_id: {
                relation: "res.partner",
            },
        });
        var FieldMany2One = core.form_widget_registry.get('many2one');
        this.ir_model_m2o = new FieldMany2One(self.dfm, {
            attrs: {
                class: 'o_add_favorite_calendar',
                name: "partner_id",
                type: "many2one",
                options: '{"no_open": True}',
                placeholder: _t("Add Favorite Calendar"),
            },
        });
        this.ir_model_m2o.appendTo(this.$el);
        this.ir_model_m2o.on('change:value', self, function() { 
            self.add_filter();
        });
    },
    add_filter: function() {
        var self = this;
        var defs = [];
        defs.push(new Model("res.users")
        .query(["partner_id"])
        .filter([["id", "=",this.view.dataset.context.uid]])
        .first()
        .done(function(result){
            $.map(self.ir_model_m2o.display_value, function(element,index) {
                if (result.partner_id[0] != index){
                    self.ds_message = new data.DataSetSearch(self, 'calendar.contacts');
                    defs.push(self.ds_message.call("create", [{'partner_id': index}]));
                }
            });
        }));
        return $.when.apply(null, defs).then(function() {
            return reload_favorite_list(self);
        });
    },
    destroy_filter: function(e) {
        var self = this;
        this.$(".oe_remove_follower").on('click', function(e) {
            self.ds_message = new data.DataSetSearch(self, 'calendar.contacts');
            var id = $(e.currentTarget)[0].dataset.id;

            Dialog.confirm(self, _t("Do you really want to delete this filter from favorite?"), {
                confirm_callback: function() {
                    self.ds_message.call('search', [[['partner_id', '=', parseInt(id)]]]).then(function(record) {
                        return self.ds_message.unlink(record);
                    }).done(function() {
                        reload_favorite_list(self);
                    });
                },
            });
        });
    },
});

var CalendarNotification = Notification.extend({
    template: "CalendarNotification",

    init: function(parent, title, text, eid) {
        this._super(parent, title, text, true);
        this.eid = eid;

        this.events = _.extend(this.events || {}, {
            'click .link2event': function() {
                var self = this;

                this.rpc("/web/action/load", {
                    action_id: "calendar.action_calendar_event_notify",
                }).then(function(r) {
                    r.res_id = self.eid;
                    return self.do_action(r);
                });
            },

            'click .link2recall': function() {
                this.destroy(true);
            },

            'click .link2showed': function() {
                this.destroy(true);
                this.rpc("/calendar/notify_ack");
            },
        });
    },
});

WebClient.include({
    get_next_notif: function() {
        var self = this;

        this.rpc("/calendar/notify")
        .done(function(result) {
            _.each(result, function(res) {
                setTimeout(function() {
                    // If notification not already displayed, we create and display it (FIXME is this check usefull?)
                    if(self.$(".eid_" + res.event_id).length === 0) {
                        self.notification_manager.display(new CalendarNotification(self.notification_manager, res.title, res.message, res.event_id));
                    }
                }, res.timer * 1000);
            });
        })
        .fail(function(err, ev) {
            if(err.code === -32098) {
                // Prevent the CrashManager to display an error
                // in case of an xhr error not due to a server error
                ev.preventDefault();
            }
        });
    },
    check_notifications: function() {
        var self = this;
        this.get_next_notif();
        this.intervalNotif = setInterval(function() {
            self.get_next_notif();
        }, 5 * 60 * 1000);
    },
    //Override the show_application of addons/web/static/src/js/chrome.js       
    show_application: function() {
        this._super();
        this.check_notifications();
    },
    //Override addons/web/static/src/js/chrome.js       
    on_logout: function() {
        this._super();
        clearInterval(this.intervalNotif);
    },
});

var Many2ManyAttendee = FieldMany2ManyTags.extend({
    tag_template: "Many2ManyAttendeeTag",
    get_render_data: function(ids){
        var dataset = new data.DataSetStatic(this, this.field.relation, this.build_context());
        return dataset.call('get_attendee_detail',[ids, this.getParent().datarecord.id || false])
                      .then(process_data);

        function process_data(data) {
            return _.map(data, function(d) {
                return _.object(['id', 'name', 'status'], d);
            });
        }
    }
});

function showCalendarInvitation(db, action, id, view, attendee_data) {
    session.session_bind(session.origin).then(function () {
        if (session.session_is_valid(db) && session.username !== "anonymous") {
            window.location.href = _.str.sprintf('/web?db=%s#id=%s&view_type=form&model=calendar.event', db, id);
        } else {
            $("body").prepend(QWeb.render('CalendarInvitation', {attendee_data: JSON.parse(attendee_data)}));
        }
    });
}

core.form_widget_registry.add('many2manyattendee', Many2ManyAttendee);

return {
    showCalendarInvitation: showCalendarInvitation,
};

});
Ejemplo n.º 5
0
odoo.define('staff_management.StaffCalendar', function (require) {
"use strict";

var core = require('web.core');
var time = require('web.time');
var CalendarView = require('web_calendar.CalendarView');

var _t = core._t;
var QWeb = core.qweb;

// TODO - Check differences between old get_fc_defaultOptions & new
/*
function get_fc_defaultOptions() {
	shortTimeformat = Date.CultureInfo.formatPatterns.shortTime;
	return {
		weekNumberTitle: _t("W"),
		allDayText: _t("All day"),
		buttonText : {
			today:	_t("Today"),
			month:	_t("Month"),
			week:	_t("Week"),
			day:	_t("Day")
		},
		monthNames: Date.CultureInfo.monthNames,
		monthNamesShort: Date.CultureInfo.abbreviatedMonthNames,
		dayNames: Date.CultureInfo.dayNames,
		dayNamesShort: Date.CultureInfo.abbreviatedDayNames,
		firstDay: Date.CultureInfo.firstDayOfWeek,
		weekNumbers: false,
		axisFormat : shortTimeformat.replace(/:mm/,'(:mm)'),
		timeFormat : {
			// for agendaWeek and agendaDay
			agenda: shortTimeformat + '{ - ' + shortTimeformat + '}', // 5:00 - 6:30
			// for all other views
			'': shortTimeformat.replace(/:mm/,'(:mm)')  // 7pm
		},
		weekMode : 'liquid',
		aspectRatio: 1.8,
		snapMinutes: 15,
	};
}
*/

function get_fc_defaultOptions() {
    var dateFormat = time.strftime_to_moment_format(_t.database.parameters.date_format);

    // adapt format for fullcalendar v1.
    // see http://fullcalendar.io/docs1/utilities/formatDate/
    var conversions = [['YYYY', 'yyyy'], ['YY', 'y'], ['DDDD', 'dddd'], ['DD', 'dd']];
    _.each(conversions, function(conv) {
        dateFormat = dateFormat.replace(conv[0], conv[1]);
    });

    return {
        weekNumberTitle: _t("W"),
        allDayText: _t("All day"),
        buttonText : {
			today:	_t("Today"),
			month:	_t("Month"),
			week:	_t("Week"),
			day:	_t("Day")
		},
        monthNames: moment.months(),
        monthNamesShort: moment.monthsShort(),
        dayNames: moment.weekdays(),
        dayNamesShort: moment.weekdaysShort(),
        firstDay: moment._locale._week.dow,
        weekNumbers: true,
        titleFormat: {
            month: 'MMMM yyyy',
            week: "W",
            day: dateFormat,
        },
        columnFormat: {
            month: 'ddd',
            week: 'ddd ' + dateFormat,
            day: 'dddd ' + dateFormat,
        },
        weekMode : 'liquid',
        snapMinutes: 15,
    };
}


var StaffCalendar = CalendarView.extend({

	color_palette: [
		'#804040',
		'#008080',
		'#004080',
		'#8080FF',
		'#800040',
		'#FF0080',
		'#804000',
		'#FF8000',
		'#008000',
		'#008040',
		'#0000FF',
		'#000040',
		'#800080',
		'#8000FF',
		'#400040',
		'#808000',
		'#004040',
		'#800000'
	],

	init:function(){
		this._super.apply(this,arguments);
	},

	// No slidebar
	init_calendar: function() {
		var self = this;

		self.$calendar.fullCalendar(self.get_fc_init_options());

		//$('.fc-button-next').empty().text('Mois').append($('<span>').addClass('fc-text-arrow').text('»'));
		//$('.fc-button-prev').empty().append($('<span>').addClass('fc-text-arrow').text('«')).append('Mois');

		return $.when();
	},

	/**
     * Render the buttons according to the CalendarView.buttons template and
     * add listeners on it.
     * Set this.$buttons with the produced jQuery element
     * @param {jQuery} [$node] a jQuery node where the rendered buttons should be inserted
     * $node may be undefined, in which case the ListView inserts them into this.options.$buttons
     * or into a div of its template
     */
    render_buttons: function($node) {
    	// TODO - use new buttons
    	/*
        var self = this;
        this.$buttons = $(QWeb.render("PersonalScheduleView.buttons", {'widget': this}));
        this.$buttons.on('click', 'button.o_calendar_button_new', function () {
            self.dataset.index = null;
            self.do_switch_view('form');
        });

        var bindCalendarButton = function(selector, arg1, arg2) {
            self.$buttons.on('click', selector, _.bind(self.$calendar.fullCalendar, self.$calendar, arg1, arg2));
        }
        bindCalendarButton('.o_calendar_button_prev', 'prev');
        bindCalendarButton('.o_calendar_button_today', 'today');
        bindCalendarButton('.o_calendar_button_next', 'next');

        this.$buttons.find('.o_calendar_button_' + this.mode).addClass('active');
        $node = $node || this.options.$buttons;
        if ($node) {
            this.$buttons.appendTo($node);
        } else {
            this.$('.o_calendar_buttons').replaceWith(this.$buttons);
        }
        */
    },

	// Format number for hour
	FormatNumberLength: function(num, length) {
		var r = "" + num;
		while (r.length < length) {
			r = "0" + r;
		}
		return r;
	},

	// convert hour from 9.5 to 09:30
	format_hour: function(hour){
		hour = parseFloat(hour);
		if(hour == undefined || isNaN(hour)){
			return '00:00';
		}
		var h = Math.floor(hour);
		var m = Math.round((hour-h) * 60);
		return this.FormatNumberLength(h, 2)+':'+this.FormatNumberLength(m, 2);
	},

	format_hour_duration: function(hour_start, hour_end){
		hour_start = parseFloat(hour_start);
		hour_end = parseFloat(hour_end);
		if(isNaN(hour_start)){
			hour_start = 0;
		}
		if(isNaN(hour_end)){
			hour_end = 0;
		}
		return this.convert_hour(hour_end-hour_start);
	},

	get_fc_init_options: function () {
		//Documentation here : http://arshaw.com/fullcalendar/docs/
		var self = this;
		return  $.extend({}, get_fc_defaultOptions(), {

			defaultView: "month",
			header: {
				left: 'prev,today,next',
				center: 'title',
				right: '' // 'month' Nothing, only one view
			},
			selectable: !this.options.read_only_mode && this.create_right,
			selectHelper: true,
			editable: !this.options.read_only_mode,
			droppable: false,
			disableDragging: true,

			// callbacks
			viewRender: function(view) {
                var mode = (view.name == "month")? "month" : ((view.name == "agendaWeek") ? "week" : "day");
                if(self.$buttons !== undefined) {
                    self.$buttons.find('.active').removeClass('active');
                    self.$buttons.find('.o_calendar_button_' + mode).addClass('active');
                }

                var title = self.title + ' (' + ((mode === "week")? _t("Week ") : "") + view.title + ")";
                //self.set({'title': title});

                self.$calendar.fullCalendar('option', 'height', Math.max(290, parseInt(self.$('.o_calendar_view').height())));

                setTimeout(function() {
                    var $fc_view = self.$calendar.find('.fc-view');
                    var width = $fc_view.find('> table').width();
                    $fc_view.find('> div').css('width', (width > $fc_view.width())? width : '100%'); // 100% = fullCalendar default
                }, 0);
            },
			eventDrop: function (event, _day_delta, _minute_delta, _all_day, _revertFunc) {
				var data = self.get_event_data(event);
				self.proxy('update_record')(event._id, data); // we don't revert the event, but update it.
			},
			eventResize: function (event, _day_delta, _minute_delta, _revertFunc) {
				var data = self.get_event_data(event);
				self.proxy('update_record')(event._id, data);
			},
			eventRender: function (event, element, view) {
				element.find('.fc-event-title').html(event.title);
			},
			eventAfterRender: function (event, element, view) {
				if ((view.name !== 'month') && (((event.end-event.start)/60000)<=30)) {
					//if duration is too small, we see the html code of img
					var current_title = $(element.find('.fc-event-time')).text();
					var new_title = current_title.substr(0,current_title.indexOf("<img")>0?current_title.indexOf("<img"):current_title.length);
					element.find('.fc-event-time').html(new_title);
				}
			},
			eventClick: function (event) { self.open_event(event._id,event.title); },
			select: function (start_date, end_date, all_day, _js_event, _view) {
				var data_template = self.get_event_data({
					start: start_date,
					end: end_date,
					allDay: all_day,
				});
				self.open_quick_create(data_template);

			},

			unselectAuto: false,
			height: $('.oe_view_manager_body').height() - 5,
			handleWindowResize: true,
			windowResize: function() {
                self.$calendar.fullCalendar('render');
            }/*,
			windowResize: function(view) {
				self.$calendar.fullCalendar('option', 'height', $('.oe_view_manager_body').height() - 5);
			}*/

		});
	},

	zeroPad: function(num, places) {
		var zero = places - num.toString().length + 1;
		return Array(+(zero > 0 && zero)).join("0") + num;
	}
});


return StaffCalendar;
});