diff options
| author | Yannick Tivisse <yti@odoo.com> | 2019-04-25 15:42:05 +0000 |
|---|---|---|
| committer | Yannick Tivisse <yti@odoo.com> | 2019-05-13 08:57:49 +0000 |
| commit | a5b6f31cf28e5381e1c85f66730bcdb55998e643 (patch) | |
| tree | 0a2261c2f7fc3b38e19692d555c40883e483f6c1 /addons/web/static/src/js | |
| parent | e1424d49b08283eac170e80ce59b7d5be5ff1392 (diff) | |
[IMP] base: Contextualize the multi company
Purpose
=======
Allow the user to select the allowed companies for which he wants to see records
on top of selecting his current company.
It is confusing for users to see the records from the company he is connected to
and the records of the children companies.
Instead of using the hierarchy of companies to access records across companies,
the user can now select (from his set of allowed companies) the companies for
which he wants to access records.
/!\ This means that the user will interact with records from company A when in
company B.
Example: a SO has been created and confirmed in A. When in B, I create the
invoice from it.
Specifications
==============
1/ Deprecate the parent/children hierarchy on the res.company model. The fields are
kept on the res.company model to ensure the retro-compatibility, but won't be used
accross the standard code anymore. The only functional usage for this mechanism
was to allow to see records from several companies by creating a virtual parent
company, which will be possible with the new mechanism.
2/ By default, a user will only see the records of the company he is connected
to (or records without a company). (It is still editable by the user if needed).
For that, put this information in the user context, to allow having different
configurations on different browser tabs. Instead of having domains like
['|',
('company_id', '=', False),
('company_id', 'child_of', user.company_id.id)]
you'll have something like
['|',
('company_id', '=', False),
('company_id', 'in', company_ids)]
Note that the 'company_ids' is a value that is passed in the evaluation
context on the record rule, as we already have user, or time.
company_ids is a list of the ids of all the enabled companies in the
user's context.
3/ Out of the generic improvements brought by this task, this will illustrate
issues that could exist since several versions. For example, it should not be
possible to create a scrap order for the company A with a package of the company
B, or it should not be possible to create an invoice on the company A with
payment terms from the company B. Before the version 12.0, it was easy to
encounter this kind of issues as the admin was the SUPERUSER_ID. A positive side
effect of the fact that the SUPERUSER_ID has become an inactive user was to
make it more difficult to introduce mismatch on the records, but haven't solved
the issue, as it was still possible to do it with parent companies
configuration. Some of these issues have been fixed in this commit, but all the
business flows should be re-tested to check if an ir.rule should be introduced
(eg: a multi company rule for stock.quand.package), if the company of a record
is correctly transfered to another record created from the first record (eg:
From a SO, create an invoice and a payment, the company of the sales order
should be transfered on the invoice and the payment, even if the company of the
sales order is A and I'm logged into the company B with the company A enabled.
4/ Currently, if I click on a button on a notification email (example 'View
Task'), I face a traceback if I'm not logged into the company of the record.
Now, if you click on a button and if you have access to the record, the correct
company will be automatically set.
5/ If I display a kanban view with several records from several companies (and
an image), all the images should be displayed.
6/ Currently if you copy paste an url, this will crash if you're not in the
correct company. This won't be fixed because it's quite impossible to do it in
a clean way. This task brings a workaround. Copy/Paste -> Traceback -> Log into
the correct company, re-copy/paste -> Ok.
7/ 2 property methods have been added on the environment to retrieve the company
on which the user is logged in and the companies the user enabled, on a specific
tab.
That way, when creating a record, instead of doing
default=lambda self: self.env.user.company_id
do
default=lambda self: self.env.company_id
On the other hand, to retrieve the enabled companies, do
companies = self.env.company_ids
8/ Modify the Company Switcher widget to allow to log into another company
WITHOUT writing on the res.users (and thus bringing cache invalidation issues
and so on). Also allow to enable several companies and see records from several
companies, and independantly of the other browser's tabs.
9/ When focusing on a tab, save the current company configuration on the local
storage. That way, when doing 'CTRL+T' or a middle click, the context is
propagated to the new tab.
10/ Improve the error message in case of multi company access errors. Now, when
the user is in debug mode, display the related names of the records and the name
of the user who brings the issue.
11/ Remove the context erasing when writing on a res.users
This is probably coming from the migration to new API of the base module.
The context was not propagated at this moment, which was a common mistake at
that time. When migrating the module, probably by using the 'black box' method,
as the context was not propagated, it was erased on the new version. This is
now an issue because the context (i.e. the enabled companies) was erased when
writing on a res.users, leading to tracebacks.
See: https://github.com/odoo/odoo/commit/7eab8e26d3d46c53f4be924d6a34e80a66e74960#diff-4c2e738ee8f64f11806c889ea097b5e7R624
12/ Fix the crash manager on redirect warnings. The issue is the following
- Create an invoice on a company without a configured CoA.
- Set a partner
- On the onchange_partner_id, a redirect warning is raised to propose you
to configure a CoA
- Click on 'Go to the configuration panel'
- A generic warning says something like 'Do you want to discard your changes?'
- Click on yes, the page refreshes, but not on the redirect action.
Now, set correctly the action on the hash, and reload instead. The breadcrumb is
lost for example, but you reach the correct action at least.
13/ Introduce a res.group to enable/disable the multi company per tab
feature.
14/ To help the users to know which tab is in which company, add the
possibility to have a favicon per company. When creating a company,
the classical 'O' icon is colored by default in a random color.
15/ Remove the company switcher on the frontend. This was mainly there
to allow a user to swicth to the company linked to the website.
This behavior is now transparent to the user. If the website A is
activated, then the company set on the context is the company of the
website.
16/ Deprecated the _company_default_get method on the res.company
model. Remove the method _get_company on the res.users model.
17/ Add 'allowed_company_ids' and 'current_company_id' on the pyeval
context. You can now use those variables on domains in the views to
access directly to the activated company.ies on the current tab.
TaskID: 1960971
closes odoo/odoo#32341
Signed-off-by: Yannick Tivisse (yti) <yti@odoo.com>
Diffstat (limited to 'addons/web/static/src/js')
| -rw-r--r-- | addons/web/static/src/js/chrome/abstract_web_client.js | 26 | ||||
| -rw-r--r-- | addons/web/static/src/js/chrome/web_client.js | 3 | ||||
| -rw-r--r-- | addons/web/static/src/js/core/py_utils.js | 6 | ||||
| -rw-r--r-- | addons/web/static/src/js/core/session.js | 23 | ||||
| -rw-r--r-- | addons/web/static/src/js/services/crash_manager.js | 6 | ||||
| -rw-r--r-- | addons/web/static/src/js/views/basic/basic_model.js | 8 | ||||
| -rw-r--r-- | addons/web/static/src/js/widgets/switch_company_menu.js | 81 |
7 files changed, 113 insertions, 40 deletions
diff --git a/addons/web/static/src/js/chrome/abstract_web_client.js b/addons/web/static/src/js/chrome/abstract_web_client.js index 68ac157868d..9566dbda850 100644 --- a/addons/web/static/src/js/chrome/abstract_web_client.js +++ b/addons/web/static/src/js/chrome/abstract_web_client.js @@ -21,9 +21,11 @@ var Dialog = require('web.Dialog'); var dom = require('web.dom'); var KeyboardNavigationMixin = require('web.KeyboardNavigationMixin'); var Loading = require('web.Loading'); +var local_storage = require('web.local_storage'); var RainbowMan = require('web.RainbowMan'); var ServiceProviderMixin = require('web.ServiceProviderMixin'); var session = require('web.session'); +var utils = require('web.utils'); var Widget = require('web.Widget'); var _t = core._t; @@ -112,6 +114,26 @@ var AbstractWebClient = Widget.extend(ServiceProviderMixin, KeyboardNavigationMi this.on("change:title_part", this, this._title_changed); this._title_changed(); + var state = $.bbq.getState(); + // If not set on the url, retrieve cids from the local storage + // of from the default company on the user + var current_company_id = session.user_companies.current_company[0] + if (!state.cids) { + state.cids = utils.get_cookie('cids') !== null ? utils.get_cookie('cids') : String(current_company_id); + } + var stateCompanyIDS = _.map(state.cids.split(','), function (cid) { return parseInt(cid) }); + var userCompanyIDS = _.map(session.user_companies.allowed_companies, function(company) {return company[0]}); + // Check that the user has access to all the companies + if (!_.isEmpty(_.difference(stateCompanyIDS, userCompanyIDS))) { + state.cids = String(current_company_id); + stateCompanyIDS = [current_company_id] + } + // Update the user context with this configuration + session.user_context.allowed_company_ids = stateCompanyIDS; + $.bbq.pushState(state); + // Update favicon + $("link[type='image/x-icon'").attr('href', '/web/image/res.company/' + String(stateCompanyIDS[0]) + '/favicon/') + return session.is_bound .then(function () { self.$el.toggleClass('o_rtl', _t.database.parameters.direction === "rtl"); @@ -167,7 +189,7 @@ var AbstractWebClient = Widget.extend(ServiceProviderMixin, KeyboardNavigationMi } }, 0); }); - window.addEventListener('blur', function (e) { self._hideAccessKeyOverlay(); }); + window.addEventListener('blur', function (e) {self._hideAccessKeyOverlay(); }); core.bus.on('click', this, function (ev) { $('.tooltip').remove(); if (!$(ev.target).is('input[type=file]')) { @@ -437,7 +459,7 @@ var AbstractWebClient = Widget.extend(ServiceProviderMixin, KeyboardNavigationMi * @param {OdooEvent} e */ _onPushState: function (e) { - this.do_push_state(e.data.state); + this.do_push_state(_.extend(e.data.state, {'cids': $.bbq.getState().cids})); }, /** * This function must be implemented by actual webclient to scroll either to diff --git a/addons/web/static/src/js/chrome/web_client.js b/addons/web/static/src/js/chrome/web_client.js index 392d534f372..19ce0a92d41 100644 --- a/addons/web/static/src/js/chrome/web_client.js +++ b/addons/web/static/src/js/chrome/web_client.js @@ -87,7 +87,8 @@ return AbstractWebClient.extend({ // If the url's state is empty, we execute the user's home action if there is one (we // show the first app if not) - if (_.isEmpty($.bbq.getState(true))) { + var state = $.bbq.getState(true); + if (_.keys(state).length === 1 && _.keys(state)[0] === "cids") { return self._rpc({ model: 'res.users', method: 'read', diff --git a/addons/web/static/src/js/core/py_utils.js b/addons/web/static/src/js/core/py_utils.js index 296ab5c3089..2e673171a8f 100644 --- a/addons/web/static/src/js/core/py_utils.js +++ b/addons/web/static/src/js/core/py_utils.js @@ -89,7 +89,11 @@ function wrap_context(context) { for (var k in context) { if (!context.hasOwnProperty(k)) { continue; } var val = context[k]; - + // Don't add a test case like ``val === undefined`` + // this is intended to prevent letting crap pass + // on the context without even knowing it. + // If you face an issue from here, try to sanitize + // the context upstream instead if (val === null) { continue; } if (val.constructor === Array) { context[k] = wrapping_list.fromJSON(val); diff --git a/addons/web/static/src/js/core/session.js b/addons/web/static/src/js/core/session.js index 2874a2ea559..21103a9529a 100644 --- a/addons/web/static/src/js/core/session.js +++ b/addons/web/static/src/js/core/session.js @@ -5,6 +5,7 @@ var ajax = require('web.ajax'); var concurrency = require('web.concurrency'); var config = require('web.config'); var core = require('web.core'); +var local_storage = require('web.local_storage'); var mixins = require('web.mixins'); var utils = require('web.utils'); @@ -305,6 +306,12 @@ var Session = core.Class.extend(mixins.EventDispatcherMixin, { options.headers["X-Debug-Mode"] = $.deparam($.param.querystring()).debug; } + // we add here the user context for ALL queries, mainly to pass + // the allowed_company_ids key + if (params && params.kwargs) { + params.kwargs.context = _.extend(params.kwargs.context || {}, this.user_context); + } + // TODO: remove if (! _.isString(url)) { _.extend(options, url); @@ -359,6 +366,22 @@ var Session = core.Class.extend(mixins.EventDispatcherMixin, { }); }, + setCompanies: function (main_company_id, company_ids) { + var hash = $.bbq.getState() + hash.cids = company_ids.sort(function(a, b) { + if (a === main_company_id) { + return -1; + } else if (b === main_company_id) { + return 1; + } else { + return a - b; + } + }).join(','); + utils.set_cookie('cids', hash.cids || String(main_company_id)); + $.bbq.pushState({'cids': hash.cids}, 0); + location.reload(); + }, + //-------------------------------------------------------------------------- // Handlers //-------------------------------------------------------------------------- diff --git a/addons/web/static/src/js/services/crash_manager.js b/addons/web/static/src/js/services/crash_manager.js index a29e21ca8ca..ff699af3262 100644 --- a/addons/web/static/src/js/services/crash_manager.js +++ b/addons/web/static/src/js/services/crash_manager.js @@ -231,8 +231,12 @@ var RedirectWarningHandler = Dialog.extend(ExceptionHandler, { title: _.str.capitalize(error.type) || _t("Odoo Warning"), buttons: [ {text: error.data.arguments[2], classes : "btn-primary", click: function() { - window.location.href = '#action='+error.data.arguments[1]; + $.bbq.pushState({ + 'action': error.data.arguments[1], + 'cids': $.bbq.getState().cids, + }, 2); self.destroy(); + location.reload(); }}, {text: _t("Cancel"), click: function() { self.destroy(); }, close: true} ], diff --git a/addons/web/static/src/js/views/basic/basic_model.js b/addons/web/static/src/js/views/basic/basic_model.js index a79fabd48d6..6aa884bbacf 100644 --- a/addons/web/static/src/js/views/basic/basic_model.js +++ b/addons/web/static/src/js/views/basic/basic_model.js @@ -3423,12 +3423,20 @@ var BasicModel = AbstractModel.extend({ evalContext.parent = this._getRecordEvalContext(parent, forDomain); } } + // Uses "current_company_id" because "company_id" would conflict with all the company_id fields + // in general, the actual "company_id" field of the form should be used for m2o domains, not this fallback + if (session.user_context.allowed_company_ids) { + var current_company = session.user_context.allowed_company_ids[0]; + } else { + var current_company = session.user_companies ? session.user_companies.current_company[0] : false; + } return _.extend({ active_id: evalContext.id || false, active_ids: evalContext.id ? [evalContext.id] : [], active_model: element.model, current_date: moment().format('YYYY-MM-DD'), id: evalContext.id || false, + current_company_id: current_company, }, session.user_context, element.context, evalContext); }, /** diff --git a/addons/web/static/src/js/widgets/switch_company_menu.js b/addons/web/static/src/js/widgets/switch_company_menu.js index a389ee268cd..0939c8b1c8b 100644 --- a/addons/web/static/src/js/widgets/switch_company_menu.js +++ b/addons/web/static/src/js/widgets/switch_company_menu.js @@ -18,40 +18,48 @@ var _t = core._t; var SwitchCompanyMenu = Widget.extend({ template: 'SwitchCompanyMenu', events: { - 'click .dropdown-item[data-menu]': '_onClick', + 'click .dropdown-item[data-menu] div.log_into': '_onSwitchCompanyClick', + 'click .dropdown-item[data-menu] div.toggle_company': '_onToggleCompanyClick', }, /** * @override */ init: function () { + var self = this; this._super.apply(this, arguments); this.isMobile = config.device.isMobile; - this._onClick = _.debounce(this._onClick, 1500, true); + this._onSwitchCompanyClick = _.debounce(this._onSwitchCompanyClick, 1500, true); + this.allowed_company_ids = String(session.user_context.allowed_company_ids).split(','); + this.user_companies = session.user_companies.allowed_companies; + this.toggle_company = session.toggle_company; + + var hash = $.bbq.getState() + if (!hash.cids || hash.cids === undefined) { + hash.cids = String(session.user_companies.current_company[0]); + } + this.current_company = parseInt(hash.cids.split(',')[0]); + this.current_company_name = _.find(session.user_companies.allowed_companies, function (company) { + return company[0] === self.current_company; + })[1]; }, + + //-------------------------------------------------------------------------- + // Handlers + //-------------------------------------------------------------------------- + /** - * @override + * @private + * @param {MouseEvent} ev */ - start: function () { - var companiesList = ''; - if (this.isMobile) { - companiesList = '<li class="bg-info">' + - _t('Tap on the list to change company') + '</li>'; - } - else { - this.$('.oe_topbar_name').text(session.user_companies.current_company[1]); + _onSwitchCompanyClick: function (ev) { + ev.preventDefault(); + var companyID = $(ev.currentTarget).parent().data('company-id'); + var hash = $.bbq.getState() + var allowed_company_ids = _.map(hash.cids.split(','), function(company_id) {return parseInt(company_id);}); + if ($($(ev.currentTarget).parent()).find('.fa-square-o').length) { + allowed_company_ids.push(companyID); } - _.each(session.user_companies.allowed_companies, function(company) { - var a = ''; - if (company[0] === session.user_companies.current_company[0]) { - a = '<i class="fa fa-check mr8"></i>'; - } else { - a = '<span style="margin-right: 24px;"/>'; - } - companiesList += '<a role="menuitem" href="#" class="dropdown-item" data-menu="company" data-company-id="' + - company[0] + '">' + a + company[1] + '</a>'; - }); - this.$('.dropdown-menu').html(companiesList); - return this._super(); + session.setCompanies(companyID, [companyID]); }, //-------------------------------------------------------------------------- @@ -62,22 +70,25 @@ var SwitchCompanyMenu = Widget.extend({ * @private * @param {MouseEvent} ev */ - _onClick: function (ev) { - ev.preventDefault(); - var companyID = $(ev.currentTarget).data('company-id'); - this._rpc({ - model: 'res.users', - method: 'write', - args: [[session.uid], {'company_id': companyID}], - }) - .then(function() { - location.reload(); - }); + _onToggleCompanyClick: function (ev) { + var companyID = $(ev.currentTarget).parent().data('company-id'); + var hash = $.bbq.getState() + var allowed_company_ids = _.map(hash.cids.split(','), function(company_id) {return parseInt(company_id);}); + var current_company_id = allowed_company_ids[0]; + if ($(ev.currentTarget).find('.fa-square-o')) { + allowed_company_ids.push(companyID); + } else { + allowed_company_ids.splice(allowed_company_ids.indexOf(companyID), 1); + } + session.setCompanies(current_company_id, allowed_company_ids); }, + }); -if (session.user_companies) { + +if (session.display_switch_company_menu) { SystrayMenu.Items.push(SwitchCompanyMenu); } + return SwitchCompanyMenu; }); |
