diff --git a/addons/web_analytics/static/src/js/web_analytics.js b/addons/web_analytics/static/src/js/web_analytics.js index c8212f4d213..a81275d1b74 100644 --- a/addons/web_analytics/static/src/js/web_analytics.js +++ b/addons/web_analytics/static/src/js/web_analytics.js @@ -1,290 +1,296 @@ var _gaq = _gaq || []; // asynchronous stack used by google analytics -openerp.web_analytics = function(instance) { +odoo.define('web_analytics.web_analytics', ['web.ActionManager', 'web.core', 'web.CrashManager', 'web.FormView', 'web.Session', 'web.session', 'web.View', 'web.web_client', 'web.WebClient'], function (require) { +"use strict"; + +var ActionManager = require('web.ActionManager'); +var CrashManager = require('web.CrashManager'); +var core = require('web.core'); +var FormView = require('web.FormView'); +var Session = require('web.Session'); +var session = require('web.session'); +var View = require('web.View'); +var web_client = require('web.web_client'); +var WebClient = require('web.WebClient'); + +/* +* The Web Analytics Module inserts the Google Analytics JS Snippet +* at the top of the page, and sends to google an url each time the +* openerp url is changed. +* The pushes of the urls is made by triggering the 'state_pushed' event in the +* web_client.do_push_state() method which is responsible of changing the openerp current url +*/ + +// Google Analytics Code snippet +(function() { + var ga = document.createElement('script'); + ga.type = 'text/javascript'; + ga.async = true; + ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; + var s = document.getElementsByTagName('script')[0]; + s.parentNode.insertBefore(ga,s); +})(); + +var Tracker = core.Class.extend({ + /* + * This method initializes the tracker + */ + init: function(webclient) { + var self = this; + self.initialized = $.Deferred(); + _gaq.push(['_setAccount', 'UA-7333765-1']); + _gaq.push(['_setDomainName', '.openerp.com']); // Allow multi-domain + self.initialize_custom(webclient).then(function() { + webclient.on('state_pushed', self, self.on_state_pushed); + self.include_tracker(); + }); + }, + /* + * This method MUST be overriden by saas_demo and saas_trial in order to + * set the correct user type. By default, the user connected is local to + * the DB (like in accounts). + */ + _get_user_type: function() { + return 'Local User'; + }, + /* + * This method gets the user access level, to be used as CV in GA + */ + _get_user_access_level: function() { + if (!session.session_is_valid()) { + return "Unauthenticated User"; + } + if (session.uid === 1) { + return 'Admin User'; + } + // Make the difference between portal users and anonymous users + if (session.username.indexOf('@') !== -1) { + return 'Portal User'; + } + if (session.username === 'anonymous') { + return 'Anonymous User'; + } + return 'Normal User'; + }, + + /* + * This method contains the initialization of all user-related custom variables + * stored in GA. Also other modules can override it to add new custom variables + * Must be followed by a call to _push_*() in order to actually send the data + * to GA. + */ + initialize_custom: function() { + var self = this; + session.rpc("/web/webclient/version_info", {}) + .done(function(res) { + _gaq.push(['_setCustomVar', 5, 'Version', res.server_version, 3]); + self._push_customvars(); + self.initialized.resolve(self); + }); + return self.initialized; + }, /* - * The Web Analytics Module inserts the Google Analytics JS Snippet - * at the top of the page, and sends to google an url each time the - * openerp url is changed. - * The pushes of the urls is made by triggering the 'state_pushed' event in the - * web_client.do_push_state() method which is responsible of changing the openerp current url + * Method called in order to send _setCustomVar to GA + */ + _push_customvars: function() { + var self = this; + // Track User Access Level, Custom Variable 4 in GA with visitor level scope + // Values: 'Admin User', 'Normal User', 'Portal User', 'Anonymous User' + _gaq.push(['_setCustomVar', 4, 'User Access Level', self._get_user_access_level(), 1]); + + // Track User Type Conversion, Custom Variable 3 in GA with session level scope + // Values: 'Visitor', 'Demo', 'Online Trial', 'Online Paying', 'Local User' + _gaq.push(['_setCustomVar', 1, 'User Type Conversion', self._get_user_type(), 2]); + }, + + /* + * Method called in order to send _trackPageview to GA */ - - // Google Analytics Code snippet - (function() { - var ga = document.createElement('script'); - ga.type = 'text/javascript'; - ga.async = true; - ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; - var s = document.getElementsByTagName('script')[0]; - s.parentNode.insertBefore(ga,s); - })(); - - instance.web_analytics.Tracker = instance.web.Class.extend({ - /* - * This method initializes the tracker - */ - init: function(webclient) { - var self = this; - self.initialized = $.Deferred(); - _gaq.push(['_setAccount', 'UA-7333765-1']); - _gaq.push(['_setDomainName', '.openerp.com']); // Allow multi-domain - self.initialize_custom(webclient).then(function() { - webclient.on('state_pushed', self, self.on_state_pushed); - self.include_tracker(); + _push_pageview: function(url) { + _gaq.push(['_trackPageview', url]); + }, + /* + * Method called in order to send _trackEvent to GA + */ + _push_event: function(options) { + _gaq.push(['_trackEvent', + options.category, + options.action, + options.label, + options.value, + options.noninteraction + ]); + }, + /* + * Method called in order to send ecommerce transactions to GA + */ + _push_ecommerce: function(trans_data, item_list) { + _gaq.push(['_addTrans', + trans_data.order_id, + trans_data.store_name, + trans_data.total, + trans_data.tax, + trans_data.shipping, + trans_data.city, + trans_data.state, + trans_data.country, + ]); + _.each(item_list, function(item) { + _gaq.push(['_addItem', + item.order_id, + item.sku, + item.name, + item.category, + item.price, + item.quantity, + ]); + }); + _gaq.push(['_trackTrans']); + }, + /* + * This method contains the initialization of the object and view type + * as an event in GA. + */ + on_state_pushed: function(state) { + // Track only pages corresponding to a 'normal' view of OpenERP, views + // related to client actions are tracked by the action manager + if (state.model && state.view_type) { + // Track the page + var url = generateUrl({'model': state.model, 'view_type': state.view_type}); + this._push_event({ + 'category': state.model, + 'action': state.view_type, + 'label': url, }); - }, - /* - * This method MUST be overriden by saas_demo and saas_trial in order to - * set the correct user type. By default, the user connected is local to - * the DB (like in accounts). - */ - _get_user_type: function() { - return 'Local User'; - }, - /* - * This method gets the user access level, to be used as CV in GA - */ - _get_user_access_level: function() { - if (!instance.session.session_is_valid()) { - return "Unauthenticated User"; - } - if (instance.session.uid === 1) { - return 'Admin User'; - } - // Make the difference between portal users and anonymous users - if (instance.session.username.indexOf('@') !== -1) { - return 'Portal User'; - } - if (instance.session.username === 'anonymous') { - return 'Anonymous User'; - } - return 'Normal User'; - }, - - /* - * This method contains the initialization of all user-related custom variables - * stored in GA. Also other modules can override it to add new custom variables - * Must be followed by a call to _push_*() in order to actually send the data - * to GA. - */ - initialize_custom: function() { - var self = this; - instance.session.rpc("/web/webclient/version_info", {}) - .done(function(res) { - _gaq.push(['_setCustomVar', 5, 'Version', res.server_version, 3]); - self._push_customvars(); - self.initialized.resolve(self); + this._push_pageview(url); + } + }, + /* + * This method includes the tracker into views and managers. It can be overriden + * by other modules in order to extend tracking functionalities + */ + include_tracker: function() { + var t = this; + // Track the events related with the creation and the modification of records, + // the view type is always form + FormView.include({ + init: function(parent, dataset, view_id, options) { + this._super.apply(this, arguments); + var self = this; + this.on('record_created', self, function(r) { + var url = generateUrl({'model': self.model, 'view_type': 'form'}); + t._push_event({ + 'category': self.model, + 'action': 'create', + 'label': url, + 'noninteraction': true, + }); }); - return self.initialized; - }, + this.on('record_saved', self, function(r) { + var url = generateUrl({'model': self.model, 'view_type': 'form'}); + t._push_event({ + 'category': self.model, + 'action': 'save', + 'label': url, + 'noninteraction': true, + }); + }); + } + }); - /* - * Method called in order to send _setCustomVar to GA - */ - _push_customvars: function() { - var self = this; - // Track User Access Level, Custom Variable 4 in GA with visitor level scope - // Values: 'Admin User', 'Normal User', 'Portal User', 'Anonymous User' - _gaq.push(['_setCustomVar', 4, 'User Access Level', self._get_user_access_level(), 1]); - - // Track User Type Conversion, Custom Variable 3 in GA with session level scope - // Values: 'Visitor', 'Demo', 'Online Trial', 'Online Paying', 'Local User' - _gaq.push(['_setCustomVar', 1, 'User Type Conversion', self._get_user_type(), 2]); - }, - - /* - * Method called in order to send _trackPageview to GA - */ - _push_pageview: function(url) { - _gaq.push(['_trackPageview', url]); - }, - /* - * Method called in order to send _trackEvent to GA - */ - _push_event: function(options) { - _gaq.push(['_trackEvent', - options.category, - options.action, - options.label, - options.value, - options.noninteraction - ]); - }, - /* - * Method called in order to send ecommerce transactions to GA - */ - _push_ecommerce: function(trans_data, item_list) { - _gaq.push(['_addTrans', - trans_data.order_id, - trans_data.store_name, - trans_data.total, - trans_data.tax, - trans_data.shipping, - trans_data.city, - trans_data.state, - trans_data.country, - ]); - _.each(item_list, function(item) { - _gaq.push(['_addItem', - item.order_id, - item.sku, - item.name, - item.category, - item.price, - item.quantity, - ]); - }); - _gaq.push(['_trackTrans']); - }, - /* - * This method contains the initialization of the object and view type - * as an event in GA. - */ - on_state_pushed: function(state) { - // Track only pages corresponding to a 'normal' view of OpenERP, views - // related to client actions are tracked by the action manager - if (state.model && state.view_type) { - // Track the page - var url = instance.web_analytics.generateUrl({'model': state.model, 'view_type': state.view_type}); - this._push_event({ - 'category': state.model, - 'action': state.view_type, + // Track client actions + ActionManager.include({ + ir_actions_client: function (action, options) { + var url = generateUrl({'action': action.tag}); + t._push_event({ + 'category': action.type, + 'action': action.tag, 'label': url, }); - this._push_pageview(url); - } - }, - /* - * This method includes the tracker into views and managers. It can be overriden - * by other modules in order to extend tracking functionalities - */ - include_tracker: function() { - var t = this; - // Track the events related with the creation and the modification of records, - // the view type is always form - instance.web.FormView.include({ - init: function(parent, dataset, view_id, options) { - this._super.apply(this, arguments); - var self = this; - this.on('record_created', self, function(r) { - var url = instance.web_analytics.generateUrl({'model': self.model, 'view_type': 'form'}); - t._push_event({ - 'category': self.model, - 'action': 'create', - 'label': url, - 'noninteraction': true, - }); - }); - this.on('record_saved', self, function(r) { - var url = instance.web_analytics.generateUrl({'model': self.model, 'view_type': 'form'}); - t._push_event({ - 'category': self.model, - 'action': 'save', - 'label': url, - 'noninteraction': true, - }); - }); - } - }); - - // Track client actions - instance.web.ActionManager.include({ - ir_actions_client: function (action, options) { - var url = instance.web_analytics.generateUrl({'action': action.tag}); - t._push_event({ - 'category': action.type, - 'action': action.tag, - 'label': url, - }); - t._push_pageview(url); - return this._super.apply(this, arguments); - }, - }); - - // Track button events - instance.web.View.include({ - do_execute_action: function(action_data, dataset, record_id, on_closed) { - var category = this.model || dataset.model || ''; - var action; - if (action_data.name && _.isNaN(action_data.name-0)) { - action = action_data.name; - } else { - action = action_data.string || action_data.special || ''; - } - var url = instance.web_analytics.generateUrl({'model': category, 'view_type': this.view_type}); - t._push_event({ - 'category': category, - 'action': action, - 'label': url, - 'noninteraction': true, - }); - return this._super.apply(this, arguments); - }, - }); - - // Track error events - instance.web.CrashManager.include({ - show_error: function(error) { - var hash = window.location.hash; - var params = $.deparam(hash.substr(hash.indexOf('#')+1)); - var options = {}; - if (params.model && params.view_type) { - options = {'model': params.model, 'view_type': params.view_type}; - } else { - options = {'action': params.action}; - } - var url = instance.web_analytics.generateUrl(options); - t._push_event({ - 'category': options.model || "ir.actions.client", - 'action': "error " + (error.code ? error.message + error.data.message : error.type + error.data.debug), - 'label': url, - 'noninteraction': true, - }); - this._super.apply(this, arguments); - }, - }); - }, - }); - - // ---------------------------------------------------------------- - // utility functions - // ---------------------------------------------------------------- - - instance.web_analytics.generateUrl = function(options) { - var url = ''; - var keys = _.keys(options); - keys = _.sortBy(keys, function(i) { return i;}); - _.each(keys, function(key) { - url += '/' + key + '/' + options[key]; + t._push_pageview(url); + return this._super.apply(this, arguments); + }, }); - return url; - }; - // kept for API compatibility - instance.web_analytics.setupTracker = function(wc) { - return wc.tracker.initialized; - }; - - instance.web.Client.include({ - bind_events: function() { - this._super.apply(this, arguments); - this.tracker = new instance.web_analytics.Tracker(this); - }, - }); - - instance.web.Session.include({ - session_authenticate: function() { - return $.when(this._super.apply(this, arguments)).then(function() { - // the call to bind_events() may have been delayed in some embed - // cases, and when that happens we can skip the push, as the - // proper one will be done when bind_event is eventually called. - if (instance.client && instance.client.tracker) { - instance.client.tracker._push_customvars(); + // Track button events + View.include({ + do_execute_action: function(action_data, dataset, record_id, on_closed) { + var category = this.model || dataset.model || ''; + var action; + if (action_data.name && _.isNaN(action_data.name-0)) { + action = action_data.name; + } else { + action = action_data.string || action_data.special || ''; } - }); - }, + var url = generateUrl({'model': category, 'view_type': this.view_type}); + t._push_event({ + 'category': category, + 'action': action, + 'label': url, + 'noninteraction': true, + }); + return this._super.apply(this, arguments); + }, + }); + + // Track error events + CrashManager.include({ + show_error: function(error) { + var hash = window.location.hash; + var params = $.deparam(hash.substr(hash.indexOf('#')+1)); + var options = {}; + if (params.model && params.view_type) { + options = {'model': params.model, 'view_type': params.view_type}; + } else { + options = {'action': params.action}; + } + var url = generateUrl(options); + t._push_event({ + 'category': options.model || "ir.actions.client", + 'action': "error " + (error.code ? error.message + error.data.message : error.type + error.data.debug), + 'label': url, + 'noninteraction': true, + }); + this._super.apply(this, arguments); + }, + }); + }, +}); + +// ---------------------------------------------------------------- +// utility functions +// ---------------------------------------------------------------- + +var generateUrl = function(options) { + var url = ''; + var keys = _.keys(options); + keys = _.sortBy(keys, function(i) { return i;}); + _.each(keys, function(key) { + url += '/' + key + '/' + options[key]; }); - + return url; }; + +// kept for API compatibility +var setupTracker = function(wc) { + return wc.tracker.initialized; +}; + +WebClient.include({ + bind_events: function() { + this._super.apply(this, arguments); + this.tracker = new Tracker(this); + }, +}); + +Session.include({ + session_authenticate: function() { + return $.when(this._super.apply(this, arguments)).then(function() { + web_client.tracker._push_customvars(); + }); + }, +}); + +}); diff --git a/addons/web_diagram/static/src/js/diagram.js b/addons/web_diagram/static/src/js/diagram.js index 3ed3b450a57..4e543a2a0b2 100644 --- a/addons/web_diagram/static/src/js/diagram.js +++ b/addons/web_diagram/static/src/js/diagram.js @@ -1,13 +1,19 @@ +odoo.define('web_diagram.DiagramView', ['web.core', 'web.data', 'web.form_common', 'web.View'], function (require) { /*--------------------------------------------------------- * OpenERP diagram library *---------------------------------------------------------*/ +"use strict"; -openerp.web_diagram = function (instance) { -var QWeb = instance.web.qweb, - _t = instance.web._t, - _lt = instance.web._lt; -instance.web.views.add('diagram', 'instance.web.DiagramView'); -instance.web.DiagramView = instance.web.View.extend({ +var core = require('web.core'); +var data = require('web.data'); +var form_common = require('web.form_common'); +var View = require('web.View'); + +var _t = core._t; +var _lt = core._lt; +var QWeb = core.qweb; + +var DiagramView = View.extend({ display_name: _lt('Diagram'), view_type: 'diagram', searchable: false, @@ -54,9 +60,9 @@ instance.web.DiagramView = instance.web.View.extend({ this.$el.addClass(this.fields_view.arch.attrs['class']); _.each(self.labels,function(label){ - html_label = '
' + label.attrs.string + "
"; + var html_label = '' + label.attrs.string + "
"; self.$el.find('.oe_diagram_header').append(html_label); - }) + }); this.init_pager(); @@ -90,16 +96,16 @@ instance.web.DiagramView = instance.web.View.extend({ _.each(this.nodes.children, function(child) { if(child.attrs.invisible == '1') - params['invisible_nodes'].push(child.attrs.name); + params.invisible_nodes.push(child.attrs.name); else { - params['visible_nodes'].push(child.attrs.name); - params['node_fields'].push(self.fields[child.attrs.name]['string']|| this.toTitleCase(child.attrs.name)); + params.visible_nodes.push(child.attrs.name); + params.node_fields.push(self.fields[child.attrs.name]['string']|| this.toTitleCase(child.attrs.name)); } }); _.each(this.connectors.children, function(conn) { - params['connectors_fields'].push(self.fields[conn.attrs.name]['string']|| this.toTitleCase(conn.attrs.name)); - params['connectors'].push(conn.attrs.name); + params.connectors_fields.push(self.fields[conn.attrs.name]['string']|| this.toTitleCase(conn.attrs.name)); + params.connectors.push(conn.attrs.name); }); this.rpc( '/web_diagram/diagram/get_diagram_info',params).done(function(result) { @@ -209,7 +215,7 @@ instance.web.DiagramView = instance.web.View.extend({ if(!confirm(_t("Deleting this node cannot be undone.\nIt will also delete all connected transitions.\n\nAre you sure ?"))){ return $.Deferred().reject().promise(); } - return new instance.web.DataSet(self,self.node).unlink([cutenode.id]); + return new data.DataSet(self,self.node).unlink([cutenode.id]); }; CuteEdge.double_click_callback = function(cuteedge){ self.edit_connector(cuteedge.id); @@ -227,7 +233,7 @@ instance.web.DiagramView = instance.web.View.extend({ if(!confirm(_t("Deleting this transition cannot be undone.\n\nAre you sure ?"))){ return $.Deferred().reject().promise(); } - return new instance.web.DataSet(self,self.connector).unlink([cuteedge.id]); + return new data.DataSet(self,self.connector).unlink([cuteedge.id]); }; }, @@ -236,7 +242,7 @@ instance.web.DiagramView = instance.web.View.extend({ edit_node: function(node_id){ var self = this; var title = _t('Activity'); - var pop = new instance.web.form.FormOpenPopup(self); + var pop = new form_common.FormOpenPopup(self); pop.show_element( self.node, @@ -270,7 +276,7 @@ instance.web.DiagramView = instance.web.View.extend({ add_node: function(){ var self = this; var title = _t('Activity'); - var pop = new instance.web.form.SelectCreatePopup(self); + var pop = new form_common.SelectCreatePopup(self); pop.select_element( self.node, { @@ -302,7 +308,7 @@ instance.web.DiagramView = instance.web.View.extend({ edit_connector: function(connector_id){ var self = this; var title = _t('Transition'); - var pop = new instance.web.form.FormOpenPopup(self); + var pop = new form_common.FormOpenPopup(self); pop.show_element( self.connector, parseInt(connector_id,10), //FIXME Isn't connector_id supposed to be an int ? @@ -321,7 +327,7 @@ instance.web.DiagramView = instance.web.View.extend({ add_connector: function(node_source_id, node_dest_id, dummy_cuteedge){ var self = this; var title = _t('Transition'); - var pop = new instance.web.form.SelectCreatePopup(self); + var pop = new form_common.SelectCreatePopup(self); pop.select_element( self.connector, @@ -420,4 +426,9 @@ instance.web.DiagramView = instance.web.View.extend({ return $.when(this._super(), this.execute_pager_action('reload')); } }); -}; + +core.view_registry.add('diagram', DiagramView); + +return DiagramView; + +}); diff --git a/addons/web_gantt/static/src/js/gantt.js b/addons/web_gantt/static/src/js/gantt.js index 47692571f4c..ce9bce91258 100644 --- a/addons/web_gantt/static/src/js/gantt.js +++ b/addons/web_gantt/static/src/js/gantt.js @@ -1,18 +1,25 @@ +odoo.define('web_gantt.GanttView', ['web.core', 'web.form_common', 'web.formats', 'web.Model', 'web.time', 'web.View'], function (require) { +"use strict"; /*--------------------------------------------------------- - * OpenERP web_gantt + * Odoo web_gantt *---------------------------------------------------------*/ -openerp.web_gantt = function (instance) { -var _t = instance.web._t, - _lt = instance.web._lt; -var QWeb = instance.web.qweb; -instance.web.views.add('gantt', 'instance.web_gantt.GanttView'); -instance.web_gantt.GanttView = instance.web.View.extend({ +var core = require('web.core'); +var form_common = require('web.form_common'); +var formats = require('web.formats'); +var Model = require('web.Model'); +var time = require('web.time'); +var View = require('web.View'); + +var _lt = core._lt; +var QWeb = core.qweb; + + +var GanttView = View.extend({ display_name: _lt('Gantt'), template: "GanttView", view_type: "gantt", init: function() { - var self = this; this._super.apply(this, arguments); this.has_been_loaded = $.Deferred(); this.chart_id = _.uniqueId(); @@ -24,7 +31,7 @@ instance.web_gantt.GanttView = instance.web.View.extend({ var self = this; this.fields_view = fields_view_get; this.$el.addClass(this.fields_view.arch.attrs['class']); - return self.alive(new instance.web.Model(this.dataset.model) + return self.alive(new Model(this.dataset.model) .call('fields_get')).then(function (fields) { self.fields = fields; self.has_been_loaded.resolve(); @@ -81,7 +88,7 @@ instance.web_gantt.GanttView = instance.web.View.extend({ group_bys = [group_bys[0]]; } // if there is no group by, simulate it - if (group_bys.length == 0) { + if (group_bys.length === 0) { group_bys = ["_pseudo_group_by"]; _.each(tasks, function(el) { el._pseudo_group_by = "Gantt View"; @@ -107,7 +114,7 @@ instance.web_gantt.GanttView = instance.web.View.extend({ group.tasks = split_groups(group.tasks, _.rest(group_bys)); }); return groups; - } + }; var groups = split_groups(tasks, group_bys); // track ids of task items for context menu @@ -124,7 +131,7 @@ instance.web_gantt.GanttView = instance.web.View.extend({ var task_infos = _.compact(_.map(task.tasks, function(sub_task) { return generate_task_info(sub_task, level + 1); })); - if (task_infos.length == 0) + if (task_infos.length === 0) return; var task_start = _.reduce(_.pluck(task_infos, "task_start"), function(date, memo) { return memo === undefined || date < memo ? date : memo; @@ -133,8 +140,8 @@ instance.web_gantt.GanttView = instance.web.View.extend({ return memo === undefined || date > memo ? date : memo; }, undefined); var duration = (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60); - var group_name = task.name ? instance.web.format_value(task.name, self.fields[group_bys[level]]) : "-"; - if (level == 0) { + var group_name = task.name ? formats.format_value(task.name, self.fields[group_bys[level]]) : "-"; + if (level === 0) { var group = new GanttProjectInfo(_.uniqueId("gantt_project_"), group_name, task_start); _.each(task_infos, function(el) { group.addTask(el.task_info); @@ -150,20 +157,20 @@ instance.web_gantt.GanttView = instance.web.View.extend({ } else { var task_name = task.__name; var duration_in_business_hours = false; - var task_start = instance.web.auto_str_to_date(task[self.fields_view.arch.attrs.date_start]); + var task_start = time.auto_str_to_date(task[self.fields_view.arch.attrs.date_start]); if (!task_start) return; var task_stop; if (self.fields_view.arch.attrs.date_stop) { - task_stop = instance.web.auto_str_to_date(task[self.fields_view.arch.attrs.date_stop]); + task_stop = time.auto_str_to_date(task[self.fields_view.arch.attrs.date_stop]); if (!task_stop) task_stop = task_start; } else { // we assume date_duration is defined - var tmp = instance.web.format_value(task[self.fields_view.arch.attrs.date_delay], + var tmp = formats.format_value(task[self.fields_view.arch.attrs.date_delay], self.fields[self.fields_view.arch.attrs.date_delay]); if (!tmp) return; - var m_task_start = moment(task_start).add(instance.web.parse_value(tmp, {type:"float"}), 'hours'); + var m_task_start = moment(task_start).add(formats.parse_value(tmp, {type:"float"}), 'hours'); task_stop = m_task_start.toDate(); } var duration = (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60); @@ -176,7 +183,7 @@ instance.web_gantt.GanttView = instance.web.View.extend({ task_ids[id] = task_info; return {task_info: task_info, task_start: task_start, task_stop: task_stop}; } - } + }; var gantt = new GanttChart(); _.each(_.compact(_.map(groups, function(e) {return generate_task_info(e, 0);})), function(project) { gantt.addProject(project); @@ -220,10 +227,10 @@ instance.web_gantt.GanttView = instance.web.View.extend({ var end = moment(start).add(duration, 'hours').toDate(); var data = {}; data[self.fields_view.arch.attrs.date_start] = - instance.web.auto_date_to_str(start, self.fields[self.fields_view.arch.attrs.date_start].type); + time.auto_date_to_str(start, self.fields[self.fields_view.arch.attrs.date_start].type); if (self.fields_view.arch.attrs.date_stop) { data[self.fields_view.arch.attrs.date_stop] = - instance.web.auto_date_to_str(end, self.fields[self.fields_view.arch.attrs.date_stop].type); + time.auto_date_to_str(end, self.fields[self.fields_view.arch.attrs.date_stop].type); } else { // we assume date_duration is defined data[self.fields_view.arch.attrs.date_delay] = duration; } @@ -231,7 +238,7 @@ instance.web_gantt.GanttView = instance.web.View.extend({ }, on_task_display: function(task) { var self = this; - var pop = new instance.web.form.FormOpenPopup(self); + var pop = new form_common.FormOpenPopup(self); pop.on('write_completed',self,self.reload); pop.show_element( self.dataset.model, @@ -242,7 +249,7 @@ instance.web_gantt.GanttView = instance.web.View.extend({ }, on_task_create: function() { var self = this; - var pop = new instance.web.form.SelectCreatePopup(this); + var pop = new form_common.SelectCreatePopup(this); pop.on("elements_selected", self, function() { self.reload(); }); @@ -255,4 +262,7 @@ instance.web_gantt.GanttView = instance.web.View.extend({ }, }); -}; +core.view_registry.add('gantt', GanttView); + +return GanttView; +}); diff --git a/addons/web_kanban_gauge/static/src/js/kanban_gauge.js b/addons/web_kanban_gauge/static/src/js/kanban_gauge.js index 27c83f285e2..5af9f4adf08 100644 --- a/addons/web_kanban_gauge/static/src/js/kanban_gauge.js +++ b/addons/web_kanban_gauge/static/src/js/kanban_gauge.js @@ -1,4 +1,12 @@ -openerp.web_kanban_gauge = function (instance) { +odoo.define('web_kanban_gauge.widget', ['web.core', 'web_kanban.common'], function (require) { +"use strict"; + +var core = require('web.core'); +var kanban_common = require('web_kanban.common'); + +var AbstractField = kanban_common.AbstractField; +var fields_registry = kanban_common.registry; +var _t = core._t; /** * Kanban widgets: GaugeWidget @@ -17,10 +25,8 @@ openerp.web_kanban_gauge = function (instance) { * - on_click_label: optional label of the input displayed when clicking * */ -var _t = instance.web._t, - _lt = instance.web._lt; -instance.web_kanban.GaugeWidget = instance.web_kanban.AbstractField.extend({ +var GaugeWidget = AbstractField.extend({ className: "oe_gauge", start: function() { @@ -131,7 +137,7 @@ instance.web_kanban.GaugeWidget = instance.web_kanban.AbstractField.extend({ event.stopPropagation(); flag_open = false; }) - .blur(function (event) { + .blur(function () { if(!flag_open) { self.$el.find(".oe_justgage_edit").remove(); $svg.fadeTo(0, 1); @@ -156,6 +162,6 @@ instance.web_kanban.GaugeWidget = instance.web_kanban.AbstractField.extend({ }, }); -instance.web_kanban.fields_registry.add("gauge", "instance.web_kanban.GaugeWidget"); +fields_registry.add("gauge", GaugeWidget); -} +}); diff --git a/addons/web_kanban_sparkline/static/src/js/kanban_sparkline.js b/addons/web_kanban_sparkline/static/src/js/kanban_sparkline.js index b8c7761d103..1c48fa3bb32 100644 --- a/addons/web_kanban_sparkline/static/src/js/kanban_sparkline.js +++ b/addons/web_kanban_sparkline/static/src/js/kanban_sparkline.js @@ -1,11 +1,17 @@ -openerp.web_kanban_sparkline = function (instance) { +odoo.define(['web_kanban.common'], function (require) { +"use strict"; + +var kanban_common = require('web_kanban.common'); + +var AbstractField = kanban_common.AbstractField; +var fields_registry = kanban_common.registry; /** * Kanban widgets: Sparkline * */ -instance.web_kanban.SparklineBarWidget = instance.web_kanban.AbstractField.extend({ +var SparklineBarWidget = AbstractField.extend({ className: "oe_sparkline_bar", start: function() { var self = this; @@ -15,10 +21,9 @@ instance.web_kanban.SparklineBarWidget = instance.web_kanban.AbstractField.exten var value = _.pluck(field_value, 'value'); var tooltips = _.pluck(field_value, 'tooltip'); var suffix = self.options.tooltip_suffix || ""; - var tooltipFormat = self.options.type == 'tristate' && '{{offset:offset}}' + suffix || '{{offset:offset}} {{value:value}}' + suffix + var tooltipFormat = self.options.type == 'tristate' && '{{offset:offset}}' + suffix || '{{offset:offset}} {{value:value}}' + suffix; var sparkline_options = _.extend({ type: 'bar', - barWidth: 5, height: '20px', barWidth: 4, barSpacing: 1, @@ -30,12 +35,12 @@ instance.web_kanban.SparklineBarWidget = instance.web_kanban.AbstractField.exten } }, self.options); self.$el.sparkline(value, sparkline_options); - self.$el.tooltip({delay: {show: self.options.delayIn || 0, hide: 0}, title: function(){return title}}); + self.$el.tooltip({delay: {show: self.options.delayIn || 0, hide: 0}, title: function(){return title;}}); }, 0); }, }); -instance.web_kanban.fields_registry.add("sparkline_bar", "instance.web_kanban.SparklineBarWidget"); +fields_registry.add("sparkline_bar", SparklineBarWidget); -} +}); diff --git a/addons/web_linkedin/static/src/js/linkedin.js b/addons/web_linkedin/static/src/js/linkedin.js index 5253d731635..80425afff29 100644 --- a/addons/web_linkedin/static/src/js/linkedin.js +++ b/addons/web_linkedin/static/src/js/linkedin.js @@ -1,527 +1,537 @@ +odoo.define('web_linkedin.web_linkedin', ['web.core', 'web.data', 'web.Dialog', 'web.form_widgets', 'web.Model', 'web.utils', 'web.Widget'], function (require) { +"use strict"; + +var core = require('web.core'); +var data = require('web.data'); +var Dialog = require('web.Dialog'); +var form_widgets = require('web.form_widgets'); +var Model = require('web.Model'); +var utils = require('web.utils'); +var Widget = require('web.Widget'); + /*--------------------------------------------------------- * OpenERP web_linkedin (module) *---------------------------------------------------------*/ -openerp.web_linkedin = function(instance) { - var QWeb = instance.web.qweb; - var _t = instance.web._t; - - /* - * instance.web_linkedin.tester.test_authentication() - * Call check if the Linkedin session is open or open a connection popup - * return a deferrer : - * - resolve if the authentication is true - * - reject if the authentication is wrong or when the user logout - */ - instance.web_linkedin.LinkedinTester = instance.web.Class.extend({ - init: function() { - this.linkedin_added = false; - this.linkedin_def = $.Deferred(); - this.auth_def = $.Deferred(); - }, - error_catcher: function (callback) { - var self = this; - if (!this.realError) { - this.realError = Error; - this.window_onerror = window.onerror; - } - if (!callback) { - Error = self.realError; - return false; - } - this.callback = callback; - window.onerror = function(message, fileName, lineNumber) { - if (!window.onerror.prototype.catched) { - self.window_onerror(message, fileName, lineNumber); - } - if (self.realError != Error) { - window.onerror.prototype.catched = false; - } else { - window.onerror = self.window_onerror; - } - }; - window.onerror.prototype.catched = false; - Error = function (message, fileName, lineNumber) { - this.name = message; - this.message = message; - this.fileName = fileName; - this.lineNumber = lineNumber; - this.caller = Error.caller.toString(); - window.onerror.prototype.catched = self.callback.apply(self, [this]); - return this; - }; - Error.prototype.toString = function () {return this.name;}; - }, - linkedin_disabled: function(error) { - this.linkedin_def.reject(); - this.auth_def.reject(); - IN = false; - var dialog = new instance.web.Dialog(this, { - title: _t("LinkedIn is not enabled"), - buttons: [ - {text: _t("Ok"), click: function() { this.parents('.modal').modal('hide'); }} - ], - }, QWeb.render('LinkedIn.DisabledWarning', {error: error})).open(); - }, - test_linkedin: function() { - var self = this; - return this.test_api_key().then(function() { - if (self.linkedin_added) { - return self.linkedin_def; - } - self.$linkedin = $(''); +var QWeb = core.qweb; +var _t = core._t; - self.error_catcher(function (error) { - if (!!error.caller.match(/API Key is invalid/)) { - self.linkedin_disabled(error); - self.$linkedin.remove(); - console.debug("LinkedIn JavaScript removed."); - self.linkedin_added = false; - self.error_catcher(false); - return true; - } else { - return false; - } - }); - window.setTimeout(function () {self.error_catcher(false);}, 5000); - - $("body").append(self.$linkedin); - var tag = document.createElement('script'); - tag.type = 'text/javascript'; - tag.src = "https://platform.linkedin.com/in.js"; - tag.innerHTML = 'api_key : ' + self.api_key + '\nauthorize : true\nscope: r_network r_basicprofile'; // r_contactinfo r_fullprofile r_emailaddress'; - - document.getElementsByTagName('head')[0].appendChild(tag); - self.linkedin_added = true; - $(tag).load(function(event) { - console.debug("LinkedIn JavaScript inserted."); - IN.Event.on(IN, "frameworkLoaded", function() { - self.error_catcher(false); - console.debug("LinkedIn DOM node inserted and frameworkLoaded."); - }); - IN.Event.on(IN, "systemReady", function() { - self.linkedin_def.resolve(); - console.debug("LinkedIn systemReady."); - }); - IN.Event.on(IN, "auth", function() { - self.auth_def.resolve(); - }); - IN.Event.on(IN, "logout", function() { - self.auth_def.reject(); - self.auth_def = $.Deferred(); - }); - }); - return self.linkedin_def.promise(); - }); - }, - test_api_key: function() { - var self = this; - if (this.api_key) { - return $.when(); +/* +* instance.web_linkedin.tester.test_authentication() +* Call check if the Linkedin session is open or open a connection popup +* return a deferrer : +* - resolve if the authentication is true +* - reject if the authentication is wrong or when the user logout +*/ +var LinkedinTester = core.Class.extend({ + init: function() { + this.linkedin_added = false; + this.linkedin_def = $.Deferred(); + this.auth_def = $.Deferred(); + }, + error_catcher: function (callback) { + var self = this; + if (!this.realError) { + this.realError = Error; + this.window_onerror = window.onerror; + } + if (!callback) { + Error = self.realError; + return false; + } + this.callback = callback; + window.onerror = function(message, fileName, lineNumber) { + if (!window.onerror.prototype.catched) { + self.window_onerror(message, fileName, lineNumber); } - return new instance.web.Model("ir.config_parameter").call("get_param", ["web.linkedin.apikey"]).then(function(a) { - if (!!a) { - self.api_key = a; + if (self.realError != Error) { + window.onerror.prototype.catched = false; + } else { + window.onerror = self.window_onerror; + } + }; + window.onerror.prototype.catched = false; + Error = function (message, fileName, lineNumber) { + this.name = message; + this.message = message; + this.fileName = fileName; + this.lineNumber = lineNumber; + this.caller = Error.caller.toString(); + window.onerror.prototype.catched = self.callback.apply(self, [this]); + return this; + }; + Error.prototype.toString = function () {return this.name;}; + }, + linkedin_disabled: function(error) { + this.linkedin_def.reject(); + this.auth_def.reject(); + IN = false; + new Dialog(this, { + title: _t("LinkedIn is not enabled"), + buttons: [ + {text: _t("Ok"), click: function() { this.parents('.modal').modal('hide'); }} + ], + }, QWeb.render('LinkedIn.DisabledWarning', {error: error})).open(); + }, + test_linkedin: function() { + var self = this; + return this.test_api_key().then(function() { + if (self.linkedin_added) { + return self.linkedin_def; + } + self.$linkedin = $(''); + + self.error_catcher(function (error) { + if (!!error.caller.match(/API Key is invalid/)) { + self.linkedin_disabled(error); + self.$linkedin.remove(); + console.debug("LinkedIn JavaScript removed."); + self.linkedin_added = false; + self.error_catcher(false); return true; } else { - return $.Deferred().reject(); + return false; } }); - }, - test_authentication: function() { - var self = this; - this.linkedin_def.done(function () { - if (IN.User.isAuthorized()) { + window.setTimeout(function () {self.error_catcher(false);}, 5000); + + $("body").append(self.$linkedin); + var tag = document.createElement('script'); + tag.type = 'text/javascript'; + tag.src = "https://platform.linkedin.com/in.js"; + tag.innerHTML = 'api_key : ' + self.api_key + '\nauthorize : true\nscope: r_network r_basicprofile'; // r_contactinfo r_fullprofile r_emailaddress'; + + document.getElementsByTagName('head')[0].appendChild(tag); + self.linkedin_added = true; + $(tag).load(function(event) { + console.debug("LinkedIn JavaScript inserted."); + IN.Event.on(IN, "frameworkLoaded", function() { + self.error_catcher(false); + console.debug("LinkedIn DOM node inserted and frameworkLoaded."); + }); + IN.Event.on(IN, "systemReady", function() { + self.linkedin_def.resolve(); + console.debug("LinkedIn systemReady."); + }); + IN.Event.on(IN, "auth", function() { self.auth_def.resolve(); - } else { - IN.User.authorize(); - } + }); + IN.Event.on(IN, "logout", function() { + self.auth_def.reject(); + self.auth_def = $.Deferred(); + }); }); - return this.auth_def.promise(); - }, - }); - - instance.web_linkedin.tester = new instance.web_linkedin.LinkedinTester(); - - instance.web_linkedin.Linkedin = instance.web.form.FieldChar.extend({ - init: function() { - this._super.apply(this, arguments); - this.display_dm = new instance.web.DropMisordered(true); - }, - initialize_content: function() { - var $ht = $(QWeb.render("FieldChar.linkedin")); - var $in = this.$("input"); - $in.replaceWith($ht); - this.$(".oe_linkedin_input").append($in); - this.$(".oe_linkedin_img").click(_.bind(this.search_linkedin, this)); - this._super(); - }, - search_linkedin: function() { - var self = this; - if (!this.open_in_process) { - this.open_in_process = true; - this.display_dm.add(instance.web_linkedin.tester.test_linkedin()).done(function() { - self.open_in_process = false; - var text = (self.get("value") || "").replace(/^\s+|\s+$/g, "").replace(/\s+/g, " "); - instance.web_linkedin.tester.test_authentication().done(function() { - var pop = new instance.web_linkedin.LinkedinSearchPopup(self, text); - pop.open(); - pop.on("selected", this, function(entity) { - self.selected_entity(entity); - }); + return self.linkedin_def.promise(); + }); + }, + test_api_key: function() { + var self = this; + if (this.api_key) { + return $.when(); + } + return new Model("ir.config_parameter").call("get_param", ["web.linkedin.apikey"]).then(function(a) { + if (!!a) { + self.api_key = a; + return true; + } else { + return $.Deferred().reject(); + } + }); + }, + test_authentication: function() { + var self = this; + this.linkedin_def.done(function () { + if (IN.User.isAuthorized()) { + self.auth_def.resolve(); + } else { + IN.User.authorize(); + } + }); + return this.auth_def.promise(); + }, +}); + +var tester = new LinkedinTester(); + +var Linkedin = form_widgets.FieldChar.extend({ + init: function() { + this._super.apply(this, arguments); + this.display_dm = new utils.DropMisordered(true); + }, + initialize_content: function() { + var $ht = $(QWeb.render("FieldChar.linkedin")); + var $in = this.$("input"); + $in.replaceWith($ht); + this.$(".oe_linkedin_input").append($in); + this.$(".oe_linkedin_img").click(_.bind(this.search_linkedin, this)); + this._super(); + }, + search_linkedin: function() { + var self = this; + if (!this.open_in_process) { + this.open_in_process = true; + this.display_dm.add(tester.test_linkedin()).done(function() { + self.open_in_process = false; + var text = (self.get("value") || "").replace(/^\s+|\s+$/g, "").replace(/\s+/g, " "); + tester.test_authentication().done(function() { + var pop = new LinkedinSearchPopup(self, text); + pop.open(); + pop.on("selected", this, function(entity) { + self.selected_entity(entity); }); }); - } - }, - selected_entity: function(entity) { - var self = this; - this.create_on_change(entity).done(function(to_change) { - var values = self.view.get_fields_values(); - _.each(to_change, function (value, key) { - if (!/linkedin/.test(key) && !!values[key]) { - if(!_.isArray(values[key])) { - delete to_change[key]; - } + }); + } + }, + selected_entity: function(entity) { + var self = this; + this.create_on_change(entity).done(function(to_change) { + var values = self.view.get_fields_values(); + _.each(to_change, function (value, key) { + if (!/linkedin/.test(key) && !!values[key]) { + if(!_.isArray(values[key])) { + delete to_change[key]; } - }) - self.view.set_values(to_change); + } }); - }, - create_on_change: function(entity) { - return entity.__type === "company" ? this.create_or_modify_company(entity) : this.create_or_modify_partner(entity); - }, - create_or_modify_company: function (entity) { - var self = this; - var to_change = {}; - var image_def = null; - to_change.is_company = true; - to_change.name = entity.name; - to_change.image = false; - if (entity.logoUrl) { - image_def = self.rpc('/web_linkedin/binary/url2binary', - {'url': entity.logoUrl}).then(function(data){ - to_change.image = data; - }); - } - to_change.website = entity.websiteUrl; - to_change.phone = false; - _.each((entity.locations || {}).values || [], function(el) { - to_change.phone = el.contactInfo.phone1; + self.view.set_values(to_change); + }); + }, + create_on_change: function(entity) { + return entity.__type === "company" ? this.create_or_modify_company(entity) : this.create_or_modify_partner(entity); + }, + create_or_modify_company: function (entity) { + var self = this; + var to_change = {}; + var image_def = null; + to_change.is_company = true; + to_change.name = entity.name; + to_change.image = false; + if (entity.logoUrl) { + image_def = self.rpc('/web_linkedin/binary/url2binary', + {'url': entity.logoUrl}).then(function(data){ + to_change.image = data; }); - to_change.linkedin_url = _.str.sprintf("http://www.linkedin.com/company/%d", entity.id); + } + to_change.website = entity.websiteUrl; + to_change.phone = false; + _.each((entity.locations || {}).values || [], function(el) { + to_change.phone = el.contactInfo.phone1; + }); + to_change.linkedin_url = _.str.sprintf("http://www.linkedin.com/company/%d", entity.id); + _.each(to_change, function (val, key) { + if (self.field_manager.datarecord[key]) { + to_change[key] = self.field_manager.datarecord[key]; + } + }); + + to_change.child_ids = []; + var children_def = $.Deferred(); + IN.API.PeopleSearch().fields(commonPeopleFields).params({ + "company-name" : entity.universalName, + "current-company": true, + "count": 50, + }).result(function (result) { + console.debug("Linkedin pepople in this company found :", result.numResults, "=>", result.people._count, result.people.values); + var result = _.reject(result.people.values || [], function(el) { + return ! el.formattedName; + }); + self.create_or_modify_company_partner(result).then(function (childs_to_change) { + _.each(childs_to_change, function (data) { + // [0,0,data] if it's a new partner + to_change.child_ids.push( data.id ? [1, data.id, data] : [0, 0, data] ); + }); + children_def.resolve(); + }); + }).error(function () { + children_def.reject(); + }); + + return $.when(image_def, children_def).then(function () { + return to_change; + }); + }, + create_or_modify_partner: function (entity, rpc_search_similar_partner) { + var self = this; + return this.create_or_modify_partner_change(entity).then(function (to_change) { + // find similar partners _.each(to_change, function (val, key) { if (self.field_manager.datarecord[key]) { to_change[key] = self.field_manager.datarecord[key]; } }); - - to_change.child_ids = []; - var children_def = $.Deferred(); - IN.API.PeopleSearch().fields(commonPeopleFields).params({ - "company-name" : entity.universalName, - "current-company": true, - "count": 50, - }).result(function (result) { - console.debug("Linkedin pepople in this company found :", result.numResults, "=>", result.people._count, result.people.values); - var result = _.reject(result.people.values || [], function(el) { - return ! el.formattedName; - }); - self.create_or_modify_company_partner(result).then(function (childs_to_change) { - _.each(childs_to_change, function (data) { - // [0,0,data] if it's a new partner - to_change.child_ids.push( data.id ? [1, data.id, data] : [0, 0, data] ); - }); - children_def.resolve(); - }); - }).error(function () { - children_def.reject(); - }); - - return $.when(image_def, children_def).then(function () { - return to_change; - }); - }, - create_or_modify_partner: function (entity, rpc_search_similar_partner) { - var self = this; - return this.create_or_modify_partner_change(entity).then(function (to_change) { - // find similar partners - _.each(to_change, function (val, key) { - if (self.field_manager.datarecord[key]) { - to_change[key] = self.field_manager.datarecord[key]; - } - }); - }); - }, - create_or_modify_partner_change: function (entity) { - var to_change = {}; - var defs = []; - to_change.is_company = false; - to_change.name = entity.formattedName; - if (entity.pictureUrl) { - defs.push(this.rpc('/web_linkedin/binary/url2binary', - {'url': entity.pictureUrl}).then(function(data){ - to_change.image = data; - })); - } - _.each((entity.phoneNumbers || {}).values || [], function(el) { - if (el.phoneType === "mobile") { - to_change.mobile = el.phoneNumber; - } else { - to_change.phone = el.phoneNumber; - } - }); - var positions = (entity.positions || {}).values || []; - for (key in positions) { - var position = positions[key]; - if (position.isCurrent) { - var company_name = position.company ? position.company.name : false; - if (!entity.parent_id && entity.parent_id !== 0 && company_name) { - defs.push(new instance.web.DataSetSearch(this, 'res.partner').call("search", [[["name", "=", company_name]]]).then(function (data) { - if(data[0]) to_change.parent_id = data[0]; - else position.title = position.title + ' (' + company_name + ') '; - to_change.function = position.title; - })); - } else if (!entity.__company || !company_name || company_name == entity.__company) { - to_change.function = position.title + (company_name ? ' (' + company_name + ') ':''); - } - break; - } - }; - - if (entity.parent_id) { - to_change.parent_id = entity.parent_id; - } - to_change.linkedin_url = to_change.linkedin_public_url = entity.publicProfileUrl || false; - to_change.linkedin_id = entity.id || false; - - return $.when.apply($, defs).then(function () { - return to_change; - }); - }, - create_or_modify_company_partner: function (entities) { - var self = this; - var deferrer = $.Deferred(); - var defs = []; - var childs_to_change = []; - - _.each(entities, function (entity, key) { - var entity = _.extend(entity, { - '__type': "people", - '__company': entity.universalName, - 'parent_id': self.field_manager.datarecord.id || 0 - }); - defs.push(self.create_or_modify_partner_change(entity).then(function (to_change) { - childs_to_change[key] = to_change; - })); - }); - $.when.apply($, defs).then(function () { - new instance.web.DataSetSearch(this, 'res.partner').call("linkedin_check_similar_partner", [entities]).then(function (partners) { - _.each(partners, function (partner, i) { - _.each(partner, function (val, key) { - if (val) { - childs_to_change[i][key] = val; - } - }); - }); - deferrer.resolve(childs_to_change); - }); - }); - return deferrer; + }); + }, + create_or_modify_partner_change: function (entity) { + var to_change = {}; + var defs = []; + to_change.is_company = false; + to_change.name = entity.formattedName; + if (entity.pictureUrl) { + defs.push(this.rpc('/web_linkedin/binary/url2binary', + {'url': entity.pictureUrl}).then(function(data){ + to_change.image = data; + })); } - }); - instance.web.form.widgets.add('linkedin', 'instance.web_linkedin.Linkedin'); - - instance.web_linkedin.Linkedin_url = instance.web.form.FieldChar.extend({ - initialize_content: function() { - this.$("input,span").replaceWith($(QWeb.render("FieldChar.linkedin_url"))); - this._super(); - }, - render_value: function() { - this._super(); - this.$(".oe_linkedin_url").attr("href", this.field_manager.datarecord.linkedin_url || "#").toggle(!!this.field_manager.datarecord.linkedin_url); - }, - }); - instance.web.form.widgets.add('linkedin_url', 'instance.web_linkedin.Linkedin_url'); - - - var commonPeopleFields = ["id", "picture-url", "public-profile-url", "first-name", "last-name", - "formatted-name", "location", "phone-numbers", "im-accounts", - "main-address", "headline", "positions", "summary", "specialties"]; - - instance.web_linkedin.LinkedinSearchPopup = instance.web.Dialog.extend({ - template: "Linkedin.popup", - init: function(parent, search) { - var self = this; - if (!IN.User.isAuthorized()) { - this.$buttons = $(""); - this.destroy(); + _.each((entity.phoneNumbers || {}).values || [], function(el) { + if (el.phoneType === "mobile") { + to_change.mobile = el.phoneNumber; + } else { + to_change.phone = el.phoneNumber; } - this._super(parent, { 'title': QWeb.render('LinkedIn.AdvancedSearch', {'title': _t("LinkedIn search")}) }); - this.search = search; - this.limit = 5; - }, - start: function() { - this._super(); - this.bind_event(); - this.display_account(); - this.do_search(); - }, - bind_event: function() { - var self = this; - this.$el.parents('.modal').on("click", ".oe_linkedin_logout", function () { - IN.User.logout(); + }); + var positions = (entity.positions || {}).values || []; + for (var key in positions) { + var position = positions[key]; + if (position.isCurrent) { + var company_name = position.company ? position.company.name : false; + if (!entity.parent_id && entity.parent_id !== 0 && company_name) { + defs.push(new data.DataSetSearch(this, 'res.partner').call("search", [[["name", "=", company_name]]]).then(function (data) { + if(data[0]) to_change.parent_id = data[0]; + else position.title = position.title + ' (' + company_name + ') '; + to_change.function = position.title; + })); + } else if (!entity.__company || !company_name || company_name == entity.__company) { + to_change.function = position.title + (company_name ? ' (' + company_name + ') ':''); + } + break; + } + } + + if (entity.parent_id) { + to_change.parent_id = entity.parent_id; + } + to_change.linkedin_url = to_change.linkedin_public_url = entity.publicProfileUrl || false; + to_change.linkedin_id = entity.id || false; + + return $.when.apply($, defs).then(function () { + return to_change; + }); + }, + create_or_modify_company_partner: function (entities) { + var self = this; + var deferrer = $.Deferred(); + var defs = []; + var childs_to_change = []; + + _.each(entities, function (entity, key) { + var entity = _.extend(entity, { + '__type': "people", + '__company': entity.universalName, + 'parent_id': self.field_manager.datarecord.id || 0 + }); + defs.push(self.create_or_modify_partner_change(entity).then(function (to_change) { + childs_to_change[key] = to_change; + })); + }); + $.when.apply($, defs).then(function () { + new data.DataSetSearch(this, 'res.partner').call("linkedin_check_similar_partner", [entities]).then(function (partners) { + _.each(partners, function (partner, i) { + _.each(partner, function (val, key) { + if (val) { + childs_to_change[i][key] = val; + } + }); + }); + deferrer.resolve(childs_to_change); + }); + }); + return deferrer; + } +}); +core.form_widget_registry.add('linkedin', Linkedin); + +var Linkedin_url = form_widgets.FieldChar.extend({ + initialize_content: function() { + this.$("input,span").replaceWith($(QWeb.render("FieldChar.linkedin_url"))); + this._super(); + }, + render_value: function() { + this._super(); + this.$(".oe_linkedin_url").attr("href", this.field_manager.datarecord.linkedin_url || "#").toggle(!!this.field_manager.datarecord.linkedin_url); + }, +}); +core.form_widget_registry.add('linkedin_url', Linkedin_url); + + +var commonPeopleFields = ["id", "picture-url", "public-profile-url", "first-name", "last-name", + "formatted-name", "location", "phone-numbers", "im-accounts", + "main-address", "headline", "positions", "summary", "specialties"]; + +var LinkedinSearchPopup = Dialog.extend({ + template: "Linkedin.popup", + init: function(parent, search) { + if (!IN.User.isAuthorized()) { + this.$buttons = $(""); + this.destroy(); + } + this._super(parent, { 'title': QWeb.render('LinkedIn.AdvancedSearch', {'title': _t("LinkedIn search")}) }); + this.search = search; + this.limit = 5; + }, + start: function() { + this._super(); + this.bind_event(); + this.display_account(); + this.do_search(); + }, + bind_event: function() { + var self = this; + this.$el.parents('.modal').on("click", ".oe_linkedin_logout", function () { + IN.User.logout(); + self.destroy(); + }); + this.$search = this.$el.parents('.modal').find(".oe_linkedin_advanced_search" ); + this.$url = this.$search.find("input[name='search']" ); + this.$button = this.$search.find("button"); + + this.$button.on("click", function (e) { + e.stopPropagation(); + self.do_search(self.$url.val() || ''); + }); + this.$url + .on("click mousedown mouseup", function (e) { + e.stopPropagation(); + }).on("keydown", function (e) { + if(e.keyCode == 13) { + $(e.target).blur(); + self.$button.click(); + } + }); + }, + display_account: function() { + var self = this; + IN.API.Profile("me") + .fields(["firstName", "lastName"]) + .result(function (result) { + $(QWeb.render('LinkedIn.loginInformation', result.values[0])).appendTo(self.$el.parents('.modal').find(".oe_dialog_custom_buttons")); + }); + }, + do_search: function(url) { + if (!IN.User || !IN.User.isAuthorized()) { + this.destroy(); + } + var self = this; + var deferrers = []; + this.$(".oe_linkedin_pop_c, .oe_linkedin_pop_p").empty(); + + if (url && url.length) { + var deferrer_c = $.Deferred(); + var deferrer_p = $.Deferred(); + deferrers.push(deferrer_c, deferrer_p); + + var url = url.replace(/\/+$/, ''); + var uid = url.replace(/(.*linkedin\.com\/[a-z]+\/)|(^.*\/company\/)|(\&.*$)/gi, ''); + + IN.API.Raw(_.str.sprintf( + "companies/universal-name=%s:(id,name,logo-url,description,industry,website-url,locations,universal-name)", + encodeURIComponent(uid.toLowerCase()))).result(function (result) { + self.do_result_companies({'companies': {'values': [result]}}); + deferrer_c.resolve(); + }).error(function () { + self.do_result_companies({}); + deferrer_c.resolve(); + }); + + var url_public = "http://www.linkedin.com/pub/"+uid; + IN.API.Profile("url="+ encodeURI(url_public).replace(/%2F/g, '/')) + .fields(commonPeopleFields) + .result(function(result) { + self.do_result_people({'people': result}); + deferrer_p.resolve(); + }).error(function (error) { + self.do_warn( _t("LinkedIn error"), _t("LinkedIn is temporary down for the searches by url.")); + self.do_result_people({}); + deferrer_p.resolve(); + }); + + this.search = url; + } + + var deferrer_c_k = $.Deferred(); + var deferrer_p_k = $.Deferred(); + deferrers.push(deferrer_c_k, deferrer_p_k); + IN.API.Raw(_.str.sprintf( + "company-search:(companies:" + + "(id,name,logo-url,description,industry,website-url,locations,universal-name))?keywords=%s&count=%d", + encodeURI(this.search), this.limit)).result(function (result) { + self.do_result_companies(result); + deferrer_c_k.resolve(); + }); + IN.API.PeopleSearch().fields(commonPeopleFields).params({"keywords": this.search, "count": this.limit}).result(function(result) { + self.do_result_people(result); + deferrer_p_k.resolve(); + }); + + return $.when.apply($, deferrers); + }, + do_result_companies: function(companies) { + var lst = (companies.companies || {}).values || []; + lst = _.first(lst, this.limit); + lst = _.map(lst, function(el) { + el.__type = "company"; + return el; + }); + console.debug("Linkedin companies found:", (companies.companies || {})._total, '=>', lst.length, lst); + return this.display_result(lst, this.$(".oe_linkedin_pop_c")); + }, + do_result_people: function(people) { + var plst = (people.people || {}).values || []; + plst = _.first(plst, this.limit); + plst = _.map(plst, function(el) { + el.__type = "people"; + return el; + }); + console.debug("Linkedin people found:", people.numResults, '=>', plst.length, plst); + return this.display_result(plst, this.$(".oe_linkedin_pop_p")); + }, + display_result: function(result, $elem) { + var self = this; + var $row; + $elem.find(".oe_no_result").remove(); + _.each(result, function(el) { + var pc = new EntityWidget(self, el); + if (!$elem.find("div").size() || $elem.find(" > div:last > div").size() >= 5) { + $row = $(""); + $row.appendTo($elem); + } + pc.appendTo($row); + pc.$el.css("display", "table-cell"); + pc.$el.css("width", "20%"); + pc.on("selected", self, function(data) { + self.trigger("selected", data); self.destroy(); }); - this.$search = this.$el.parents('.modal').find(".oe_linkedin_advanced_search" ); - this.$url = this.$search.find("input[name='search']" ); - this.$button = this.$search.find("button"); - - this.$button.on("click", function (e) { - e.stopPropagation(); - self.do_search(self.$url.val() || ''); - }); - this.$url - .on("click mousedown mouseup", function (e) { - e.stopPropagation(); - }).on("keydown", function (e) { - if(e.keyCode == 13) { - $(e.target).blur(); - self.$button.click(); - } - }); - }, - display_account: function() { - var self = this; - IN.API.Profile("me") - .fields(["firstName", "lastName"]) - .result(function (result) { - $(QWeb.render('LinkedIn.loginInformation', result.values[0])).appendTo(self.$el.parents('.modal').find(".oe_dialog_custom_buttons")); - }) - }, - do_search: function(url) { - if (!IN.User || !IN.User.isAuthorized()) { - this.destroy(); - } - var self = this; - var deferrers = []; - this.$(".oe_linkedin_pop_c, .oe_linkedin_pop_p").empty(); - - if (url && url.length) { - var deferrer_c = $.Deferred(); - var deferrer_p = $.Deferred(); - deferrers.push(deferrer_c, deferrer_p); - - var url = url.replace(/\/+$/, ''); - var uid = url.replace(/(.*linkedin\.com\/[a-z]+\/)|(^.*\/company\/)|(\&.*$)/gi, ''); - - IN.API.Raw(_.str.sprintf( - "companies/universal-name=%s:(id,name,logo-url,description,industry,website-url,locations,universal-name)", - encodeURIComponent(uid.toLowerCase()))).result(function (result) { - self.do_result_companies({'companies': {'values': [result]}}); - deferrer_c.resolve(); - }).error(function (error) { - self.do_result_companies({}); - deferrer_c.resolve(); - }); - - var url_public = "http://www.linkedin.com/pub/"+uid; - IN.API.Profile("url="+ encodeURI(url_public).replace(/%2F/g, '/')) - .fields(commonPeopleFields) - .result(function(result) { - self.do_result_people({'people': result}); - deferrer_p.resolve(); - }).error(function (error) { - self.do_warn( _t("LinkedIn error"), _t("LinkedIn is temporary down for the searches by url.")); - self.do_result_people({}); - deferrer_p.resolve(); - }); - - this.search = url; - } - - var deferrer_c_k = $.Deferred(); - var deferrer_p_k = $.Deferred(); - deferrers.push(deferrer_c_k, deferrer_p_k); - IN.API.Raw(_.str.sprintf( - "company-search:(companies:" + - "(id,name,logo-url,description,industry,website-url,locations,universal-name))?keywords=%s&count=%d", - encodeURI(this.search), this.limit)).result(function (result) { - self.do_result_companies(result); - deferrer_c_k.resolve(); - }); - IN.API.PeopleSearch().fields(commonPeopleFields).params({"keywords": this.search, "count": this.limit}).result(function(result) { - self.do_result_people(result); - deferrer_p_k.resolve(); - }); - - return $.when.apply($, deferrers); - }, - do_result_companies: function(companies) { - var lst = (companies.companies || {}).values || []; - lst = _.first(lst, this.limit); - lst = _.map(lst, function(el) { - el.__type = "company"; - return el; - }); - console.debug("Linkedin companies found:", (companies.companies || {})._total, '=>', lst.length, lst); - return this.display_result(lst, this.$(".oe_linkedin_pop_c")); - }, - do_result_people: function(people) { - var plst = (people.people || {}).values || []; - plst = _.first(plst, this.limit); - plst = _.map(plst, function(el) { - el.__type = "people"; - return el; - }); - console.debug("Linkedin people found:", people.numResults, '=>', plst.length, plst); - return this.display_result(plst, this.$(".oe_linkedin_pop_p")); - }, - display_result: function(result, $elem) { - var self = this; - var $row; - $elem.find(".oe_no_result").remove(); - _.each(result, function(el) { - var pc = new instance.web_linkedin.EntityWidget(self, el); - if (!$elem.find("div").size() || $elem.find(" > div:last > div").size() >= 5) { - $row = $(""); - $row.appendTo($elem); - } - pc.appendTo($row); - pc.$el.css("display", "table-cell"); - pc.$el.css("width", "20%"); - pc.on("selected", self, function(data) { - self.trigger("selected", data); - self.destroy(); - }); - }); - if (!$elem.find("div").size()) { - $elem.append($('