diff options
281 files changed, 1021 insertions, 797 deletions
diff --git a/addons/account/__init__.py b/addons/account/__init__.py index 866c39de02e..1c47b94f829 100644 --- a/addons/account/__init__.py +++ b/addons/account/__init__.py @@ -13,7 +13,7 @@ SYSCOHADA_LIST = ['BJ', 'BF', 'CM', 'CF', 'KM', 'CG', 'CI', 'GA', 'GN', 'GW', 'G def _auto_install_l10n(cr, registry): #check the country of the main company (only) and eventually load some module needed in that country env = api.Environment(cr, SUPERUSER_ID, {}) - country_code = env.user.company_id.country_id.code + country_code = env.company_id.country_id.code if country_code: #auto install localization module(s) if available module_list = [] diff --git a/addons/account/controllers/onboarding.py b/addons/account/controllers/onboarding.py index 879fd0a82fc..1fd3044623b 100644 --- a/addons/account/controllers/onboarding.py +++ b/addons/account/controllers/onboarding.py @@ -10,7 +10,7 @@ class OnboardingController(http.Controller): It can be empty if the user has closed it or if he doesn't have the permission to see it. """ - company = request.env.user.company_id + company = request.env.company_id if not request.env.user._is_admin() or \ company.account_invoice_onboarding_state == 'closed': return {} @@ -27,7 +27,7 @@ class OnboardingController(http.Controller): """ Returns the `banner` for the account dashboard onboarding panel. It can be empty if the user has closed it or if he doesn't have the permission to see it. """ - company = request.env.user.company_id + company = request.env.company_id if not request.env.user._is_admin() or \ company.account_dashboard_onboarding_state == 'closed': diff --git a/addons/account/models/account.py b/addons/account/models/account.py index db5a88044a6..3453e39a2cf 100644 --- a/addons/account/models/account.py +++ b/addons/account/models/account.py @@ -91,7 +91,7 @@ class AccountAccount(models.Model): 'account_id', 'tax_id', string='Default Taxes') note = fields.Text('Internal Notes') company_id = fields.Many2one('res.company', string='Company', required=True, - default=lambda self: self.env['res.company']._company_default_get('account.account')) + default=lambda self: self.env.company_id) tag_ids = fields.Many2many('account.account.tag', 'account_account_account_tag', string='Tags', help="Optional tags you may want to assign for custom reporting") group_id = fields.Many2one('account.group') @@ -390,7 +390,7 @@ class AccountJournalGroup(models.Model): _description = "Account Journal Group" name = fields.Char(required=True, translate=True) - company_id = fields.Many2one('res.company', required=True, default=lambda self: self.env['res.company']._company_default_get('account.account')) + company_id = fields.Many2one('res.company', required=True, default=lambda self: self.env.company_id) account_journal_ids = fields.Many2many('account.journal', string="Journals") sequence = fields.Integer(default=10) @@ -457,7 +457,7 @@ class AccountJournal(models.Model): #groups_id = fields.Many2many('res.groups', 'account_journal_group_rel', 'journal_id', 'group_id', string='Groups') currency_id = fields.Many2one('res.currency', help='The currency used to enter statement', string="Currency", oldname='currency') - company_id = fields.Many2one('res.company', string='Company', required=True, index=True, default=lambda self: self.env.user.company_id, + company_id = fields.Many2one('res.company', string='Company', required=True, index=True, default=lambda self: self.env.company_id, help="Company related to this journal") refund_sequence = fields.Boolean(string='Dedicated Credit Note Sequence', help="Check this box if you don't want to share the same sequence for invoices and credit notes made from this journal", default=False) @@ -760,7 +760,7 @@ class AccountJournal(models.Model): @api.model def create(self, vals): - company_id = vals.get('company_id', self.env.user.company_id.id) + company_id = vals.get('company_id', self.env.company_id.id) if vals.get('type') in ('bank', 'cash'): # For convenience, the name can be inferred from account number if not vals.get('name') and 'bank_acc_number' in vals: @@ -832,16 +832,16 @@ class AccountJournal(models.Model): @api.depends('company_id') def _belong_to_company(self): for journal in self: - journal.belong_to_company = (journal.company_id.id == self.env.user.company_id.id) + journal.belong_to_company = (journal.company_id.id == self.env.company_id.id) @api.multi def _search_company_journals(self, operator, value): if value: - recs = self.search([('company_id', operator, self.env.user.company_id.id)]) + recs = self.search([('company_id', operator, self.env.company_id.id)]) elif operator == '=': - recs = self.search([('company_id', '!=', self.env.user.company_id.id)]) + recs = self.search([('company_id', '!=', self.env.company_id.id)]) else: - recs = self.search([('company_id', operator, self.env.user.company_id.id)]) + recs = self.search([('company_id', operator, self.env.company_id.id)]) return [('id', 'in', [x.id for x in recs])] @api.multi @@ -899,7 +899,7 @@ class AccountTax(models.Model): amount_type = fields.Selection(default='percent', string="Tax Computation", required=True, oldname='type', selection=[('group', 'Group of Taxes'), ('fixed', 'Fixed'), ('percent', 'Percentage of Price'), ('division', 'Percentage of Price Tax Included')]) active = fields.Boolean(default=True, help="Set active to false to hide the tax without removing it.") - company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company_id) children_tax_ids = fields.Many2many('account.tax', 'account_tax_filiation_rel', 'parent_tax', 'child_tax', string='Children Taxes') sequence = fields.Integer(required=True, default=1, help="The sequence field is used to define order in which the tax lines are applied.") @@ -1080,7 +1080,7 @@ class AccountTax(models.Model): }] } """ if len(self) == 0: - company_id = self.env.user.company_id + company_id = self.env.company_id else: company_id = self[0].company_id if not currency: diff --git a/addons/account/models/account_bank_statement.py b/addons/account/models/account_bank_statement.py index 487477dee6a..631a053b905 100644 --- a/addons/account/models/account_bank_statement.py +++ b/addons/account/models/account_bank_statement.py @@ -101,7 +101,7 @@ class AccountBankStatement(models.Model): @api.model def _default_journal(self): journal_type = self.env.context.get('journal_type', False) - company_id = self.env['res.company']._company_default_get('account.bank.statement').id + company_id = self.env.company_id.id if journal_type: journals = self.env['account.journal'].search([('type', '=', journal_type), ('company_id', '=', company_id)]) if journals: @@ -145,7 +145,7 @@ class AccountBankStatement(models.Model): journal_id = fields.Many2one('account.journal', string='Journal', required=True, states={'confirm': [('readonly', True)]}, default=_default_journal) journal_type = fields.Selection(related='journal_id.type', help="Technical field used for usability purposes", readonly=False) company_id = fields.Many2one('res.company', related='journal_id.company_id', string='Company', store=True, readonly=True, - default=lambda self: self.env['res.company']._company_default_get('account.bank.statement')) + default=lambda self: self.env.company_id) total_entry_encoding = fields.Monetary('Transactions Subtotal', compute='_end_balance', store=True, help="Total of transaction lines.") balance_end = fields.Monetary('Computed Balance', compute='_end_balance', store=True, help='Balance as calculated based on Opening Balance and transaction lines') diff --git a/addons/account/models/account_fiscal_year.py b/addons/account/models/account_fiscal_year.py index 8e664c2ea72..e5af53a2eb0 100644 --- a/addons/account/models/account_fiscal_year.py +++ b/addons/account/models/account_fiscal_year.py @@ -17,7 +17,7 @@ class AccountFiscalYear(models.Model): date_to = fields.Date(string='End Date', required=True, help='Ending Date, included in the fiscal year.') company_id = fields.Many2one('res.company', string='Company', required=True, - default=lambda self: self.env.user.company_id) + default=lambda self: self.env.company_id) @api.constrains('date_from', 'date_to', 'company_id') def _check_dates(self): diff --git a/addons/account/models/account_invoice.py b/addons/account/models/account_invoice.py index e639196597f..8b1e00c86ca 100644 --- a/addons/account/models/account_invoice.py +++ b/addons/account/models/account_invoice.py @@ -49,7 +49,7 @@ class AccountInvoice(models.Model): def _get_default_incoterm(self): - return self.env.user.company_id.incoterm_id + return self.env.company_id.incoterm_id @api.one @api.depends('invoice_line_ids.price_subtotal', 'tax_line_ids.amount', 'tax_line_ids.amount_rounding', @@ -82,7 +82,7 @@ class AccountInvoice(models.Model): return self.env['account.journal'].browse(self._context.get('default_journal_id')) inv_type = self._context.get('type', 'out_invoice') inv_types = inv_type if isinstance(inv_type, list) else [inv_type] - company_id = self._context.get('company_id', self.env.user.company_id.id) + company_id = self._context.get('company_id', self.env.company_id.id) domain = [ ('type', 'in', [TYPE2JOURNAL[ty] for ty in inv_types if ty in TYPE2JOURNAL]), ('company_id', '=', company_id), @@ -96,12 +96,12 @@ class AccountInvoice(models.Model): @api.model def _default_currency(self): journal = self._default_journal() - return journal.currency_id or journal.company_id.currency_id or self.env.user.company_id.currency_id + return journal.currency_id or journal.company_id.currency_id or self.env.company_id.currency_id def _default_comment(self): invoice_type = self.env.context.get('type', 'out_invoice') if invoice_type == 'out_invoice' and self.env['ir.config_parameter'].sudo().get_param('account.use_invoice_terms'): - return self.env.user.company_id.invoice_terms + return self.env.company_id.invoice_terms def _get_aml_for_amount_residual(self): """ Get the aml to consider to compute the amount residual of invoices """ @@ -367,7 +367,7 @@ class AccountInvoice(models.Model): domain="[('type', 'in', {'out_invoice': ['sale'], 'out_refund': ['sale'], 'in_refund': ['purchase'], 'in_invoice': ['purchase']}.get(type, [])), ('company_id', '=', company_id)]") company_id = fields.Many2one('res.company', string='Company', change_default=True, required=True, readonly=True, states={'draft': [('readonly', False)]}, - default=lambda self: self.env['res.company']._company_default_get('account.invoice')) + default=lambda self: self.env.company_id) reconciled = fields.Boolean(string='Paid/Reconciled', store=True, readonly=True, compute='_compute_residual', help="It indicates that the invoice has been paid and the journal entry of the invoice has been reconciled with one or several journal entries of payment.") @@ -734,7 +734,7 @@ class AccountInvoice(models.Model): def message_post(self, **kwargs): if self.env.context.get('mark_invoice_as_sent'): self.filtered(lambda inv: not inv.sent).write({'sent': True}) - self.env.user.company_id.set_onboarding_step_done('account_onboarding_sample_invoice_state') + self.env.company_id.set_onboarding_step_done('account_onboarding_sample_invoice_state') return super(AccountInvoice, self.with_context(mail_post_autofollow=True)).message_post(**kwargs) @api.model @@ -1746,7 +1746,7 @@ class AccountInvoiceLine(models.Model): if self.invoice_id.currency_id and self.invoice_id.currency_id != self.invoice_id.company_id.currency_id: currency = self.invoice_id.currency_id date = self.invoice_id._get_currency_rate_date() - price_subtotal_signed = currency._convert(price_subtotal_signed, self.invoice_id.company_id.currency_id, self.company_id or self.env.user.company_id, date or fields.Date.today()) + price_subtotal_signed = currency._convert(price_subtotal_signed, self.invoice_id.company_id.currency_id, self.company_id or self.env.company_id, date or fields.Date.today()) sign = self.invoice_id.type in ['in_refund', 'out_refund'] and -1 or 1 self.price_subtotal_signed = price_subtotal_signed * sign @@ -1848,7 +1848,7 @@ class AccountInvoiceLine(models.Model): taxes = self.product_id.supplier_taxes_id or self.account_id.tax_ids or self.invoice_id.company_id.account_purchase_tax_id # Keep only taxes of the company - company_id = self.company_id or self.env.user.company_id + company_id = self.company_id or self.env.company_id taxes = taxes.filtered(lambda r: r.company_id == company_id) self.invoice_line_tax_ids = fp_taxes = self.invoice_id.fiscal_position_id.map_tax(taxes, self.product_id, self.invoice_id.partner_id) diff --git a/addons/account/models/account_journal_dashboard.py b/addons/account/models/account_journal_dashboard.py index 11306b4a5a6..afb4e24c059 100644 --- a/addons/account/models/account_journal_dashboard.py +++ b/addons/account/models/account_journal_dashboard.py @@ -281,7 +281,7 @@ class account_journal(models.Model): curr_cache = {} if curr_cache is None else curr_cache for result in results_dict: cur = self.env['res.currency'].browse(result.get('currency')) - company = self.env['res.company'].browse(result.get('company_id')) or self.env.user.company_id + company = self.env['res.company'].browse(result.get('company_id')) or self.env.company_id rslt_count += 1 date = result.get('date_invoice') or fields.Date.today() diff --git a/addons/account/models/account_move.py b/addons/account/models/account_move.py index eaa18ec5e4d..a5d60435ff1 100644 --- a/addons/account/models/account_move.py +++ b/addons/account/models/account_move.py @@ -26,7 +26,7 @@ class AccountMove(models.Model): def default_get(self, fields): rec = super(AccountMove, self).default_get(fields) if not rec.get('journal_id'): - rec.update({'journal_id': self.env['account.journal'].search([('type', '=', 'general'), ('company_id', '=', self.env.user.company_id.id)], limit=1).id}) + rec.update({'journal_id': self.env['account.journal'].search([('type', '=', 'general'), ('company_id', '=', self.env.company_id.id)], limit=1).id}) return rec @api.multi @@ -90,12 +90,12 @@ class AccountMove(models.Model): @api.one @api.depends('company_id') def _compute_currency(self): - self.currency_id = self.company_id.currency_id or self.env.user.company_id.currency_id + self.currency_id = self.company_id.currency_id or self.env.company_id.currency_id @api.multi def _get_default_journal(self): if self.env.context.get('default_journal_type'): - return self.env['account.journal'].search([('company_id', '=', self.env.user.company_id.id), ('type', '=', self.env.context['default_journal_type'])], limit=1).id + return self.env['account.journal'].search([('company_id', '=', self.env.company_id.id), ('type', '=', self.env.context['default_journal_type'])], limit=1).id @api.multi @api.depends('line_ids.partner_id') @@ -402,7 +402,7 @@ class AccountMove(models.Model): def assert_balanced(self): if not self.ids: return True - prec = self.env.user.company_id.currency_id.decimal_places + prec = self.env.company_id.currency_id.decimal_places self._cr.execute("""\ SELECT move_id @@ -484,7 +484,7 @@ class AccountMove(models.Model): ('reverse_entry_id', '=', False)]) for move in records: date = None - if move.reverse_date and (not self.env.user.company_id.period_lock_date or move.reverse_date > self.env.user.company_id.period_lock_date): + if move.reverse_date and (not self.env.company_id.period_lock_date or move.reverse_date > self.env.company_id.period_lock_date): date = move.reverse_date move.reverse_moves(date=date, auto=True) @@ -1348,7 +1348,7 @@ class AccountMoveLine(models.Model): currency_id = False date = self.env.context.get('date') or fields.Date.today() company = self.env.context.get('company_id') - company = self.env['res.company'].browse(company) if company else self.env.user.company_id + company = self.env['res.company'].browse(company) if company else self.env.company_id if src_currency and src_currency != company_currency: amount_currency = amount amount = src_currency._convert(amount, company_currency, company, date) @@ -1404,7 +1404,7 @@ class AccountMoveLine(models.Model): 'move_id': move_line.id, 'user_id': move_line.invoice_id.user_id.id or self._uid, 'partner_id': move_line.partner_id.id, - 'company_id': move_line.analytic_account_id.company_id.id or self.env.user.company_id.id, + 'company_id': move_line.analytic_account_id.company_id.id or self.env.company_id.id, }) return result @@ -1429,7 +1429,7 @@ class AccountMoveLine(models.Model): 'ref': self.ref, 'move_id': self.id, 'user_id': self.invoice_id.user_id.id or self._uid, - 'company_id': distribution.account_id.company_id.id or self.env.user.company_id.id, + 'company_id': distribution.account_id.company_id.id or self.env.company_id.id, } @api.model diff --git a/addons/account/models/account_payment.py b/addons/account/models/account_payment.py index baca985def8..bc20a820c9b 100644 --- a/addons/account/models/account_payment.py +++ b/addons/account/models/account_payment.py @@ -72,7 +72,7 @@ class account_payment(models.Model): partner_id = fields.Many2one('res.partner', string='Partner', tracking=True, readonly=True, states={'draft': [('readonly', False)]}) amount = fields.Monetary(string='Payment Amount', required=True, readonly=True, states={'draft': [('readonly', False)]}, tracking=True) - currency_id = fields.Many2one('res.currency', string='Currency', required=True, readonly=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env.user.company_id.currency_id) + currency_id = fields.Many2one('res.currency', string='Currency', required=True, readonly=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env.company_id.currency_id) payment_date = fields.Date(string='Payment Date', default=fields.Date.context_today, required=True, readonly=True, states={'draft': [('readonly', False)]}, copy=False, tracking=True) communication = fields.Char(string='Memo', readonly=True, states={'draft': [('readonly', False)]}) journal_id = fields.Many2one('account.journal', string='Payment Journal', required=True, readonly=True, states={'draft': [('readonly', False)]}, tracking=True, domain=[('type', 'in', ('bank', 'cash'))]) @@ -304,7 +304,7 @@ class account_payment(models.Model): if payment_currency == currency: total += amount_total else: - total += payment_currency._convert(amount_total, currency, self.env.user.company_id, self.payment_date or fields.Date.today()) + total += payment_currency._convert(amount_total, currency, self.env.company_id, self.payment_date or fields.Date.today()) return total @api.multi @@ -693,7 +693,7 @@ class payment_register(models.TransientModel): if 'invoice_ids' not in rec: rec['invoice_ids'] = [(6, 0, invoices.ids)] if 'journal_id' not in rec: - rec['journal_id'] = self.env['account.journal'].search([('company_id', '=', self.env.user.company_id.id), ('type', 'in', ('bank', 'cash'))], limit=1).id + rec['journal_id'] = self.env['account.journal'].search([('company_id', '=', self.env.company_id.id), ('type', 'in', ('bank', 'cash'))], limit=1).id if 'payment_method_id' not in rec: if invoices[0].type in ('out_invoice', 'in_refund'): domain = [('payment_type', '=', 'inbound')] diff --git a/addons/account/models/account_payment_term.py b/addons/account/models/account_payment_term.py index 05e06310c16..4756b1ec22c 100644 --- a/addons/account/models/account_payment_term.py +++ b/addons/account/models/account_payment_term.py @@ -42,7 +42,7 @@ class AccountPaymentTerm(models.Model): if self.env.context.get('currency_id'): currency = self.env['res.currency'].browse(self.env.context['currency_id']) else: - currency = self.env.user.company_id.currency_id + currency = self.env.company_id.currency_id for line in self.line_ids: if line.value == 'fixed': amt = sign * currency.round(line.value_amount) diff --git a/addons/account/models/account_reconcile_model.py b/addons/account/models/account_reconcile_model.py index 5ab6865831a..53280b2732f 100644 --- a/addons/account/models/account_reconcile_model.py +++ b/addons/account/models/account_reconcile_model.py @@ -13,7 +13,7 @@ class AccountReconcileModel(models.Model): # Base fields. name = fields.Char(string='Name', required=True) sequence = fields.Integer(required=True, default=10) - company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company_id) rule_type = fields.Selection(selection=[ ('writeoff_button', _('Manually create a write-off on clicked button.')), diff --git a/addons/account/models/chart_template.py b/addons/account/models/chart_template.py index dc339adc005..55dec0dfae2 100644 --- a/addons/account/models/chart_template.py +++ b/addons/account/models/chart_template.py @@ -165,13 +165,10 @@ class AccountChartTemplate(models.Model): """ self.ensure_one() # do not use `request.env` here, it can cause deadlocks - if request and request.session.uid: - current_user = self.env['res.users'].browse(request.uid) - company = current_user.company_id + if request and 'allowed_company_ids' in dir(request): + company = self.env['res.company'].browse(request.allowed_company_ids[0]) else: - # fallback to company of current user, most likely __system__ - # (won't work well for multi-company) - company = self.env.user.company_id + company = self.env.company_id # If we don't have any chart of account on this company, install this chart of account if not company.chart_template_id and not self.existing_accounting(company): self.load_for_current_company(15.0, 15.0) @@ -186,13 +183,10 @@ class AccountChartTemplate(models.Model): """ self.ensure_one() # do not use `request.env` here, it can cause deadlocks - if request and request.session.uid: - current_user = self.env['res.users'].browse(request.uid) - company = current_user.company_id + if request and 'allowed_company_ids' in dir(request): + company = self.env['res.company'].browse(request.allowed_company_ids[0]) else: - # fallback to company of current user, most likely __system__ - # (won't work well for multi-company) - company = self.env.user.company_id + company = self.env.company_id # Ensure everything is translated to the company's language, not the user's one. self = self.with_context(lang=company.partner_id.lang) if not self.env.user._is_admin(): diff --git a/addons/account/models/company.py b/addons/account/models/company.py index abff7bbd861..093730ebf31 100644 --- a/addons/account/models/company.py +++ b/addons/account/models/company.py @@ -313,7 +313,7 @@ Best Regards,''')) @api.model def setting_init_fiscal_year_action(self): """ Called by the 'Fiscal Year Opening' button of the setup bar.""" - company = self.env.user.company_id + company = self.env.company_id company.create_op_move_if_non_existant() new_wizard = self.env['account.financial.year.op'].create({'company_id': company.id}) view_id = self.env.ref('account.setup_financial_year_opening_form').id @@ -331,7 +331,7 @@ Best Regards,''')) @api.model def setting_chart_of_accounts_action(self): """ Called by the 'Chart of Accounts' button of the setup bar.""" - company = self.env.user.company_id + company = self.env.company_id company.set_onboarding_step_done('account_setup_coa_state') # If an opening move has already been posted, we open the tree view showing all the accounts @@ -455,25 +455,25 @@ Best Regards,''')) @api.model def action_close_account_invoice_onboarding(self): """ Mark the invoice onboarding panel as closed. """ - self.env.user.company_id.account_invoice_onboarding_state = 'closed' + self.env.company_id.account_invoice_onboarding_state = 'closed' @api.model def action_close_account_dashboard_onboarding(self): """ Mark the dashboard onboarding panel as closed. """ - self.env.user.company_id.account_dashboard_onboarding_state = 'closed' + self.env.company_id.account_dashboard_onboarding_state = 'closed' @api.model def action_open_account_onboarding_invoice_layout(self): """ Onboarding step for the invoice layout. """ action = self.env.ref('account.action_open_account_onboarding_invoice_layout').read()[0] - action['res_id'] = self.env.user.company_id.id + action['res_id'] = self.env.company_id.id return action @api.model def action_open_account_onboarding_sale_tax(self): """ Onboarding step for the invoice layout. """ action = self.env.ref('account.action_open_account_onboarding_sale_tax').read()[0] - action['res_id'] = self.env.user.company_id.id + action['res_id'] = self.env.company_id.id return action @api.model @@ -482,7 +482,7 @@ Best Regards,''')) # use current user as partner partner = self.env.user.partner_id - company_id = self.env.user.company_id.id + company_id = self.env.company_id.id # try to find an existing sample invoice sample_invoice = self.env['account.invoice'].search( [('company_id', '=', company_id), @@ -490,7 +490,7 @@ Best Regards,''')) if len(sample_invoice) == 0: # If there are no existing accounts or no journal, fail - account = self.env.user.company_id.get_chart_of_accounts_or_fail() + account = self.env.company_id.get_chart_of_accounts_or_fail() journal = self.env['account.journal'].search([('company_id', '=', company_id)], limit=1) if len(journal) == 0: diff --git a/addons/account/models/partner.py b/addons/account/models/partner.py index 85ec5f9bb66..b5df07cf8f5 100644 --- a/addons/account/models/partner.py +++ b/addons/account/models/partner.py @@ -204,7 +204,7 @@ class ResPartner(models.Model): @api.multi def _credit_debit_get(self): - tables, where_clause, where_params = self.env['account.move.line'].with_context(company_id=self.env.user.company_id.id)._query_get() + tables, where_clause, where_params = self.env['account.move.line'].with_context(company_id=self.env.company_id.id)._query_get() where_params = [tuple(self.ids)] + where_params if where_clause: where_clause = 'AND ' + where_clause @@ -263,7 +263,7 @@ class ResPartner(models.Model): self.total_invoiced = 0.0 return True - user_currency_id = self.env.user.company_id.currency_id.id + user_currency_id = self.env.company_id.currency_id.id all_partners_and_children = {} all_partner_ids = [] for partner in self: @@ -309,7 +309,7 @@ class ResPartner(models.Model): partner.contracts_count = AccountAnalyticAccount.search_count([('partner_id', '=', partner.id)]) def get_followup_lines_domain(self, date, overdue_only=False, only_unblocked=False): - domain = [('reconciled', '=', False), ('account_id.deprecated', '=', False), ('account_id.internal_type', '=', 'receivable'), '|', ('debit', '!=', 0), ('credit', '!=', 0), ('company_id', '=', self.env.user.company_id.id)] + domain = [('reconciled', '=', False), ('account_id.deprecated', '=', False), ('account_id.internal_type', '=', 'receivable'), '|', ('debit', '!=', 0), ('credit', '!=', 0), ('company_id', '=', self.env.company_id.id)] if only_unblocked: domain += [('blocked', '=', False)] if self.ids: @@ -362,14 +362,14 @@ class ResPartner(models.Model): @api.multi def mark_as_reconciled(self): self.env['account.partial.reconcile'].check_access_rights('write') - return self.sudo().with_context(company_id=self.env.user.company_id.id).write({'last_time_entries_checked': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) + return self.sudo().with_context(company_id=self.env.company_id.id).write({'last_time_entries_checked': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) @api.one def _get_company_currency(self): if self.company_id: self.currency_id = self.sudo().company_id.currency_id else: - self.currency_id = self.env.user.company_id.currency_id + self.currency_id = self.env.company_id.currency_id credit = fields.Monetary(compute='_credit_debit_get', search=_credit_search, string='Total Receivable', help="Total amount this customer owes you.") @@ -448,7 +448,7 @@ class ResPartner(models.Model): if self.company_id: company = self.company_id else: - company = self.env.user.company_id + company = self.env.company_id return {'domain': {'property_account_position_id': [('company_id', 'in', [company.id, False])]}} def can_edit_vat(self): diff --git a/addons/account/models/product.py b/addons/account/models/product.py index 43ea3d90b7a..ec818721697 100644 --- a/addons/account/models/product.py +++ b/addons/account/models/product.py @@ -23,9 +23,9 @@ class ProductTemplate(models.Model): _inherit = "product.template" taxes_id = fields.Many2many('account.tax', 'product_taxes_rel', 'prod_id', 'tax_id', help="Default taxes used when selling the product.", string='Customer Taxes', - domain=[('type_tax_use', '=', 'sale')], default=lambda self: self.env.user.company_id.account_sale_tax_id) + domain=[('type_tax_use', '=', 'sale')], default=lambda self: self.env.company_id.account_sale_tax_id) supplier_taxes_id = fields.Many2many('account.tax', 'product_supplier_taxes_rel', 'prod_id', 'tax_id', string='Vendor Taxes', help='Default taxes used when buying the product.', - domain=[('type_tax_use', '=', 'purchase')], default=lambda self: self.env.user.company_id.account_purchase_tax_id) + domain=[('type_tax_use', '=', 'purchase')], default=lambda self: self.env.company_id.account_purchase_tax_id) property_account_income_id = fields.Many2one('account.account', company_dependent=True, string="Income Account", oldname="property_account_income", domain=[('deprecated', '=', False)], diff --git a/addons/account/models/reconciliation_widget.py b/addons/account/models/reconciliation_widget.py index 4683afab86f..0e267d706ed 100644 --- a/addons/account/models/reconciliation_widget.py +++ b/addons/account/models/reconciliation_widget.py @@ -361,7 +361,7 @@ class AccountReconciliation(models.AbstractModel): is_partner and ' ' or "AND at.type <> 'payable' AND at.type <> 'receivable'", account_type and "AND at.type = %(account_type)s" or '', res_ids and 'AND ' + res_alias + '.id in %(res_ids)s' or '', - self.env.user.company_id.id, + self.env.company_id.id, is_partner and 'AND l.partner_id = p.id' or ' ', aml_ids and 'AND l.id IN %(aml_ids)s' or '', is_partner and 'l.partner_id, p.id,' or ' ', diff --git a/addons/account/models/res_config_settings.py b/addons/account/models/res_config_settings.py index 0e0ac37ae44..c54dc0b2f3a 100644 --- a/addons/account/models/res_config_settings.py +++ b/addons/account/models/res_config_settings.py @@ -142,7 +142,7 @@ class ResConfigSettings(models.TransientModel): def _onchange_tax_exigibility(self): res = {} tax = self.env['account.tax'].search([ - ('company_id', '=', self.env.user.company_id.id), ('tax_exigibility', '=', 'on_payment') + ('company_id', '=', self.env.company_id.id), ('tax_exigibility', '=', 'on_payment') ], limit=1) if not self.tax_exigibility and tax: self.tax_exigibility = True diff --git a/addons/account/report/account_aged_partner_balance.py b/addons/account/report/account_aged_partner_balance.py index 08d0b976263..36070e760b7 100644 --- a/addons/account/report/account_aged_partner_balance.py +++ b/addons/account/report/account_aged_partner_balance.py @@ -46,7 +46,7 @@ class ReportAgedPartnerBalance(models.AbstractModel): total = [] partner_clause = '' cr = self.env.cr - user_company = self.env.user.company_id + user_company = self.env.company_id user_currency = user_company.currency_id company_ids = self._context.get('company_ids') or [user_company.id] move_state = ['draft', 'posted'] @@ -140,7 +140,7 @@ class ReportAgedPartnerBalance(models.AbstractModel): if partial_line.max_date <= date_from: line_amount -= partial_line.company_id.currency_id._convert(partial_line.amount, user_currency, user_company, date_from) - if not self.env.user.company_id.currency_id.is_zero(line_amount): + if not self.env.company_id.currency_id.is_zero(line_amount): partners_amount[partner_id] += line_amount lines.setdefault(partner_id, []) lines[partner_id].append({ @@ -178,7 +178,7 @@ class ReportAgedPartnerBalance(models.AbstractModel): for partial_line in line.matched_credit_ids: if partial_line.max_date <= date_from: line_amount -= partial_line.company_id.currency_id._convert(partial_line.amount, user_currency, user_company, date_from) - if not self.env.user.company_id.currency_id.is_zero(line_amount): + if not self.env.company_id.currency_id.is_zero(line_amount): undue_amounts[partner_id] += line_amount lines.setdefault(partner_id, []) lines[partner_id].append({ @@ -198,7 +198,7 @@ class ReportAgedPartnerBalance(models.AbstractModel): total[6] = total[6] + undue_amt values['direction'] = undue_amt - if not float_is_zero(values['direction'], precision_rounding=self.env.user.company_id.currency_id.rounding): + if not float_is_zero(values['direction'], precision_rounding=self.env.company_id.currency_id.rounding): at_least_one_amount = True for i in range(5): @@ -208,7 +208,7 @@ class ReportAgedPartnerBalance(models.AbstractModel): # Adding counter total[(i)] = total[(i)] + (during and during[0] or 0) values[str(i)] = during and during[0] or 0.0 - if not float_is_zero(values[str(i)], precision_rounding=self.env.user.company_id.currency_id.rounding): + if not float_is_zero(values[str(i)], precision_rounding=self.env.company_id.currency_id.rounding): at_least_one_amount = True values['total'] = sum([values['direction']] + [values[str(i)] for i in range(5)]) ## Add for total diff --git a/addons/account/report/account_invoice_report.py b/addons/account/report/account_invoice_report.py index 7861644525a..e431a183259 100644 --- a/addons/account/report/account_invoice_report.py +++ b/addons/account/report/account_invoice_report.py @@ -15,10 +15,10 @@ class AccountInvoiceReport(models.Model): def _compute_amounts_in_user_currency(self): """Compute the amounts in the currency of the user """ - user_currency_id = self.env.user.company_id.currency_id + user_currency_id = self.env.company_id.currency_id currency_rate_id = self.env['res.currency.rate'].search([ ('rate', '=', 1), - '|', ('company_id', '=', self.env.user.company_id.id), ('company_id', '=', False)], limit=1) + '|', ('company_id', '=', self.env.company_id.id), ('company_id', '=', False)], limit=1) base_currency_id = currency_rate_id.currency_id for record in self: date = record.date or fields.Date.today() diff --git a/addons/account/security/account_security.xml b/addons/account/security/account_security.xml index bad495b9290..16be4f2d247 100644 --- a/addons/account/security/account_security.xml +++ b/addons/account/security/account_security.xml @@ -86,104 +86,104 @@ <field name="name">Account Entry</field> <field name="model_id" ref="model_account_move"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="account_move_line_comp_rule" model="ir.rule"> <field name="name">Entry lines</field> <field name="model_id" ref="model_account_move_line"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="journal_comp_rule" model="ir.rule"> <field name="name">Journal multi-company</field> <field name="model_id" ref="model_account_journal_group"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="journal_comp_rule" model="ir.rule"> <field name="name">Journal multi-company</field> <field name="model_id" ref="model_account_journal"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="account_comp_rule" model="ir.rule"> <field name="name">Account multi-company</field> <field name="model_id" ref="model_account_account"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="tax_comp_rule" model="ir.rule"> <field name="name">Tax multi-company</field> <field name="model_id" ref="model_account_tax"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="invoice_comp_rule" model="ir.rule"> <field name="name">Invoice multi-company</field> <field name="model_id" ref="model_account_invoice"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="invoice_analysis_comp_rule" model="ir.rule"> <field name="name">Invoice Analysis multi-company</field> <field name="model_id" ref="model_account_invoice_report"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="account_fiscal_position_comp_rule" model="ir.rule"> <field name="name">Account fiscal Mapping company rule</field> <field name="model_id" ref="model_account_fiscal_position"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="account_invoice_line_comp_rule"> <field name="name">Invoice Line company rule</field> <field name="model_id" ref="model_account_invoice_line"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="account_bank_statement_comp_rule"> <field name="name">Account bank statement company rule</field> <field name="model_id" ref="model_account_bank_statement"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="account_bank_statement_line_comp_rule"> <field name="name">Account bank statement line company rule</field> <field name="model_id" ref="model_account_bank_statement_line"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="account_reconcile_model_template_comp_rule"> <field name="name">Account reconcile model template company rule</field> <field name="model_id" ref="model_account_reconcile_model"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="account_payment_comp_rule"> <field name="name">Account payment company rule</field> <field name="model_id" ref="model_account_payment"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="account_payment_term_comp_rule"> <field name="name">Account payment term company rule</field> <field name="model_id" ref="model_account_payment_term"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <!-- Portal for invoice and invoice lines --> diff --git a/addons/account/tests/account_test_classes.py b/addons/account/tests/account_test_classes.py index f8f33356da4..57441be8652 100644 --- a/addons/account/tests/account_test_classes.py +++ b/addons/account/tests/account_test_classes.py @@ -27,7 +27,7 @@ class AccountingTestCase(HttpCase): :param property_name: The name of the property. ''' - company_id = self.env.user.company_id + company_id = self.env.company_id field_id = self.env['ir.model.fields'].search( [('model', '=', 'product.template'), ('name', '=', property_name)], limit=1) property_id = self.env['ir.property'].search([ diff --git a/addons/account/tests/test_account_all_l10n.py b/addons/account/tests/test_account_all_l10n.py index b8a6e5811b7..23fb0616a64 100644 --- a/addons/account/tests/test_account_all_l10n.py +++ b/addons/account/tests/test_account_all_l10n.py @@ -40,5 +40,5 @@ class TestAllL10n(SingleTransactionCase): comp = self.env['res.company'].create({ 'name': cname, }) - self.env.user.company_id = comp + self.env.company_id = comp coa.try_loading_for_current_company() diff --git a/addons/account/tests/test_account_customer_invoice.py b/addons/account/tests/test_account_customer_invoice.py index 03ca61aecf5..b3fe591092b 100644 --- a/addons/account/tests/test_account_customer_invoice.py +++ b/addons/account/tests/test_account_customer_invoice.py @@ -108,7 +108,7 @@ class TestAccountCustomerInvoice(AccountTestUsers): def test_customer_invoice_tax(self): - self.env.user.company_id.tax_calculation_rounding_method = 'round_globally' + self.env.company_id.tax_calculation_rounding_method = 'round_globally' payment_term = self.env.ref('account.account_payment_term_advance') journalrec = self.env['account.journal'].search([('type', '=', 'sale')])[0] @@ -169,7 +169,7 @@ class TestAccountCustomerInvoice(AccountTestUsers): self.assertEquals(invoice.amount_untaxed, sum([x.base for x in invoice.tax_line_ids])) def test_customer_invoice_tax_refund(self): - company = self.env.user.company_id + company = self.env.company_id tax_account = self.env['account.account'].create({ 'name': 'TAX', 'code': 'TAX', diff --git a/addons/account/tests/test_bank_statement_reconciliation.py b/addons/account/tests/test_bank_statement_reconciliation.py index 0311f278a4b..dd3554839fb 100644 --- a/addons/account/tests/test_bank_statement_reconciliation.py +++ b/addons/account/tests/test_bank_statement_reconciliation.py @@ -70,7 +70,7 @@ class TestBankStatementReconciliation(AccountingTestCase): vals = {'partner_id': self.partner.id, 'type': 'out_invoice', 'name': '-', - 'currency_id': self.env.user.company_id.currency_id.id, + 'currency_id': self.env.company_id.currency_id.id, } # new creates a temporary record to apply the on_change afterwards invoice = self.i_model.new(vals) diff --git a/addons/account/tests/test_reconciliation.py b/addons/account/tests/test_reconciliation.py index 0fc4c2bc7dd..c3064a03b32 100644 --- a/addons/account/tests/test_reconciliation.py +++ b/addons/account/tests/test_reconciliation.py @@ -912,7 +912,7 @@ class TestReconciliationExec(TestReconciliation): account_type = ['receivable'] report_date_to = time.strftime('%Y') + '-07-17' partner = self.env['res.partner'].create({'name': 'AgedPartner'}) - currency = self.env.user.company_id.currency_id + currency = self.env.company_id.currency_id invoice = self.create_invoice_partner(currency_id=currency.id, partner_id=partner.id) journal = self.env['account.journal'].create({'name': 'Bank', 'type': 'bank', 'code': 'THE'}) @@ -1021,7 +1021,7 @@ class TestReconciliationExec(TestReconciliation): AgedReport = self.env['report.account.report_agedpartnerbalance'].with_context(include_nullified_amount=True) account_type = ['receivable'] partner = self.env['res.partner'].create({'name': 'AgedPartner'}) - currency = self.env.user.company_id.currency_id + currency = self.env.company_id.currency_id invoice = self.create_invoice_partner(currency_id=currency.id, partner_id=partner.id) journal = self.env['account.journal'].create({'name': 'Bank', 'type': 'bank', 'code': 'THE'}) @@ -1523,7 +1523,7 @@ class TestReconciliationExec(TestReconciliation): def test_reconciliation_to_check(self): partner = self.env['res.partner'].create({'name': 'UncertainPartner'}) - currency = self.env.user.company_id.currency_id + currency = self.env.company_id.currency_id invoice = self.create_invoice_partner(currency_id=currency.id, partner_id=partner.id) journal = self.env['account.journal'].create({'name': 'Bank', 'type': 'bank', 'code': 'THE', 'update_posted':True}) diff --git a/addons/account/wizard/account_invoice_send.py b/addons/account/wizard/account_invoice_send.py index 54fbd7ff4be..5525b908af3 100644 --- a/addons/account/wizard/account_invoice_send.py +++ b/addons/account/wizard/account_invoice_send.py @@ -10,8 +10,8 @@ class AccountInvoiceSend(models.TransientModel): _inherits = {'mail.compose.message':'composer_id'} _description = 'Account Invoice Send' - is_email = fields.Boolean('Email', default=lambda self: self.env.user.company_id.invoice_is_email) - is_print = fields.Boolean('Print', default=lambda self: self.env.user.company_id.invoice_is_print) + is_email = fields.Boolean('Email', default=lambda self: self.env.company_id.invoice_is_email) + is_print = fields.Boolean('Print', default=lambda self: self.env.company_id.invoice_is_print) printed = fields.Boolean('Is Printed', default=False) invoice_ids = fields.Many2many('account.invoice', 'account_invoice_account_invoice_send_rel', string='Invoices') composer_id = fields.Many2one('mail.compose.message', string='Composer', required=True, ondelete='cascade') diff --git a/addons/account/wizard/account_report_common.py b/addons/account/wizard/account_report_common.py index f5e5814c814..8e3ecee1700 100644 --- a/addons/account/wizard/account_report_common.py +++ b/addons/account/wizard/account_report_common.py @@ -7,7 +7,7 @@ class AccountCommonReport(models.TransientModel): _name = "account.common.report" _description = "Account Common Report" - company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company_id) journal_ids = fields.Many2many('account.journal', string='Journals', required=True, default=lambda self: self.env['account.journal'].search([('company_id', '=', self.company_id.id)])) date_from = fields.Date(string='Start Date') date_to = fields.Date(string='End Date') diff --git a/addons/account/wizard/setup_wizards.py b/addons/account/wizard/setup_wizards.py index cb4820d4a0f..88b1f5b5657 100644 --- a/addons/account/wizard/setup_wizards.py +++ b/addons/account/wizard/setup_wizards.py @@ -42,7 +42,7 @@ class FinancialYearOpeningWizard(models.TransientModel): @api.multi def action_save_onboarding_fiscal_year(self): - self.env.user.company_id.set_onboarding_step_done('account_setup_fy_data_state') + self.env.company_id.set_onboarding_step_done('account_setup_fy_data_state') class SetupBarBankConfigWizard(models.TransientModel): @@ -71,7 +71,7 @@ class SetupBarBankConfigWizard(models.TransientModel): def _onchange_new_journal_code(self): for record in self: if not record.linked_journal_id: - record.new_journal_code = self.env['account.journal'].get_next_bank_cash_default_code('bank', self.env['res.company']._company_default_get('account.journal').id) + record.new_journal_code = self.env['account.journal'].get_next_bank_cash_default_code('bank', self.env.company_id.id) else: record.new_journal_code = self.linked_journal_id.code @@ -81,7 +81,7 @@ class SetupBarBankConfigWizard(models.TransientModel): company, so we always inject the corresponding partner when creating the model. """ - vals['partner_id'] = self.env.user.company_id.partner_id.id + vals['partner_id'] = self.env.company_id.partner_id.id return super(SetupBarBankConfigWizard, self).create(vals) @api.onchange('linked_journal_id') @@ -105,7 +105,7 @@ class SetupBarBankConfigWizard(models.TransientModel): for record in self: selected_journal = record.linked_journal_id if record.num_journals_without_account == 0: - company = self.env['res.company']._company_default_get('account.journal') + company = self.env.company_id selected_journal = self.env['account.journal'].create({ 'name': record.new_journal_name, 'code': record.new_journal_code, diff --git a/addons/account/wizard/wizard_tax_adjustments.py b/addons/account/wizard/wizard_tax_adjustments.py index 91a0edc7cf4..2ebae475fe4 100644 --- a/addons/account/wizard/wizard_tax_adjustments.py +++ b/addons/account/wizard/wizard_tax_adjustments.py @@ -19,7 +19,7 @@ class TaxAdjustments(models.TransientModel): credit_account_id = fields.Many2one('account.account', string='Credit account', required=True, domain=[('deprecated', '=', False)]) amount = fields.Monetary(currency_field='company_currency_id', required=True) adjustment_type = fields.Selection([('debit', 'Applied on debit journal item'), ('credit', 'Applied on credit journal item')], string="Adjustment Type", store=False, required=True) - company_currency_id = fields.Many2one('res.currency', readonly=True, default=lambda self: self.env.user.company_id.currency_id) + company_currency_id = fields.Many2one('res.currency', readonly=True, default=lambda self: self.env.company_id.currency_id) tax_id = fields.Many2one('account.tax', string='Adjustment Tax', ondelete='restrict', domain=[('type_tax_use', '=', 'adjustment')], required=True) @api.multi diff --git a/addons/account_analytic_default/security/account_analytic_default_security.xml b/addons/account_analytic_default/security/account_analytic_default_security.xml index 5183a7fb2d9..513146cd564 100644 --- a/addons/account_analytic_default/security/account_analytic_default_security.xml +++ b/addons/account_analytic_default/security/account_analytic_default_security.xml @@ -6,7 +6,7 @@ <field name="name">Analytic Default multi company rule</field> <field name="model_id" ref="model_account_analytic_default"/> <field eval="True" name="global"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> </data> diff --git a/addons/account_bank_statement_import/account_bank_statement_import.py b/addons/account_bank_statement_import/account_bank_statement_import.py index 34ac575431c..6a4ef086808 100644 --- a/addons/account_bank_statement_import/account_bank_statement_import.py +++ b/addons/account_bank_statement_import/account_bank_statement_import.py @@ -129,7 +129,7 @@ class AccountBankStatementImport(models.TransientModel): """ Look for a res.currency and account.journal using values extracted from the statement and make sure it's consistent. """ - company_currency = self.env.user.company_id.currency_id + company_currency = self.env.company_id.currency_id journal_obj = self.env['account.journal'] currency = None sanitized_account_number = sanitize_account_number(account_number) diff --git a/addons/account_facturx/models/account_invoice.py b/addons/account_facturx/models/account_invoice.py index 50dc6f29c81..911f6a917a2 100644 --- a/addons/account_facturx/models/account_invoice.py +++ b/addons/account_facturx/models/account_invoice.py @@ -118,7 +118,7 @@ class AccountInvoice(models.Model): if elements[0].attrib.get('currencyID'): currency_str = elements[0].attrib['currencyID'] currency = self.env.ref('base.%s' % currency_str.upper(), raise_if_not_found=False) - if currency != self.env.user.company_id.currency_id and currency.active: + if currency != self.env.company_id.currency_id and currency.active: invoice_form.currency_id = currency # Store xml total amount. diff --git a/addons/account_tax_python/models/account_tax.py b/addons/account_tax_python/models/account_tax.py index 632b7375f40..f9058e6f512 100644 --- a/addons/account_tax_python/models/account_tax.py +++ b/addons/account_tax_python/models/account_tax.py @@ -29,7 +29,7 @@ class AccountTaxPython(models.Model): def _compute_amount(self, base_amount, price_unit, quantity=1.0, product=None, partner=None): self.ensure_one() if self.amount_type == 'code': - company = self.env.user.company_id + company = self.env.company_id localdict = {'base_amount': base_amount, 'price_unit':price_unit, 'quantity': quantity, 'product':product, 'partner':partner, 'company': company} safe_eval(self.python_compute, localdict, mode="exec", nocopy=True) return localdict['result'] @@ -38,7 +38,7 @@ class AccountTaxPython(models.Model): @api.multi def compute_all(self, price_unit, currency=None, quantity=1.0, product=None, partner=None): taxes = self.filtered(lambda r: r.amount_type != 'code') - company = self.env.user.company_id + company = self.env.company_id for tax in self.filtered(lambda r: r.amount_type == 'code'): localdict = self._context.get('tax_computation_context', {}) localdict.update({'price_unit': price_unit, 'quantity': quantity, 'product': product, 'partner': partner, 'company': company}) diff --git a/addons/account_voucher/models/account_voucher.py b/addons/account_voucher/models/account_voucher.py index d868a1de62f..2aadf6fe2fb 100644 --- a/addons/account_voucher/models/account_voucher.py +++ b/addons/account_voucher/models/account_voucher.py @@ -16,7 +16,7 @@ class AccountVoucher(models.Model): @api.model def _default_journal(self): voucher_type = self._context.get('voucher_type', 'sale') - company_id = self._context.get('company_id', self.env.user.company_id.id) + company_id = self._context.get('company_id', self.env.company_id.id) domain = [ ('type', '=', voucher_type), ('company_id', '=', company_id), @@ -25,7 +25,7 @@ class AccountVoucher(models.Model): @api.model def _default_payment_journal(self): - company_id = self._context.get('company_id', self.env.user.company_id.id) + company_id = self._context.get('company_id', self.env.company_id.id) domain = [ ('type', 'in', ('bank', 'cash')), ('company_id', '=', company_id), @@ -96,11 +96,11 @@ class AccountVoucher(models.Model): journal = self.env['account.journal'].browse(self.env.context.get('default_journal_id', False)) if journal.currency_id: return journal.currency_id.id - return self.env.user.company_id.currency_id.id + return self.env.company_id.currency_id.id @api.model def _get_company(self): - return self._context.get('company_id', self.env.user.company_id.id) + return self._context.get('company_id', self.env.company_id.id) @api.constrains('company_id', 'currency_id') def _check_company_id(self): @@ -274,7 +274,7 @@ class AccountVoucher(models.Model): :return: Tuple build as (remaining amount not allocated on voucher lines, list of account_move_line created in this method) :rtype: tuple(float, list of int) ''' - tax_calculation_rounding_method = self.env.user.company_id.tax_calculation_rounding_method + tax_calculation_rounding_method = self.env.company_id.tax_calculation_rounding_method tax_lines_vals = [] for line in self.line_ids: #create one move line per voucher line where amount is not 0.0 diff --git a/addons/account_voucher/security/account_voucher_security.xml b/addons/account_voucher/security/account_voucher_security.xml index c32e720f67e..6c0d836c0c0 100644 --- a/addons/account_voucher/security/account_voucher_security.xml +++ b/addons/account_voucher/security/account_voucher_security.xml @@ -5,13 +5,13 @@ <field name="name">Voucher multi-company</field> <field name="model_id" ref="model_account_voucher"/> <field eval="True" name="global"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="voucher_line_comp_rule" model="ir.rule"> <field name="name">Voucher Line multi-company</field> <field name="model_id" ref="model_account_voucher_line"/> <field eval="True" name="global"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> </data> </odoo> diff --git a/addons/analytic/models/analytic_account.py b/addons/analytic/models/analytic_account.py index 91815380304..92d038ab732 100644 --- a/addons/analytic/models/analytic_account.py +++ b/addons/analytic/models/analytic_account.py @@ -93,7 +93,7 @@ class AccountAnalyticAccount(models.Model): if self._context.get('company_ids'): domain.append(('company_id', 'in', self._context['company_ids'])) - user_currency = self.env.user.company_id.currency_id + user_currency = self.env.company_id.currency_id credit_groups = analytic_line_obj.read_group( domain=domain + [('amount', '>=', 0.0)], fields=['account_id', 'currency_id', 'amount'], @@ -103,7 +103,7 @@ class AccountAnalyticAccount(models.Model): data_credit = defaultdict(float) for l in credit_groups: data_credit[l['account_id'][0]] += Curr.browse(l['currency_id'][0])._convert( - l['amount'], user_currency, self.env.user.company_id, fields.Date.today()) + l['amount'], user_currency, self.env.company_id, fields.Date.today()) debit_groups = analytic_line_obj.read_group( domain=domain + [('amount', '<', 0.0)], @@ -114,7 +114,7 @@ class AccountAnalyticAccount(models.Model): data_debit = defaultdict(float) for l in debit_groups: data_debit[l['account_id'][0]] += Curr.browse(l['currency_id'][0])._convert( - l['amount'], user_currency, self.env.user.company_id, fields.Date.today()) + l['amount'], user_currency, self.env.company_id, fields.Date.today()) for account in self: account.debit = abs(data_debit.get(account.id, 0.0)) @@ -129,7 +129,7 @@ class AccountAnalyticAccount(models.Model): line_ids = fields.One2many('account.analytic.line', 'account_id', string="Analytic Lines") - company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company_id) # use auto_join to speed up name_search call partner_id = fields.Many2one('res.partner', string='Customer', auto_join=True, tracking=True) @@ -186,7 +186,7 @@ class AccountAnalyticLine(models.Model): partner_id = fields.Many2one('res.partner', string='Partner') user_id = fields.Many2one('res.users', string='User', default=_default_user) tag_ids = fields.Many2many('account.analytic.tag', 'account_analytic_line_tag_rel', 'line_id', 'tag_id', string='Tags', copy=True) - company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, default=lambda self: self.env.company_id) currency_id = fields.Many2one(related="company_id.currency_id", string="Currency", readonly=True, store=True, compute_sudo=True) group_id = fields.Many2one('account.analytic.group', related='account_id.group_id', store=True, readonly=True, compute_sudo=True) diff --git a/addons/analytic/security/analytic_security.xml b/addons/analytic/security/analytic_security.xml index 5e66d317f5c..696beb03dc8 100644 --- a/addons/analytic/security/analytic_security.xml +++ b/addons/analytic/security/analytic_security.xml @@ -6,28 +6,28 @@ <field name="name">Analytic multi company rule</field> <field name="model_id" ref="model_account_analytic_account"/> <field eval="True" name="global"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="analytic_line_comp_rule" model="ir.rule"> <field name="name">Analytic line multi company rule</field> <field name="model_id" ref="model_account_analytic_line"/> <field eval="True" name="global"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="analytic_group_comp_rule" model="ir.rule"> <field name="name">Analytic line multi company rule</field> <field name="model_id" ref="model_account_analytic_group"/> <field eval="True" name="global"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="analytic_tag_comp_rule" model="ir.rule"> <field name="name">Analytic line multi company rule</field> <field name="model_id" ref="model_account_analytic_tag"/> <field eval="True" name="global"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> </data> <data noupdate="0"> diff --git a/addons/base_setup/models/res_config_settings.py b/addons/base_setup/models/res_config_settings.py index 73da6f2a076..49dccf49bc5 100644 --- a/addons/base_setup/models/res_config_settings.py +++ b/addons/base_setup/models/res_config_settings.py @@ -9,8 +9,9 @@ class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' group_multi_company = fields.Boolean("Manage multiple companies", implied_group='base.group_multi_company') + group_toggle_company = fields.Boolean("Toggle multiple companies", implied_group='base.group_toggle_company') company_id = fields.Many2one('res.company', string='Company', required=True, - default=lambda self: self.env.user.company_id) + default=lambda self: self.env.company_id) user_default_rights = fields.Boolean( "Default Access Rights", config_parameter='base_setup.default_user_rights', @@ -67,7 +68,7 @@ class ResConfigSettings(models.TransientModel): 'view_type': 'form', 'view_mode': 'form', 'res_model': 'res.company', - 'res_id': self.env.user.company_id.id, + 'res_id': self.env.company_id.id, 'target': 'current', } @api.multi @@ -103,7 +104,7 @@ class ResConfigSettings(models.TransientModel): 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', - 'res_id': self.env.user.company_id.id, + 'res_id': self.env.company_id.id, 'res_model': 'res.company', 'views': [(template.id, 'form')], 'view_id': template.id, diff --git a/addons/base_setup/views/res_config_settings_views.xml b/addons/base_setup/views/res_config_settings_views.xml index 8aff13e062b..8dcbda44ed5 100644 --- a/addons/base_setup/views/res_config_settings_views.xml +++ b/addons/base_setup/views/res_config_settings_views.xml @@ -141,6 +141,18 @@ </div> </div> </div> + <div class="col-12 col-lg-6 o_setting_box"> + <div class="o_setting_left_pane"> + <field name="group_toggle_company"/> + </div> + <div class="o_setting_right_pane"> + <label string="Multi-companies by Tab" for="group_toggle_company"/> + <div class="text-muted"> + Manage multiple companies on the same browser tab. Be careful that this advanced tool should + only be used for reporting purpose. + </div> + </div> + </div> <div class="col-12 col-lg-6 o_setting_box" title="Configure company rules to automatically create SO/PO when one of your company sells/buys to another of your company." attrs="{'invisible': [('group_multi_company', '=', False)]}" id="inter_company"> <div class="o_setting_left_pane"> <field name="module_inter_company_rules" widget="upgrade_boolean"/> diff --git a/addons/base_vat/models/res_partner.py b/addons/base_vat/models/res_partner.py index c5118cd476b..c25c8641bb8 100644 --- a/addons/base_vat/models/res_partner.py +++ b/addons/base_vat/models/res_partner.py @@ -155,7 +155,7 @@ class ResPartner(models.Model): if self.env.context.get('company_id'): company = self.env['res.company'].browse(self.env.context['company_id']) else: - company = self.env.user.company_id + company = self.env.company_id if company.vat_check_vies: # force full VIES online check check_func = self.vies_vat_check @@ -182,7 +182,7 @@ class ResPartner(models.Model): if self.env.context.get('company_id'): company = self.env['res.company'].browse(self.env.context['company_id']) else: - company = self.env.user.company_id + company = self.env.company_id if company.vat_check_vies: return '\n' + _('The VAT number [%s] for partner [%s] either failed the VIES VAT validation check or did not respect the expected format %s.') % (self.vat, self.name, vat_no) return '\n' + _('The VAT number [%s] for partner [%s] does not seem to be valid. \nNote: the expected format is %s') % (self.vat, self.name, vat_no) diff --git a/addons/crm/models/crm_lead.py b/addons/crm/models/crm_lead.py index 008725eb595..cd6f402e579 100644 --- a/addons/crm/models/crm_lead.py +++ b/addons/crm/models/crm_lead.py @@ -124,7 +124,7 @@ class Lead(models.Model): mobile = fields.Char('Mobile') function = fields.Char('Job Position') title = fields.Many2one('res.partner.title') - company_id = fields.Many2one('res.company', string='Company', index=True, default=lambda self: self.env.user.company_id.id) + company_id = fields.Many2one('res.company', string='Company', index=True, default=lambda self: self.env.company_id.id) meeting_count = fields.Integer('# Meetings', compute='_compute_meeting_count') lost_reason = fields.Many2one('crm.lost.reason', string='Lost Reason', index=True, tracking=True) @@ -1082,7 +1082,7 @@ class Lead(models.Model): result['done']['target'] = self.env.user.target_sales_done result['won']['target'] = self.env.user.target_sales_won - result['currency_id'] = self.env.user.company_id.currency_id.id + result['currency_id'] = self.env.company_id.currency_id.id return result diff --git a/addons/crm/security/crm_security.xml b/addons/crm/security/crm_security.xml index 450b0e3646c..e96c6f1809a 100644 --- a/addons/crm/security/crm_security.xml +++ b/addons/crm/security/crm_security.xml @@ -35,7 +35,7 @@ <record id="crm_lead_company_rule" model="ir.rule"> <field name="name">CRM Lead Multi-Company</field> <field name="model_id" ref="model_crm_lead"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="crm_rule_all_lead" model="ir.rule"> @@ -70,7 +70,7 @@ <field name="name">CRM Lead Multi-Company</field> <field name="model_id" ref="model_crm_activity_report"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> </data> diff --git a/addons/crm/tests/test_new_lead_notification.py b/addons/crm/tests/test_new_lead_notification.py index 16228fcc55c..1b0f4c3a14c 100644 --- a/addons/crm/tests/test_new_lead_notification.py +++ b/addons/crm/tests/test_new_lead_notification.py @@ -43,7 +43,7 @@ class NewLeadNotification(TestCrmCases): self.assertTrue(lead_user.message_needaction) def test_new_lead_from_email_multicompany(self): - company0 = self.env.user.company_id + company0 = self.env.company_id company1 = self.env['res.company'].create({'name': 'new_company'}) self.env.user.write({ diff --git a/addons/crm_iap_lead_website/models/crm_reveal_rule.py b/addons/crm_iap_lead_website/models/crm_reveal_rule.py index 1b063d95c75..4e0e2c0c831 100644 --- a/addons/crm_iap_lead_website/models/crm_reveal_rule.py +++ b/addons/crm_iap_lead_website/models/crm_reveal_rule.py @@ -273,7 +273,7 @@ class CRMRevealRule(models.Model): } def _get_rules_payload(self): - company_country = self.env.user.company_id.country_id + company_country = self.env.company_id.country_id rule_payload = {} for rule in self: data = { diff --git a/addons/delivery/models/stock_picking.py b/addons/delivery/models/stock_picking.py index 6444f110d38..66512fdf384 100644 --- a/addons/delivery/models/stock_picking.py +++ b/addons/delivery/models/stock_picking.py @@ -74,7 +74,7 @@ class StockPicking(models.Model): carrier_price = fields.Float(string="Shipping Cost") delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True) - carrier_id = fields.Many2one("delivery.carrier", string="Carrier") + carrier_id = fields.Many2one("delivery.carrier", string="Carrier", domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") volume = fields.Float(copy=False) weight = fields.Float(compute='_cal_weight', digits=dp.get_precision('Stock Weight'), store=True, help="Total weight of the products in the picking.") carrier_tracking_ref = fields.Char(string='Tracking Reference', copy=False) diff --git a/addons/delivery/security/delivery_carrier_security.xml b/addons/delivery/security/delivery_carrier_security.xml index db718fbf361..e9e22c47088 100644 --- a/addons/delivery/security/delivery_carrier_security.xml +++ b/addons/delivery/security/delivery_carrier_security.xml @@ -5,7 +5,7 @@ <field name="name">Delivery Carrier multi-company</field> <field name="model_id" ref="model_delivery_carrier"/> <field name="global" eval="True"/> - <field name="domain_force"> ['|',('company_id','=',user.company_id.id),('company_id','=',False)]</field> + <field name="domain_force"> ['|', ('company_id', 'in', company_ids), ('company_id', '=', False)]</field> <field name="active" eval="False"/> </record> </data> diff --git a/addons/delivery/tests/test_delivery_cost.py b/addons/delivery/tests/test_delivery_cost.py index 71d0ab0ae98..a57e617d946 100644 --- a/addons/delivery/tests/test_delivery_cost.py +++ b/addons/delivery/tests/test_delivery_cost.py @@ -32,7 +32,7 @@ class TestDeliveryCost(common.TransactionCase): # that the company actually uses USD self.env.cr.execute( "UPDATE res_company SET currency_id = %s WHERE id = %s", - [self.env.ref('base.USD').id, self.env.user.company_id.id]) + [self.env.ref('base.USD').id, self.env.company_id.id]) self.pricelist.currency_id = self.env.ref('base.USD').id def test_00_delivery_cost(self): diff --git a/addons/digest/models/digest.py b/addons/digest/models/digest.py index 1d10c59d504..f7eb085a5b3 100644 --- a/addons/digest/models/digest.py +++ b/addons/digest/models/digest.py @@ -33,7 +33,7 @@ class Digest(models.Model): default=lambda self: self.env.ref('digest.digest_mail_template'), required=True) currency_id = fields.Many2one(related="company_id.currency_id", string='Currency', readonly=False) - company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.user.company_id.id) + company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company_id.id) available_fields = fields.Char(compute='_compute_available_fields') is_subscribed = fields.Boolean('Is user subscribed', compute='_compute_is_subscribed') state = fields.Selection([('activated', 'Activated'), ('deactivated', 'Deactivated')], string='Status', readonly=True, default='activated') diff --git a/addons/event/models/event.py b/addons/event/models/event.py index 328abb783d9..0095452a69d 100644 --- a/addons/event/models/event.py +++ b/addons/event/models/event.py @@ -101,12 +101,12 @@ class EventEvent(models.Model): readonly=False, states={'done': [('readonly', True)]}) company_id = fields.Many2one( 'res.company', string='Company', change_default=True, - default=lambda self: self.env['res.company']._company_default_get('event.event'), + default=lambda self: self.env.company_id, required=False, readonly=False, states={'done': [('readonly', True)]}) organizer_id = fields.Many2one( 'res.partner', string='Organizer', tracking=True, - default=lambda self: self.env.user.company_id.partner_id) + default=lambda self: self.env.company_id.partner_id) event_type_id = fields.Many2one( 'event.type', string='Category', readonly=False, states={'done': [('readonly', True)]}, @@ -165,7 +165,7 @@ class EventEvent(models.Model): is_online = fields.Boolean('Online Event') address_id = fields.Many2one( 'res.partner', string='Location', - default=lambda self: self.env.user.company_id.partner_id, + default=lambda self: self.env.company_id.partner_id, readonly=False, states={'done': [('readonly', True)]}, tracking=True) country_id = fields.Many2one('res.country', 'Country', related='address_id.country_id', store=True, readonly=False) diff --git a/addons/event/security/event_security.xml b/addons/event/security/event_security.xml index cf87135ddbe..08dd739cf52 100644 --- a/addons/event/security/event_security.xml +++ b/addons/event/security/event_security.xml @@ -32,7 +32,7 @@ <field name="global" eval="True"/> <field name="domain_force">['|', ('company_id', '=', False), - ('company_id', 'child_of', [user.company_id.id]), + ('company_id', 'in', company_ids), ] </field> </record> @@ -42,7 +42,7 @@ <field name="global" eval="True"/> <field name="domain_force">['|', ('company_id', '=', False), - ('company_id', 'child_of', [user.company_id.id]), + ('company_id', 'in', company_ids), ] </field> </record> diff --git a/addons/event_sale/models/sale_order.py b/addons/event_sale/models/sale_order.py index fac1730bead..c2f0feb9398 100644 --- a/addons/event_sale/models/sale_order.py +++ b/addons/event_sale/models/sale_order.py @@ -80,7 +80,7 @@ class SaleOrderLine(models.Model): @api.onchange('event_ticket_id') def _onchange_event_ticket_id(self): - company = self.event_id.company_id or self.env.user.company_id + company = self.event_id.company_id or self.env.company_id currency = company.currency_id self.price_unit = currency._convert( self.event_ticket_id.price, self.order_id.currency_id, self.order_id.company_id, self.order_id.date_order or fields.Date.today()) diff --git a/addons/fleet/models/fleet_vehicle.py b/addons/fleet/models/fleet_vehicle.py index 773d10050ca..0d4ebd157f4 100644 --- a/addons/fleet/models/fleet_vehicle.py +++ b/addons/fleet/models/fleet_vehicle.py @@ -19,7 +19,7 @@ class FleetVehicle(models.Model): name = fields.Char(compute="_compute_vehicle_name", store=True) active = fields.Boolean('Active', default=True, tracking=True) - company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env['res.company']._company_default_get()) + company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env.company_id) currency_id = fields.Many2one('res.currency', related='company_id.currency_id') license_plate = fields.Char(tracking=True, help='License plate number of the vehicle (i = plate number for a car)') diff --git a/addons/fleet/models/fleet_vehicle_cost.py b/addons/fleet/models/fleet_vehicle_cost.py index fa5bd4bf418..453b7a8b1c7 100644 --- a/addons/fleet/models/fleet_vehicle_cost.py +++ b/addons/fleet/models/fleet_vehicle_cost.py @@ -32,7 +32,7 @@ class FleetVehicleCost(models.Model): contract_id = fields.Many2one('fleet.vehicle.log.contract', 'Contract', help='Contract attached to this cost') auto_generated = fields.Boolean('Automatically Generated', readonly=True) description = fields.Char("Cost Description") - company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env['res.company']._company_default_get()) + company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env.company_id) currency_id = fields.Many2one('res.currency', related='company_id.currency_id') def _get_odometer(self): diff --git a/addons/gamification/models/goal.py b/addons/gamification/models/goal.py index dfb850897c8..05f7059cbbd 100644 --- a/addons/gamification/models/goal.py +++ b/addons/gamification/models/goal.py @@ -66,7 +66,7 @@ class GoalDefinition(models.Model): items = [] if goal.monetary: - items.append(self.env.user.company_id.currency_id.symbol or u'¤') + items.append(self.env.company_id.currency_id.symbol or u'¤') if goal.suffix: items.append(goal.suffix) diff --git a/addons/gamification/security/gamification_security.xml b/addons/gamification/security/gamification_security.xml index 3eecfb2e98c..4629c8776b2 100644 --- a/addons/gamification/security/gamification_security.xml +++ b/addons/gamification/security/gamification_security.xml @@ -31,7 +31,7 @@ <record id="goal_global_multicompany" model="ir.rule"> <field name="name">Multicompany rule on challenges</field> <field name="model_id" ref="model_gamification_goal"/> - <field name="domain_force">[('user_id.company_id', 'child_of', [user.company_id.id])]</field> + <field name="domain_force">[('user_id.company_id', 'in', company_ids)]</field> <field name="global" eval="True"/> </record> diff --git a/addons/hr/models/hr.py b/addons/hr/models/hr.py index cccb266981b..7660c755471 100644 --- a/addons/hr/models/hr.py +++ b/addons/hr/models/hr.py @@ -47,7 +47,7 @@ class Job(models.Model): description = fields.Text(string='Job Description') requirements = fields.Text('Requirements') department_id = fields.Many2one('hr.department', string='Department') - company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company_id) state = fields.Selection([ ('recruit', 'Recruitment in Progress'), ('open', 'Not Recruiting') @@ -379,7 +379,7 @@ class Department(models.Model): name = fields.Char('Department Name', required=True) complete_name = fields.Char('Complete Name', compute='_compute_complete_name', store=True) active = fields.Boolean('Active', default=True) - company_id = fields.Many2one('res.company', string='Company', index=True, default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', string='Company', index=True, default=lambda self: self.env.company_id) parent_id = fields.Many2one('hr.department', string='Parent Department', index=True) child_ids = fields.One2many('hr.department', 'parent_id', string='Child Departments') manager_id = fields.Many2one('hr.employee', string='Manager', tracking=True) diff --git a/addons/hr/models/res_partner.py b/addons/hr/models/res_partner.py index 9258c1ac5da..62f7c3f949a 100644 --- a/addons/hr/models/res_partner.py +++ b/addons/hr/models/res_partner.py @@ -16,8 +16,7 @@ class Partner(models.Model): try: employee_group = self.env.ref('base.group_user') - hr_suggestions = [{'id': user.partner_id.id, 'name': user.name, 'email': user.email} - for user in employee_group.users] + hr_suggestions = [{'id': user.partner_id.id, 'name': user.name, 'email': user.email} for user in employee_group.users] suggestions.append(hr_suggestions) return suggestions except AccessError: diff --git a/addons/hr/security/hr_security.xml b/addons/hr/security/hr_security.xml index 8d435e67463..c735d05b1ce 100644 --- a/addons/hr/security/hr_security.xml +++ b/addons/hr/security/hr_security.xml @@ -30,21 +30,21 @@ <field name="name">Employee multi company rule</field> <field name="model_id" ref="model_hr_employee"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="hr_dept_comp_rule" model="ir.rule"> <field name="name">Department multi company rule</field> <field name="model_id" ref="model_hr_department"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="hr_job_comp_rule" model="ir.rule"> <field name="name">Job multi company rule</field> <field name="model_id" ref="model_hr_job"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> </data> diff --git a/addons/hr_attendance_presence/models/hr_employee.py b/addons/hr_attendance_presence/models/hr_employee.py index 3fac86ce6c4..af259d7fc4f 100644 --- a/addons/hr_attendance_presence/models/hr_employee.py +++ b/addons/hr_attendance_presence/models/hr_employee.py @@ -16,7 +16,7 @@ class Employee(models.Model): action = super(Employee, self)._action_open_presence_view() if self.env['ir.config_parameter'].sudo().get_param('hr_presence.hr_presence_control_attendance'): - company = self.env.user.company_id + company = self.env.company_id employees = self.env['hr.employee'].search([ ('department_id.company_id', '=', company.id), ('user_id', '!=', False), diff --git a/addons/hr_contract/models/hr_contract.py b/addons/hr_contract/models/hr_contract.py index f41d4faba71..4f333a3c4b4 100644 --- a/addons/hr_contract/models/hr_contract.py +++ b/addons/hr_contract/models/hr_contract.py @@ -66,7 +66,7 @@ class Contract(models.Model): help="End date of the trial period (if there is one).") resource_calendar_id = fields.Many2one( 'resource.calendar', 'Working Schedule', - default=lambda self: self.env['res.company']._company_default_get().resource_calendar_id.id) + default=lambda self: self.env.company_id.resource_calendar_id.id) wage = fields.Monetary('Wage', digits=(16, 2), required=True, tracking=True, help="Employee's monthly gross wage.") advantages = fields.Text('Advantages') notes = fields.Text('Notes') @@ -79,7 +79,7 @@ class Contract(models.Model): ('cancel', 'Cancelled') ], string='Status', group_expand='_expand_states', tracking=True, help='Status of the contract', default='draft') - company_id = fields.Many2one('res.company', default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', default=lambda self: self.env.company_id) currency_id = fields.Many2one(string="Currency", related='company_id.currency_id', readonly=True) permit_no = fields.Char('Work Permit No', related="employee_id.permit_no", readonly=False) visa_no = fields.Char('Visa No', related="employee_id.visa_no", readonly=False) diff --git a/addons/hr_contract/security/security.xml b/addons/hr_contract/security/security.xml index d592b820a16..4a3cf359d8e 100644 --- a/addons/hr_contract/security/security.xml +++ b/addons/hr_contract/security/security.xml @@ -21,7 +21,7 @@ <field name="name">HR Contract: Multi Company</field> <field name="model_id" ref="model_hr_contract"/> <field name="global" eval="True"/> - <field name="domain_force">['|', ('company_id', '=', False), ('company_id', 'child_of', [user.company_id.id])]</field> + <field name="domain_force">['|', ('company_id', '=', False), ('company_id', 'in', company_ids)]</field> </record> </data> diff --git a/addons/hr_expense/models/hr_expense.py b/addons/hr_expense/models/hr_expense.py index b0a8c584c67..a4fc1c58338 100644 --- a/addons/hr_expense/models/hr_expense.py +++ b/addons/hr_expense/models/hr_expense.py @@ -56,8 +56,8 @@ class HrExpense(models.Model): untaxed_amount = fields.Float("Subtotal", store=True, compute='_compute_amount', digits=dp.get_precision('Account')) total_amount = fields.Monetary("Total", compute='_compute_amount', store=True, currency_field='currency_id', digits=dp.get_precision('Account')) total_amount_company = fields.Monetary("Total (Company Currency)", compute='_compute_total_amount_company', store=True, currency_field='company_currency_id', digits=dp.get_precision('Account')) - company_id = fields.Many2one('res.company', string='Company', readonly=True, states={'draft': [('readonly', False)], 'refused': [('readonly', False)]}, default=lambda self: self.env.user.company_id) - currency_id = fields.Many2one('res.currency', string='Currency', readonly=True, states={'draft': [('readonly', False)], 'refused': [('readonly', False)]}, default=lambda self: self.env.user.company_id.currency_id) + company_id = fields.Many2one('res.company', string='Company', readonly=True, states={'draft': [('readonly', False)], 'refused': [('readonly', False)]}, default=lambda self: self.env.company_id) + currency_id = fields.Many2one('res.currency', string='Currency', readonly=True, states={'draft': [('readonly', False)], 'refused': [('readonly', False)]}, default=lambda self: self.env.company_id.currency_id) company_currency_id = fields.Many2one('res.currency', string="Report Company Currency", related='sheet_id.currency_id', store=True, readonly=False) analytic_account_id = fields.Many2one('account.analytic.account', string='Analytic Account', states={'post': [('readonly', True)], 'done': [('readonly', True)]}, oldname='analytic_account') analytic_tag_ids = fields.Many2many('account.analytic.tag', string='Analytic Tags', states={'post': [('readonly', True)], 'done': [('readonly', True)]}) @@ -224,7 +224,7 @@ class HrExpense(models.Model): journal = expense.sheet_id.bank_journal_id if expense.payment_mode == 'company_account' else expense.sheet_id.journal_id move = self.env['account.move'].create({ 'journal_id': journal.id, - 'company_id': self.env.user.company_id.id, + 'company_id': self.env.company_id.id, 'date': account_date, 'ref': expense.sheet_id.name, # force the name to the default value, to avoid an eventual 'default_name' in the context @@ -595,8 +595,8 @@ class HrExpenseSheet(models.Model): payment_mode = fields.Selection(related='expense_line_ids.payment_mode', default='own_account', readonly=True, string="Paid By") user_id = fields.Many2one('res.users', 'Manager', readonly=True, copy=False, states={'draft': [('readonly', False)]}, tracking=True, oldname='responsible_id') total_amount = fields.Monetary('Total Amount', currency_field='currency_id', compute='_compute_amount', store=True, digits=dp.get_precision('Account')) - company_id = fields.Many2one('res.company', string='Company', readonly=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env.user.company_id) - currency_id = fields.Many2one('res.currency', string='Currency', readonly=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env.user.company_id.currency_id) + company_id = fields.Many2one('res.company', string='Company', readonly=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env.company_id) + currency_id = fields.Many2one('res.currency', string='Currency', readonly=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env.company_id.currency_id) attachment_number = fields.Integer(compute='_compute_attachment_number', string='Number of Attachments') journal_id = fields.Many2one('account.journal', string='Expense Journal', states={'done': [('readonly', True)], 'post': [('readonly', True)]}, default=_default_journal_id, help="The journal used when the expense is done.") bank_journal_id = fields.Many2one('account.journal', string='Bank Journal', states={'done': [('readonly', True)], 'post': [('readonly', True)]}, default=_default_bank_journal_id, help="The payment method used when the expense is paid by the company.") @@ -697,7 +697,7 @@ class HrExpenseSheet(models.Model): raise UserError(_("Expenses must have an expense journal specified to generate accounting entries.")) expense_line_ids = self.mapped('expense_line_ids')\ - .filtered(lambda r: not float_is_zero(r.total_amount, precision_rounding=(r.currency_id or self.env.user.company_id.currency_id).rounding)) + .filtered(lambda r: not float_is_zero(r.total_amount, precision_rounding=(r.currency_id or self.env.company_id.currency_id).rounding)) res = expense_line_ids.action_move_create() if not self.accounting_date: diff --git a/addons/hr_expense/security/ir_rule.xml b/addons/hr_expense/security/ir_rule.xml index 51a3a8d641d..3b13eb977a6 100644 --- a/addons/hr_expense/security/ir_rule.xml +++ b/addons/hr_expense/security/ir_rule.xml @@ -55,13 +55,13 @@ <field name="name">Expense multi company rule</field> <field name="model_id" ref="model_hr_expense"/> <field eval="True" name="global"/> - <field name="domain_force">['|',('company_id', '=', False), ('company_id', 'child_of', [user.company_id.id])]</field> + <field name="domain_force">['|',('company_id', '=', False), ('company_id', 'in', company_ids)]</field> </record> <record id="hr_expense_report_comp_rule" model="ir.rule"> <field name="name">Expense Report multi company rule</field> <field name="model_id" ref="model_hr_expense_sheet"/> <field eval="True" name="global"/> - <field name="domain_force">['|',('company_id', '=', False), ('company_id', 'child_of', [user.company_id.id])]</field> + <field name="domain_force">['|',('company_id', '=', False), ('company_id', 'in', company_ids)]</field> </record> </data> diff --git a/addons/hr_expense/tests/test_expenses.py b/addons/hr_expense/tests/test_expenses.py index 66a56b2f557..5ab7abe3d67 100644 --- a/addons/hr_expense/tests/test_expenses.py +++ b/addons/hr_expense/tests/test_expenses.py @@ -83,11 +83,11 @@ class TestAccountEntry(TestExpenseCommon): multi-currency. And taxes. """ # Clean-up the rates - self.cr.execute("UPDATE res_company SET currency_id = %s WHERE id = %s", [self.env.ref('base.USD').id, self.env.user.company_id.id]) + self.cr.execute("UPDATE res_company SET currency_id = %s WHERE id = %s", [self.env.ref('base.USD').id, self.env.company_id.id]) self.env['res.currency.rate'].search([]).unlink() self.env['res.currency.rate'].create({ 'currency_id': self.env.ref('base.EUR').id, - 'company_id': self.env.user.company_id.id, + 'company_id': self.env.company_id.id, 'rate': 2.0, 'name': '2010-01-01', }) @@ -142,7 +142,7 @@ class TestAccountEntry(TestExpenseCommon): self.assertEquals(self.analytic_account.line_ids, expense.account_move_id.mapped('line_ids.analytic_line_ids')) self.assertEquals(len(self.analytic_account.line_ids), 1, "Analytic Account should have only one line") self.assertAlmostEquals(self.analytic_account.line_ids[0].amount, -318.18, "Amount on the only AAL is wrong") - self.assertAlmostEquals(self.analytic_account.line_ids[0].currency_id, self.env.user.company_id.currency_id, "Currency on the only AAL is wrong") + self.assertAlmostEquals(self.analytic_account.line_ids[0].currency_id, self.env.company_id.currency_id, "Currency on the only AAL is wrong") self.assertEquals(self.analytic_account.line_ids[0].product_id, self.product_expense, "Product of AAL should be the one from the expense") def test_expense_from_email(self): diff --git a/addons/hr_expense/wizard/hr_expense_sheet_register_payment.py b/addons/hr_expense/wizard/hr_expense_sheet_register_payment.py index 76a97f6a561..2cacf083f74 100644 --- a/addons/hr_expense/wizard/hr_expense_sheet_register_payment.py +++ b/addons/hr_expense/wizard/hr_expense_sheet_register_payment.py @@ -23,7 +23,7 @@ class HrExpenseSheetRegisterPaymentWizard(models.TransientModel): company_id = fields.Many2one('res.company', related='journal_id.company_id', string='Company', readonly=True, required=True) payment_method_id = fields.Many2one('account.payment.method', string='Payment Type', required=True) amount = fields.Monetary(string='Payment Amount', required=True) - currency_id = fields.Many2one('res.currency', string='Currency', required=True, default=lambda self: self.env.user.company_id.currency_id) + currency_id = fields.Many2one('res.currency', string='Currency', required=True, default=lambda self: self.env.company_id.currency_id) payment_date = fields.Date(string='Payment Date', default=fields.Date.context_today, required=True) communication = fields.Char(string='Memo') hide_payment_method = fields.Boolean(compute='_compute_hide_payment_method', diff --git a/addons/hr_holidays/models/hr_leave.py b/addons/hr_holidays/models/hr_leave.py index 443d01f4729..942b83dbe2a 100644 --- a/addons/hr_holidays/models/hr_leave.py +++ b/addons/hr_holidays/models/hr_leave.py @@ -278,7 +278,7 @@ class HolidaysRequest(models.Model): self.date_to = False return - domain = [('calendar_id', '=', self.employee_id.resource_calendar_id.id or self.env.user.company_id.resource_calendar_id.id)] + domain = [('calendar_id', '=', self.employee_id.resource_calendar_id.id or self.env.company_id.resource_calendar_id.id)] attendances = self.env['resource.calendar.attendance'].search(domain, order='dayofweek, day_period DESC') # find first attendance coming after first_day @@ -341,7 +341,7 @@ class HolidaysRequest(models.Model): self.category_id = False elif self.holiday_type == 'company' and not self.mode_company_id: self.employee_id = False - self.mode_company_id = self.env.user.company_id.id + self.mode_company_id = self.env.company_id.id self.category_id = False elif self.holiday_type == 'department' and not self.department_id: self.employee_id = False @@ -376,7 +376,7 @@ class HolidaysRequest(models.Model): @api.depends('number_of_days') def _compute_number_of_hours_display(self): for holiday in self: - calendar = holiday.employee_id.resource_calendar_id or self.env.user.company_id.resource_calendar_id + calendar = holiday.employee_id.resource_calendar_id or self.env.company_id.resource_calendar_id if holiday.date_from and holiday.date_to: number_of_hours = calendar.get_work_hours_count(holiday.date_from, holiday.date_to) holiday.number_of_hours_display = number_of_hours or (holiday.number_of_days * HOURS_PER_DAY) @@ -438,12 +438,12 @@ class HolidaysRequest(models.Model): employee = self.env['hr.employee'].browse(employee_id) return employee._get_work_days_data(date_from, date_to)['days'] - today_hours = self.env.user.company_id.resource_calendar_id.get_work_hours_count( + today_hours = self.env.company_id.resource_calendar_id.get_work_hours_count( datetime.combine(date_from.date(), time.min), datetime.combine(date_from.date(), time.max), False) - return self.env.user.company_id.resource_calendar_id.get_work_hours_count(date_from, date_to) / (today_hours or HOURS_PER_DAY) + return self.env.company_id.resource_calendar_id.get_work_hours_count(date_from, date_to) / (today_hours or HOURS_PER_DAY) #################################################### # ORM Overrides methods @@ -563,6 +563,9 @@ class HolidaysRequest(models.Model): def copy_data(self, default=None): raise UserError(_('A leave cannot be duplicated.')) + def _get_mail_redirect_suggested_company(self): + return self.holiday_status_id.company_id + #################################################### # Business methods #################################################### @@ -606,7 +609,7 @@ class HolidaysRequest(models.Model): @api.multi def _prepare_holidays_meeting_values(self): self.ensure_one() - calendar = self.employee_id.resource_calendar_id or self.env.user.company_id.resource_calendar_id + calendar = self.employee_id.resource_calendar_id or self.env.company_id.resource_calendar_id meeting_values = { 'name': self.display_name, 'categ_ids': [(6, 0, [ diff --git a/addons/hr_holidays/models/hr_leave_allocation.py b/addons/hr_holidays/models/hr_leave_allocation.py index abfb441a0c9..1ad7b9fca45 100644 --- a/addons/hr_holidays/models/hr_leave_allocation.py +++ b/addons/hr_holidays/models/hr_leave_allocation.py @@ -365,6 +365,9 @@ class HolidaysAllocation(models.Model): def copy_data(self, default=None): raise UserError(_('A time off cannot be duplicated.')) + def _get_mail_redirect_suggested_company(self): + return self.holiday_status_id.company_id + #################################################### # Business methods #################################################### diff --git a/addons/hr_holidays/models/hr_leave_type.py b/addons/hr_holidays/models/hr_leave_type.py index 9b92f171d9e..fed5240b002 100644 --- a/addons/hr_holidays/models/hr_leave_type.py +++ b/addons/hr_holidays/models/hr_leave_type.py @@ -64,7 +64,7 @@ class HolidaysType(models.Model): compute='_compute_group_days_allocation', string='Days Allocated') group_days_leave = fields.Float( compute='_compute_group_days_leave', string='Group Time Off') - company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company_id) responsible_id = fields.Many2one('res.users', 'Responsible', domain=lambda self: [('groups_id', 'in', self.env.ref('hr_holidays.group_hr_holidays_user').id)], help="This user will be responsible for approving this type of times off" "This is only used when validation is 'hr' or 'both'",) @@ -208,7 +208,7 @@ class HolidaysType(models.Model): elif 'default_employee_id' in self._context: employee_id = self._context['default_employee_id'] else: - employee_id = self.env['hr.employee'].search([('user_id', '=', self.env.user.id), ('company_id', '=', self.env.user.company_id.id)], limit=1).id + employee_id = self.env['hr.employee'].search([('user_id', '=', self.env.user.id), ('company_id', '=', self.env.company_id.id)], limit=1).id return employee_id @api.multi diff --git a/addons/hr_holidays/security/hr_holidays_security.xml b/addons/hr_holidays/security/hr_holidays_security.xml index c8b10a11d7b..623438454b4 100644 --- a/addons/hr_holidays/security/hr_holidays_security.xml +++ b/addons/hr_holidays/security/hr_holidays_security.xml @@ -77,7 +77,7 @@ <field name="name">Time Off: multi company global rule</field> <field name="model_id" ref="model_hr_leave"/> <field name="global" eval="True"/> - <field name="domain_force">['|', ('holiday_status_id.company_id', '=', False), ('holiday_status_id.company_id', 'in', [user.company_id.id])]</field> + <field name="domain_force">['|', ('holiday_status_id.company_id', '=', False), ('holiday_status_id.company_id', 'in', company_ids)]</field> </record> <record id="hr_leave_allocation_rule_employee" model="ir.rule"> @@ -145,7 +145,7 @@ <field name="name">Time Off multi company rule</field> <field name="model_id" ref="model_hr_leave_type"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','in',[user.company_id.id])]</field> + <field name="domain_force">['|', ('company_id', '=', False), ('company_id', 'in', company_ids)]</field> </record> </odoo> diff --git a/addons/hr_org_chart/controllers/hr_org_chart.py b/addons/hr_org_chart/controllers/hr_org_chart.py index 20f1c30047a..a82d9002d33 100644 --- a/addons/hr_org_chart/controllers/hr_org_chart.py +++ b/addons/hr_org_chart/controllers/hr_org_chart.py @@ -9,12 +9,17 @@ from odoo.http import request class HrOrgChartController(http.Controller): _managers_level = 5 # FP request - def _check_employee(self, employee_id): + def _check_employee(self, employee_id, **kw): if not employee_id: # to check return None employee_id = int(employee_id) - Employee = request.env['hr.employee'] + if ('context' in kw and 'allowed_company_ids' in kw['context']): + cids = kw['context']['allowed_company_ids'] + else: + cids = [request.env.company_id.id] + + Employee = request.env['hr.employee'].with_context(allowed_company_ids=cids) # check and raise if not Employee.check_access_rights('read', raise_exception=False): return None @@ -38,9 +43,9 @@ class HrOrgChartController(http.Controller): ) @http.route('/hr/get_org_chart', type='json', auth='user') - def get_org_chart(self, employee_id): + def get_org_chart(self, employee_id, **kw): - employee = self._check_employee(employee_id) + employee = self._check_employee(employee_id, **kw) if not employee: # to check return {} @@ -64,15 +69,14 @@ class HrOrgChartController(http.Controller): return values @http.route('/hr/get_subordinates', type='json', auth='user') - def get_subordinates(self, employee_id, subordinates_type=None): + def get_subordinates(self, employee_id, subordinates_type=None, **kw): """ Get employee subordinates. Possible values for 'subordinates_type': - 'indirect' - 'direct' """ - - employee = self._check_employee(employee_id) + employee = self._check_employee(employee_id, **kw) if not employee: # to check return {} diff --git a/addons/hr_org_chart/static/src/js/hr_org_chart.js b/addons/hr_org_chart/static/src/js/hr_org_chart.js index c4f200d1ea9..5e2ba861058 100644 --- a/addons/hr_org_chart/static/src/js/hr_org_chart.js +++ b/addons/hr_org_chart/static/src/js/hr_org_chart.js @@ -5,6 +5,7 @@ var AbstractField = require('web.AbstractField'); var concurrency = require('web.concurrency'); var core = require('web.core'); var field_registry = require('web.field_registry'); +var session = require('web.session'); var QWeb = core.qweb; var _t = core._t; @@ -41,7 +42,8 @@ var FieldOrgChart = AbstractField.extend({ return this.dm.add(this._rpc({ route: '/hr/get_org_chart', params: { - employee_id: employee_id + employee_id: employee_id, + context: session.user_context, }, })).then(function (data) { self.orgData = data; @@ -59,7 +61,8 @@ var FieldOrgChart = AbstractField.extend({ route: '/hr/get_subordinates', params: { employee_id: employee_id, - subordinates_type: type + subordinates_type: type, + context: session.user_context, }, })); }, diff --git a/addons/hr_presence/models/hr_employee.py b/addons/hr_presence/models/hr_employee.py index 0fedc553c86..3c27bf4874c 100644 --- a/addons/hr_presence/models/hr_employee.py +++ b/addons/hr_presence/models/hr_employee.py @@ -28,7 +28,7 @@ class ResCompany(models.Model): @api.model def _check_presence(self): - company = self.env.user.company_id + company = self.env.company_id if not company.hr_presence_last_compute_date or \ company.hr_presence_last_compute_date.day != Datetime.now().day: self.env['hr.employee'].search([ diff --git a/addons/hr_recruitment/models/hr_job.py b/addons/hr_recruitment/models/hr_job.py index a7c13066500..50f63374447 100644 --- a/addons/hr_recruitment/models/hr_job.py +++ b/addons/hr_recruitment/models/hr_job.py @@ -10,7 +10,7 @@ class Job(models.Model): @api.model def _default_address_id(self): - return self.env.user.company_id.partner_id + return self.env.company_id.partner_id def _get_default_favorite_user_ids(self): return [(6, 0, [self.env.uid])] diff --git a/addons/hr_recruitment/models/hr_recruitment.py b/addons/hr_recruitment/models/hr_recruitment.py index 87b93a7a165..4c9c6f63f5b 100644 --- a/addons/hr_recruitment/models/hr_recruitment.py +++ b/addons/hr_recruitment/models/hr_recruitment.py @@ -110,7 +110,7 @@ class Applicant(models.Model): department = self.env['hr.department'].browse(self._context['default_department_id']) company_id = department.company_id.id if not company_id: - company_id = self.env['res.company']._company_default_get('hr.applicant') + company_id = self.env.company_id return company_id name = fields.Char("Subject / Application Name", required=True) diff --git a/addons/hr_recruitment/security/hr_recruitment_security.xml b/addons/hr_recruitment/security/hr_recruitment_security.xml index 85949b967dd..50d5f825ca4 100644 --- a/addons/hr_recruitment/security/hr_recruitment_security.xml +++ b/addons/hr_recruitment/security/hr_recruitment_security.xml @@ -10,7 +10,7 @@ <field name="name">Applicant multi company rule</field> <field name="model_id" ref="model_hr_applicant"/> <field eval="True" name="global"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="group_hr_recruitment_user" model="res.groups"> diff --git a/addons/hr_timesheet/models/hr_timesheet.py b/addons/hr_timesheet/models/hr_timesheet.py index 7d1edf4b2b0..c7f31dee0bb 100644 --- a/addons/hr_timesheet/models/hr_timesheet.py +++ b/addons/hr_timesheet/models/hr_timesheet.py @@ -90,7 +90,7 @@ class AccountAnalyticLine(models.Model): @api.model def _apply_timesheet_label(self, view_arch): doc = etree.XML(view_arch) - encoding_uom = self.env.user.company_id.timesheet_encode_uom_id + encoding_uom = self.env.company_id.timesheet_encode_uom_id # Here, we select only the unit_amount field having no string set to give priority to # custom inheretied view stored in database. Even if normally, no xpath can be done on # 'string' attribute. @@ -159,7 +159,7 @@ class AccountAnalyticLine(models.Model): cost = timesheet.employee_id.timesheet_cost or 0.0 amount = -timesheet.unit_amount * cost amount_converted = timesheet.employee_id.currency_id._convert( - amount, timesheet.account_id.currency_id, self.env.user.company_id, timesheet.date) + amount, timesheet.account_id.currency_id, self.env.company_id, timesheet.date) result[timesheet.id].update({ 'amount': amount_converted, }) diff --git a/addons/hr_timesheet/models/ir_http.py b/addons/hr_timesheet/models/ir_http.py index a0694d71d1b..d20ad2f9d7a 100644 --- a/addons/hr_timesheet/models/ir_http.py +++ b/addons/hr_timesheet/models/ir_http.py @@ -13,7 +13,7 @@ class Http(models.AbstractModel): """ result = super(Http, self).session_info() - company = self.env.user.company_id + company = self.env.company_id encoding_uom = company.timesheet_encode_uom_id result['timesheet_uom'] = encoding_uom.read(['name', 'rounding', 'timesheet_widget'])[0] diff --git a/addons/hr_timesheet/models/project.py b/addons/hr_timesheet/models/project.py index 94f94e13f1d..9a554313cca 100644 --- a/addons/hr_timesheet/models/project.py +++ b/addons/hr_timesheet/models/project.py @@ -49,7 +49,7 @@ class Project(models.Model): if allow_timesheets and not values.get('analytic_account_id'): analytic_account = self.env['account.analytic.account'].create({ 'name': values.get('name', _('Unknown Analytic Account')), - 'company_id': values.get('company_id', self.env.user.company_id.id), + 'company_id': values.get('company_id', self.env.company_id.id), 'partner_id': values.get('partner_id'), 'active': True, }) diff --git a/addons/iap/models/iap.py b/addons/iap/models/iap.py index af375d5050b..122aab66b35 100644 --- a/addons/iap/models/iap.py +++ b/addons/iap/models/iap.py @@ -158,11 +158,11 @@ class IapAccount(models.Model): service_name = fields.Char() account_token = fields.Char(default=lambda s: uuid.uuid4().hex) - company_id = fields.Many2one('res.company', default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', default=lambda self: self.env.company_id) @api.model def get(self, service_name, force_create=True): - account = self.search([('service_name', '=', service_name), ('company_id', 'in', [self.env.user.company_id.id, False])]) + account = self.search([('service_name', '=', service_name), ('company_id', 'in', [self.env.company_id.id, False])]) if not account and force_create: account = self.create({'service_name': service_name}) # Since the account did not exist yet, we will encounter a NoCreditError, diff --git a/addons/iap/security/ir_rule.xml b/addons/iap/security/ir_rule.xml index 2935ce2b746..05e8dcd4b72 100644 --- a/addons/iap/security/ir_rule.xml +++ b/addons/iap/security/ir_rule.xml @@ -5,9 +5,7 @@ <field name="model_id" ref="model_iap_account"/> <field name="groups" eval="[(4, ref('base.group_user'))]"/> <!-- partners can CUD services linked to themselves --> - <field name="domain_force">[ - ('company_id', 'in', [user.company_id.id, False]), - ]</field> + <field name="domain_force">['|', ('company_id', '=', False), ('company_id', 'in', company_ids)]</field> </record> </data> </odoo>
\ No newline at end of file diff --git a/addons/l10n_de/models/chart_template.py b/addons/l10n_de/models/chart_template.py index 0ba279d14e8..fb830340b33 100644 --- a/addons/l10n_de/models/chart_template.py +++ b/addons/l10n_de/models/chart_template.py @@ -17,7 +17,7 @@ class AccountChartTemplate(models.Model): # Write paperformat and report template used on company def load_for_current_company(self, sale_tax_rate, purchase_tax_rate): res = super(AccountChartTemplate, self).load_for_current_company(sale_tax_rate, purchase_tax_rate) - company = self.env.user.company_id + company = self.env.company_id if company.country_id.code == 'DE': company.write({'external_report_layout_id': self.env.ref('l10n_de.external_layout_din5008').id, 'paperformat_id': self.env.ref('l10n_de.paperformat_euro_din').id}) diff --git a/addons/l10n_do/models/chart_template.py b/addons/l10n_do/models/chart_template.py index 7d85be1847b..892cb8582e5 100644 --- a/addons/l10n_do/models/chart_template.py +++ b/addons/l10n_do/models/chart_template.py @@ -9,7 +9,7 @@ class AccountChartTemplate(models.Model): @api.model def _get_default_bank_journals_data(self): - if self.env.user.company_id.country_id and self.env.user.company_id.country_id.code.upper() == 'DO': + if self.env.company_id.country_id and self.env.company_id.country_id.code.upper() == 'DO': return [ {'acc_name': _('Cash'), 'account_type': 'cash'}, {'acc_name': _('Caja Chica'), 'account_type': 'cash'}, diff --git a/addons/l10n_eu_service/wizard/wizard.py b/addons/l10n_eu_service/wizard/wizard.py index 0a96599a28d..2e90c94ecea 100644 --- a/addons/l10n_eu_service/wizard/wizard.py +++ b/addons/l10n_eu_service/wizard/wizard.py @@ -18,7 +18,7 @@ class l10n_eu_service(models.TransientModel): return eu_group def _get_default_company_id(self): - return self.env.user.company_id.id + return self.env.company_id.id def _default_fiscal_position_id(self): user = self.env.user diff --git a/addons/l10n_fr_certification/data/account_move.xml b/addons/l10n_fr_certification/data/account_move.xml index c4d735d2b14..cb72a999561 100644 --- a/addons/l10n_fr_certification/data/account_move.xml +++ b/addons/l10n_fr_certification/data/account_move.xml @@ -5,7 +5,7 @@ <field name="type">ir.actions.server</field> <field name="state">code</field> <field name="code"> - action = env['account.move']._check_hash_integrity(env.user.company_id.id) + action = env['account.move']._check_hash_integrity(env.company_id.id) </field> </record> diff --git a/addons/l10n_fr_certification/models/account.py b/addons/l10n_fr_certification/models/account.py index 208b5238967..a85eaebfebc 100644 --- a/addons/l10n_fr_certification/models/account.py +++ b/addons/l10n_fr_certification/models/account.py @@ -117,7 +117,7 @@ class AccountMove(models.Model): order="l10n_fr_secure_sequence_number ASC") if not moves: - raise UserError(_('There isn\'t any journal entry flagged for data inalterability yet for the company %s. This mechanism only runs for journal entries generated after the installation of the module France - Certification CGI 286 I-3 bis.') % self.env.user.company_id.name) + raise UserError(_('There isn\'t any journal entry flagged for data inalterability yet for the company %s. This mechanism only runs for journal entries generated after the installation of the module France - Certification CGI 286 I-3 bis.') % self.env.company_id.name) previous_hash = u'' start_move_info = [] for move in moves: diff --git a/addons/l10n_fr_fec/wizard/account_fr_fec.py b/addons/l10n_fr_fec/wizard/account_fr_fec.py index 0a6459a0953..0c0ec49558e 100644 --- a/addons/l10n_fr_fec/wizard/account_fr_fec.py +++ b/addons/l10n_fr_fec/wizard/account_fr_fec.py @@ -65,7 +65,7 @@ class AccountFrFec(models.TransientModel): sql_query += ''' AND am.state = 'posted' ''' - company = self.env.user.company_id + company = self.env.company_id formatted_date_from = fields.Date.to_string(self.date_from).replace('-', '') date_from = self.date_from formatted_date_year = date_from.year @@ -108,7 +108,7 @@ class AccountFrFec(models.TransientModel): # 2) CSV files are easier to read/use for a regular accountant. # So it will be easier for the accountant to check the file before # sending it to the fiscal administration - company = self.env.user.company_id + company = self.env.company_id company_legal_data = self._get_company_legal_data(company) header = [ diff --git a/addons/l10n_fr_pos_cert/data/pos_inalterability.xml b/addons/l10n_fr_pos_cert/data/pos_inalterability.xml index 377204b73c6..1026c9b90d2 100644 --- a/addons/l10n_fr_pos_cert/data/pos_inalterability.xml +++ b/addons/l10n_fr_pos_cert/data/pos_inalterability.xml @@ -10,7 +10,7 @@ <field name="type">ir.actions.server</field> <field name="state">code</field> <field name="code"> -action = env['pos.order']._check_hash_integrity(env.user.company_id.id) +action = env['pos.order']._check_hash_integrity(env.company_id.id) </field> </record> diff --git a/addons/l10n_fr_pos_cert/models/pos.py b/addons/l10n_fr_pos_cert/models/pos.py index d74641e3c88..89d027b0123 100644 --- a/addons/l10n_fr_pos_cert/models/pos.py +++ b/addons/l10n_fr_pos_cert/models/pos.py @@ -154,7 +154,7 @@ class pos_order(models.Model): order="l10n_fr_secure_sequence_number ASC") if not orders: - raise UserError(_('There isn\'t any order flagged for data inalterability yet for the company %s. This mechanism only runs for point of sale orders generated after the installation of the module France - Certification CGI 286 I-3 bis. - POS') % self.env.user.company_id.name) + raise UserError(_('There isn\'t any order flagged for data inalterability yet for the company %s. This mechanism only runs for point of sale orders generated after the installation of the module France - Certification CGI 286 I-3 bis. - POS') % self.env.company_id.name) previous_hash = u'' start_order_info = [] for order in orders: diff --git a/addons/l10n_fr_sale_closing/security/account_closing_intercompany.xml b/addons/l10n_fr_sale_closing/security/account_closing_intercompany.xml index 6a8215852aa..a316014794e 100644 --- a/addons/l10n_fr_sale_closing/security/account_closing_intercompany.xml +++ b/addons/l10n_fr_sale_closing/security/account_closing_intercompany.xml @@ -2,7 +2,7 @@ <record model="ir.rule" id="account_sale_closing_multi_company"> <field name="name">Sale Closing multi-company</field> <field name="model_id" ref="model_account_sale_closing"/> - <field name="domain_force">[('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">[('company_id', 'in', company_ids)]</field> </record> </odoo> diff --git a/addons/l10n_generic_coa/data/account_bank_statement_demo.xml b/addons/l10n_generic_coa/data/account_bank_statement_demo.xml index 3f620cb4bb2..8a34bad5be1 100644 --- a/addons/l10n_generic_coa/data/account_bank_statement_demo.xml +++ b/addons/l10n_generic_coa/data/account_bank_statement_demo.xml @@ -4,7 +4,7 @@ <record id="demo_bank_statement_1" model="account.bank.statement"> <field name="journal_id" model="account.journal" search="[ ('type', '=', 'bank'), - ('company_id', '=', obj().env['res.company']._company_default_get('account.journal').id)]"/> + ('company_id', '=', obj().env.company_id.id)]"/> <field name="date" eval="time.strftime('%Y')+'-01-01'"/> <field name="name" eval="'BNK/%s/0001' % time.strftime('%Y')"/> <field name="balance_end_real">8998.2</field> @@ -18,7 +18,7 @@ <field name="name" eval="'INV/%s/0002 and INV/%s/0003' % (time.strftime('%Y'), time.strftime('%Y'))"/> <field name="journal_id" model="account.journal" search="[ ('type', '=', 'bank'), - ('company_id', '=', obj().env['res.company']._company_default_get('account.journal').id)]"/> + ('company_id', '=', obj().env.company_id.id)]"/> <field name="amount">1275.0</field> <field name="date" eval="time.strftime('%Y')+'-01-01'"/> <field name="partner_id" ref="base.res_partner_2"/> @@ -31,7 +31,7 @@ <field name="name">Bank fees</field> <field name="journal_id" model="account.journal" search="[ ('type', '=', 'bank'), - ('company_id', '=', obj().env['res.company']._company_default_get('account.journal').id)]"/> + ('company_id', '=', obj().env.company_id.id)]"/> <field name="amount">-32.58</field> <field name="date" eval="time.strftime('%Y')+'-01-01'"/> </record> @@ -43,7 +43,7 @@ <field name="name">Prepayment</field> <field name="journal_id" model="account.journal" search="[ ('type', '=', 'bank'), - ('company_id', '=', obj().env['res.company']._company_default_get('account.journal').id)]"/> + ('company_id', '=', obj().env.company_id.id)]"/> <field name="amount">650.0</field> <field name="date" eval="time.strftime('%Y')+'-01-01'"/> <field name="partner_id" ref="base.res_partner_12"/> @@ -56,7 +56,7 @@ <field name="name" eval="'First 2000 $ of invoice %s/0001' % time.strftime('%Y')"/> <field name="journal_id" model="account.journal" search="[ ('type', '=', 'bank'), - ('company_id', '=', obj().env['res.company']._company_default_get('account.journal').id)]"/> + ('company_id', '=', obj().env.company_id.id)]"/> <field name="amount">2000.0</field> <field name="date" eval="time.strftime('%Y')+'-01-01'"/> <field name="partner_id" ref="base.res_partner_12"/> @@ -69,7 +69,7 @@ <field name="name">Last Year Interests</field> <field name="journal_id" model="account.journal" search="[ ('type', '=', 'bank'), - ('company_id', '=', obj().env['res.company']._company_default_get('account.journal').id)]"/> + ('company_id', '=', obj().env.company_id.id)]"/> <field name="amount">102.78</field> <field name="date" eval="time.strftime('%Y')+'-01-01'"/> </record> @@ -81,7 +81,7 @@ <field name="name" eval="'INV/'+time.strftime('%Y')+'/0002'"/> <field name="journal_id" model="account.journal" search="[ ('type', '=', 'bank'), - ('company_id', '=', obj().env['res.company']._company_default_get('account.journal').id)]"/> + ('company_id', '=', obj().env.company_id.id)]"/> <field name="amount">750.0</field> <field name="date" eval="time.strftime('%Y')+'-01-01'"/> <field name="partner_id" ref="base.res_partner_2"/> diff --git a/addons/l10n_generic_coa/data/account_invoice_demo.xml b/addons/l10n_generic_coa/data/account_invoice_demo.xml index 667c2445054..47cefa73854 100644 --- a/addons/l10n_generic_coa/data/account_invoice_demo.xml +++ b/addons/l10n_generic_coa/data/account_invoice_demo.xml @@ -168,7 +168,7 @@ <field name="account_id" model="account.account" search="['|', ('tag_ids', '=', ref('account.demo_ceo_wages_account')), ('user_type_id', '=', ref('account.data_account_type_expenses')), - ('company_id', '=', obj().env['res.company']._company_default_get('account.account').id)]"/> + ('company_id', '=', obj().env.company_id.id)]"/> </record> <function model="account.invoice" name="action_invoice_open"> <value eval="[ref('demo_invoice_january_wages')]"/> @@ -189,12 +189,12 @@ <field name="account_id" model="account.account" search="['|', ('tag_ids', '=', ref('account.demo_office_furniture_account')), ('user_type_id', '=', ref('account.data_account_type_expenses')), - ('company_id', '=', obj().env['res.company']._company_default_get('account.account').id)]"/> + ('company_id', '=', obj().env.company_id.id)]"/> <field name="invoice_line_tax_ids" model="account.tax" eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'purchase'), ('amount', '>', 0), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <function model="account.invoice" name="_onchange_invoice_line_ids"> @@ -209,7 +209,7 @@ <field name="account_id" model="account.account" search="[ ('user_type_id', '=', ref('account.data_account_type_revenue')), ('tag_ids', 'in', [ref('account.account_tag_financing')]), - ('company_id', '=', obj().env['res.company']._company_default_get('account.account').id)]"/> + ('company_id', '=', obj().env.company_id.id)]"/> </record> <function model="account.bank.statement.line" name="fast_counterpart_creation"> diff --git a/addons/l10n_in/data/account_invoice_demo.xml b/addons/l10n_in/data/account_invoice_demo.xml index 9fa88d1a6ad..a740c459694 100644 --- a/addons/l10n_in/data/account_invoice_demo.xml +++ b/addons/l10n_in/data/account_invoice_demo.xml @@ -23,7 +23,7 @@ eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), ('children_tax_ids.amount','=', 14), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <record id="demo_invoice_b2b_line_2" model="account.invoice.line"> <field name="name" model="account.invoice.line" eval="obj().env.ref('product.product_product_9').partner_ref"/> @@ -37,7 +37,7 @@ eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), ('children_tax_ids.amount','=', 9), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <record id="demo_invoice_b2b_line_3" model="account.invoice.line"> <field name="name" model="account.invoice.line" eval="obj().env.ref('product.product_product_10').partner_ref"/> @@ -50,7 +50,7 @@ <field name="invoice_line_tax_ids" model="account.tax" eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id), + ('company_id', '=', obj().env.company_id.id), '|', ('children_tax_ids.amount', '=', 9), '&', @@ -89,7 +89,7 @@ eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), ('children_tax_ids.amount','=', 9), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <record id="demo_invoice_b2cs_line_2" model="account.invoice.line"> <field name="name" model="account.invoice.line" eval="obj().env.ref('product.product_product_20').partner_ref"/> @@ -103,7 +103,7 @@ eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), ('children_tax_ids.amount','=', 9), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <record id="demo_invoice_b2cs_line_3" model="account.invoice.line"> <field name="name" model="account.invoice.line" eval="obj().env.ref('product.product_product_22').partner_ref"/> @@ -117,7 +117,7 @@ eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), ('children_tax_ids.amount','=', 2.5), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <record id="demo_invoice_b2cs_line_4" model="account.invoice.line"> <field name="name" model="account.invoice.line" eval="obj().env.ref('product.product_product_24').partner_ref"/> @@ -131,7 +131,7 @@ eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), ('children_tax_ids.amount','=', 2.5), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <function model="account.invoice" name="_onchange_invoice_line_ids"> @@ -164,7 +164,7 @@ ('type_tax_use', '=', 'sale'), ('tax_group_id', '=', obj().env.ref('l10n_in.igst_group').id), ('amount','=', 18), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <function model="account.invoice" name="_onchange_invoice_line_ids"> @@ -187,7 +187,7 @@ eval="obj().search([ ('type', '=', 'sale'), ('l10n_in_import_export', '=', True), - ('company_id', '=', obj().env['res.company']._company_default_get('account.journal').id)], limit=1).id + ('company_id', '=', obj().env.company_id.id)], limit=1).id or obj().search([('type', '=', 'sale')], limit=1).id"/> <field name="l10n_in_shipping_bill_number">999704</field> <field name="l10n_in_shipping_bill_date" eval="time.strftime('%Y-%m')+'-02'"/> @@ -207,7 +207,7 @@ ('type_tax_use', '=', 'sale'), ('tax_group_id', '=', obj().env.ref('l10n_in.igst_group').id), ('amount','=', 18), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <function model="account.invoice" name="_onchange_invoice_line_ids"> @@ -239,7 +239,7 @@ eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), ('tax_group_id', '=', obj().env.ref('l10n_in.exempt_group').id), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <record id="demo_invoice_nill_line_2" model="account.invoice.line"> <field name="name" model="account.invoice.line" eval="obj().env.ref('product.product_product_5').partner_ref"/> @@ -253,7 +253,7 @@ eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), ('tax_group_id', '=', obj().env.ref('l10n_in.nil_rated_group').id), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> @@ -289,7 +289,7 @@ eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), ('children_tax_ids.amount','=', 14), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <record id="demo_invoice_cdnr_line_2" model="account.invoice.line"> <field name="name" model="account.invoice.line" eval="obj().env.ref('product.product_product_9').partner_ref"/> @@ -303,7 +303,7 @@ eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), ('children_tax_ids.amount','=', 9), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <record id="demo_invoice_cdnr_line_3" model="account.invoice.line"> <field name="name" model="account.invoice.line" eval="obj().env.ref('product.product_product_10').partner_ref"/> @@ -316,7 +316,7 @@ <field name="invoice_line_tax_ids" model="account.tax" eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id), + ('company_id', '=', obj().env.company_id.id), '|', ('children_tax_ids.amount', '=', 9), '&', @@ -356,7 +356,7 @@ eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), ('children_tax_ids.amount','=', 9), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <function model="account.invoice" name="_onchange_invoice_line_ids"> @@ -389,7 +389,7 @@ eval="[(6, 0, obj().search([ ('type_tax_use', '=', 'sale'), ('children_tax_ids.amount','=', 9), - ('company_id', '=', obj().env['res.company']._company_default_get('account.tax').id)], limit=1).ids)]"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).ids)]"/> </record> <function model="account.invoice" name="_onchange_invoice_line_ids"> diff --git a/addons/l10n_in/data/account_payment_demo.xml b/addons/l10n_in/data/account_payment_demo.xml index 86e881746bf..bc2f31b8bb7 100644 --- a/addons/l10n_in/data/account_payment_demo.xml +++ b/addons/l10n_in/data/account_payment_demo.xml @@ -11,11 +11,11 @@ <field name="journal_id" model="account.journal" eval="obj().search([ ('type', '=', 'cash'), - ('company_id', '=', obj().env['res.company']._company_default_get('account.journal').id)], limit=1).id"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).id"/> <field name="payment_method_id" model="account.journal" eval="obj().search([ ('type', '=', 'cash'), - ('company_id', '=', obj().env['res.company']._company_default_get('account.journal').id)], limit=1).inbound_payment_method_ids[0].id"/> + ('company_id', '=', obj().env.company_id.id)], limit=1).inbound_payment_method_ids[0].id"/> </record> <function model="account.payment" name="post"> diff --git a/addons/l10n_it_edi/models/account_invoice.py b/addons/l10n_it_edi/models/account_invoice.py index b0f801558aa..6b027bc6354 100644 --- a/addons/l10n_it_edi/models/account_invoice.py +++ b/addons/l10n_it_edi/models/account_invoice.py @@ -271,16 +271,16 @@ class AccountInvoice(models.Model): message = self.env['mail.message'].create({ 'subject': _('Sending file: %s') % (self.l10n_it_einvoice_id.name), - 'body': _('Sending file: %s to ES: %s') % (self.l10n_it_einvoice_id.name, self.env.user.company_id.l10n_it_address_recipient_fatturapa), + 'body': _('Sending file: %s to ES: %s') % (self.l10n_it_einvoice_id.name, self.env.company_id.l10n_it_address_recipient_fatturapa), 'author_id': self.env.user.partner_id.id, - 'email_from': self.env.user.company_id.l10n_it_address_send_fatturapa, - 'mail_server_id': self.env.user.company_id.l10n_it_mail_pec_server_id.id, + 'email_from': self.env.company_id.l10n_it_address_send_fatturapa, + 'mail_server_id': self.env.company_id.l10n_it_mail_pec_server_id.id, 'attachment_ids': [(6, 0, self.l10n_it_einvoice_id.ids)], }) mail_fattura = self.env['mail.mail'].create({ 'mail_message_id': message.id, - 'email_to': self.env.user.company_id.l10n_it_address_recipient_fatturapa, + 'email_to': self.env.company_id.l10n_it_address_recipient_fatturapa, }) try: mail_fattura.send(raise_exception=True) @@ -332,15 +332,15 @@ class AccountInvoice(models.Model): if company: self_ctx = self_ctx.with_context(company_id=company.id) else: - company = self.env.user.company_id + company = self.env.company_id if elements: _logger.info(_('Company not found with codice fiscale: %s. The company\'s user is set by default.') % elements[0].text) else: _logger.info(_('Company not found. The company\'s user is set by default.')) if not self.env.user._is_superuser(): - if self.env.user.company_id != company: - raise UserError(_("You can only import invoice concern your current company: %s") % self.env.user.company_id.display_name) + if self.env.company_id != company: + raise UserError(_("You can only import invoice concern your current company: %s") % self.env.company_id.display_name) journal_id = self_ctx._default_journal().id self_ctx = self_ctx.with_context(journal_id=journal_id) @@ -395,7 +395,7 @@ class AccountInvoice(models.Model): if elements: currency_str = elements[0].text currency = self.env.ref('base.%s' % currency_str.upper(), raise_if_not_found=False) - if currency != self.env.user.company_id.currency_id and currency.active: + if currency != self.env.company_id.currency_id and currency.active: invoice_form.currency_id = currency # Date. <2.1.1.3> diff --git a/addons/l10n_nl/models/account_chart_template.py b/addons/l10n_nl/models/account_chart_template.py index 483ce15650c..d7a4a2ae75d 100644 --- a/addons/l10n_nl/models/account_chart_template.py +++ b/addons/l10n_nl/models/account_chart_template.py @@ -9,8 +9,8 @@ class AccountChartTemplate(models.Model): def load_for_current_company(self, sale_tax_rate, purchase_tax_rate): # Add tag to 999999 account res = super(AccountChartTemplate, self).load_for_current_company(sale_tax_rate, purchase_tax_rate) - if self.env.user.company_id.country_id.code == 'NL': - account = self.env['account.account'].search([('code', '=', '999999'), ('company_id', '=', self.env.user.company_id.id)]) + if self.env.company_id.country_id.code == 'NL': + account = self.env['account.account'].search([('code', '=', '999999'), ('company_id', '=', self.env.company_id.id)]) if account: account.tag_ids = [(4, self.env.ref('l10n_nl.account_tag_12').id)] return res diff --git a/addons/lunch/models/lunch_cashmove.py b/addons/lunch/models/lunch_cashmove.py index dab6faccbd1..d04d3b79d32 100644 --- a/addons/lunch/models/lunch_cashmove.py +++ b/addons/lunch/models/lunch_cashmove.py @@ -11,7 +11,7 @@ class LunchCashMove(models.Model): _description = 'Lunch Cashmove' _order = 'date desc' - currency_id = fields.Many2one('res.currency', default=lambda self: self.env['res.company']._company_default_get()) + currency_id = fields.Many2one('res.currency', default=lambda self: self.env.company_id) user_id = fields.Many2one('res.users', 'User', default=lambda self: self.env.uid) date = fields.Date('Date', required=True, default=fields.Date.context_today) diff --git a/addons/lunch/models/lunch_order.py b/addons/lunch/models/lunch_order.py index ee3f01c6d44..ba447ab394e 100644 --- a/addons/lunch/models/lunch_order.py +++ b/addons/lunch/models/lunch_order.py @@ -36,7 +36,7 @@ class LunchOrder(models.Model): ('confirmed', 'Received'), ('cancelled', 'Cancelled')], 'Status', readonly=True, index=True, default='new') - company_id = fields.Many2one('res.company', related='user_id.company_id', store=True) + company_id = fields.Many2one('res.company', default=lambda self: self.env.company_id.id) currency_id = fields.Many2one('res.currency', related='company_id.currency_id', readonly=True, store=True) quantity = fields.Float('Quantity', required=True, default=1) diff --git a/addons/lunch/models/lunch_product.py b/addons/lunch/models/lunch_product.py index 6d4132d9bde..5623bce8de1 100644 --- a/addons/lunch/models/lunch_product.py +++ b/addons/lunch/models/lunch_product.py @@ -13,7 +13,7 @@ class LunchProductCategory(models.Model): _description = 'Lunch Product Category' name = fields.Char('Product Category', required=True) - company_id = fields.Many2one('res.company', default=lambda self: self.env['res.company']._company_default_get()) + company_id = fields.Many2one('res.company', default=lambda self: self.env.company_id) currency_id = fields.Many2one('res.currency', related='company_id.currency_id') topping_label_1 = fields.Char('Topping Label 1', required=True, default='Supplements') topping_label_2 = fields.Char('Topping Label 2', required=True, default='Beverages') @@ -60,14 +60,14 @@ class LunchTopping(models.Model): _description = 'Lunch Toppings' name = fields.Char('Name', required=True) - company_id = fields.Many2one('res.company', default=lambda self: self.env['res.company']._company_default_get()) + company_id = fields.Many2one('res.company', default=lambda self: self.env.company_id) currency_id = fields.Many2one('res.currency', related='company_id.currency_id') price = fields.Float('Price', digits=dp.get_precision('Account'), required=True) category_id = fields.Many2one('lunch.product.category') topping_category = fields.Integer('Topping Category', help="This field is a technical field", required=True, default=1) def name_get(self): - currency_id = self.env.user.company_id.currency_id + currency_id = self.env.company_id.currency_id res = dict(super(LunchTopping, self).name_get()) for topping in self: price = formatLang(self.env, topping.price, currency_obj=currency_id) @@ -88,7 +88,7 @@ class LunchProduct(models.Model): supplier_id = fields.Many2one('lunch.supplier', 'Vendor', required=True) active = fields.Boolean(default=True) - company_id = fields.Many2one('res.company', default=lambda self: self.env['res.company']._company_default_get()) + company_id = fields.Many2one('res.company', default=lambda self: self.env.company_id) currency_id = fields.Many2one('res.currency', related='company_id.currency_id') # image: all image fields are base64 encoded and PIL-supported diff --git a/addons/lunch/wizard/lunch_line_wizard.py b/addons/lunch/wizard/lunch_line_wizard.py index 2006144e582..989d3a0acc8 100644 --- a/addons/lunch/wizard/lunch_line_wizard.py +++ b/addons/lunch/wizard/lunch_line_wizard.py @@ -21,7 +21,7 @@ class LunchOrderWizard(models.TransientModel): order="date desc, id desc", limit=1) return last_time_ordered - currency_id = fields.Many2one('res.currency', default=lambda self: self.env.user.company_id.currency_id) + currency_id = fields.Many2one('res.currency', default=lambda self: self.env.company_id.currency_id) product_id = fields.Many2one('lunch.product', string='Product ID') product_description = fields.Text('Description', related='product_id.description') diff --git a/addons/mail/controllers/main.py b/addons/mail/controllers/main.py index 6b8cf59ccdc..611db76e980 100644 --- a/addons/mail/controllers/main.py +++ b/addons/mail/controllers/main.py @@ -52,6 +52,7 @@ class MailController(http.Controller): # access_token and kwargs are used in the portal controller override for the Send by email or Share Link # to give access to the record to a recipient that has normally no access. uid = request.session.uid + user = request.env['res.users'].sudo().browse(uid) # no model / res_id, meaning no possible record -> redirect to login if not model or not res_id or model not in request.env: @@ -69,7 +70,33 @@ class MailController(http.Controller): if not RecordModel.sudo(uid).check_access_rights('read', raise_exception=False): return cls._redirect_to_messaging() try: - record_sudo.sudo(uid).check_access_rule('read') + # We need here to extend the "allowed_company_ids" to allow a redirection + # to any record that the user can access, regardless of currently visible + # records based on the "currently allowed companies". + cids = request.httprequest.cookies.get('cids', str(request.env.user.company_id)) + cids = [int(cid) for cid in cids.split(',')] + try: + record_sudo.sudo(uid).with_context(allowed_company_ids=cids).check_access_rule('read') + except AccessError: + # In case the allowed_company_ids from the cookies (i.e. the last user configuration + # on his browser) is not sufficient to avoid an ir.rule access error, try to following + # heuristic: + # - Guess the supposed necessary company to access the record via the method + # _get_mail_redirect_suggested_company + # - If no company, then redirect to the messaging + # - If the multi company per tag group is activated, merge the suggested company + # withe the companies on the cookie + # - else, use this company as enabled company + # - Make a new access test if it succeeds, redirect to the record. Otherwise, + # redirect to the messaging. + suggested_company = record_sudo._get_mail_redirect_suggested_company() + if not suggested_company: + raise AccessError() + if user.has_group('base.group_toggle_company'): + cids += [suggested_company] + else: + cids = [suggested_company] + record_sudo.sudo(uid).with_context(allowed_company_ids=cids).check_access_rule('read') except AccessError: return cls._redirect_to_messaging() else: @@ -98,6 +125,7 @@ class MailController(http.Controller): if view_id: url_params['view_id'] = view_id + url_params['cids'] = ','.join([str(cid) for cid in cids]) url = '/web?#%s' % url_encode(url_params) return werkzeug.utils.redirect(url) diff --git a/addons/mail/models/mail_message.py b/addons/mail/models/mail_message.py index ba3108d61f6..f59f26e0a66 100644 --- a/addons/mail/models/mail_message.py +++ b/addons/mail/models/mail_message.py @@ -1225,7 +1225,7 @@ class Message(models.Model): if self.env.user.partner_id.email: email_from = formataddr((self.env.user.partner_id.name, self.env.user.partner_id.email)) else: - email_from = self.env.user.company_id.catchall + email_from = self.env.company_id.catchall body_html = tools.append_content_to_html('<div>%s</div>' % tools.ustr(comment), msg.body) vals = { diff --git a/addons/mail/models/mail_template.py b/addons/mail/models/mail_template.py index 5a6d21b825f..c3caa10c33b 100644 --- a/addons/mail/models/mail_template.py +++ b/addons/mail/models/mail_template.py @@ -535,7 +535,7 @@ class MailTemplate(models.Model): template_ctx = { 'message': self.env['mail.message'].sudo().new(dict(body=values['body_html'], record_name=record.display_name)), 'model_description': self.env['ir.model']._get(record._name).display_name, - 'company': 'company_id' in record and record['company_id'] or self.env.user.company_id, + 'company': 'company_id' in record and record['company_id'] or self.env.company_id, } body = template.render(template_ctx, engine='ir.qweb', minimal_qcontext=True) values['body_html'] = self.env['mail.thread']._replace_local_links(body) diff --git a/addons/mail/models/mail_thread.py b/addons/mail/models/mail_thread.py index 81f1dc0510b..dc8e2db4a62 100644 --- a/addons/mail/models/mail_thread.py +++ b/addons/mail/models/mail_thread.py @@ -867,7 +867,7 @@ class MailThread(models.AbstractModel): result_email.update(dict((rid, '%s@%s' % (catchall, alias_domain)) for rid in left_ids)) # compute name of reply-to - TDE tocheck: quotes and stuff like that - company_name = company.name if company else self.env.user.company_id.name + company_name = company.name if company else self.env.company_id.name for res_id in result_email.keys(): name = '%s%s%s' % (company_name, ' ' if doc_names.get(res_id) else '', doc_names.get(res_id, '')) result[res_id] = formataddr((name, result_email[res_id])) @@ -1260,7 +1260,7 @@ class MailThread(models.AbstractModel): body = self.env.ref('mail.mail_bounce_catchall').render({ 'message': message, }, engine='ir.qweb') - self._routing_create_bounce_email(email_from, body, message, reply_to=self.env.user.company_id.email) + self._routing_create_bounce_email(email_from, body, message, reply_to=self.env.company_id.email) return [] dest_aliases = Alias.search([('alias_name', 'in', rcpt_tos_localparts)]) @@ -2435,3 +2435,17 @@ class MailThread(models.AbstractModel): self._message_auto_subscribe_notify(pids, template) return True + + def _get_mail_redirect_suggested_company(self): + """ Return the suggested company to be set on the context + in case of a mail redirection to the record. To avoid multi + company issues when clicking on a link sent by email, this + could be called to try setting the most suited company on + the allowed_company_ids in the context. This method can be + overriden, for example on the hr.leave model, where the + most suited company is the company of the leave type, as + specified by the ir.rule. + """ + if 'company_id' in self: + return self.company_id + return False diff --git a/addons/maintenance/models/maintenance.py b/addons/maintenance/models/maintenance.py index 6f7ace29554..4961b367fbf 100644 --- a/addons/maintenance/models/maintenance.py +++ b/addons/maintenance/models/maintenance.py @@ -32,7 +32,7 @@ class MaintenanceEquipmentCategory(models.Model): name = fields.Char('Category Name', required=True, translate=True) company_id = fields.Many2one('res.company', string='Company', - default=lambda self: self.env.user.company_id) + default=lambda self: self.env.company_id) technician_user_id = fields.Many2one('res.users', 'Responsible', tracking=True, default=lambda self: self.env.uid, oldname='user_id') color = fields.Integer('Color Index') note = fields.Text('Comments', translate=True) @@ -123,7 +123,7 @@ class MaintenanceEquipment(models.Model): name = fields.Char('Equipment Name', required=True, translate=True) company_id = fields.Many2one('res.company', string='Company', - default=lambda self: self.env.user.company_id) + default=lambda self: self.env.company_id) active = fields.Boolean(default=True) technician_user_id = fields.Many2one('res.users', string='Technician', tracking=True, oldname='user_id') owner_user_id = fields.Many2one('res.users', string='Owner', tracking=True) @@ -277,14 +277,14 @@ class MaintenanceRequest(models.Model): def _get_default_team_id(self): MT = self.env['maintenance.team'] - team = MT.search([('company_id', '=', self.env.user.company_id.id)], limit=1) + team = MT.search([('company_id', '=', self.env.company_id.id)], limit=1) if not team: team = MT.search([], limit=1) return team.id name = fields.Char('Subjects', required=True) company_id = fields.Many2one('res.company', string='Company', - default=lambda self: self.env.user.company_id) + default=lambda self: self.env.company_id) description = fields.Text('Description') request_date = fields.Date('Request Date', tracking=True, default=fields.Date.context_today, help="Date requested for the maintenance to happen") @@ -404,7 +404,7 @@ class MaintenanceTeam(models.Model): name = fields.Char(required=True, translate=True) active = fields.Boolean(default=True) company_id = fields.Many2one('res.company', string='Company', - default=lambda self: self.env.user.company_id) + default=lambda self: self.env.company_id) member_ids = fields.Many2many('res.users', 'maintenance_team_users_rel', string="Team Members") color = fields.Integer("Color Index", default=0) request_ids = fields.One2many('maintenance.request', 'maintenance_team_id', copy=False) diff --git a/addons/maintenance/security/maintenance.xml b/addons/maintenance/security/maintenance.xml index 75a53c685d3..047c5c9ef45 100644 --- a/addons/maintenance/security/maintenance.xml +++ b/addons/maintenance/security/maintenance.xml @@ -41,28 +41,28 @@ <field name="name">Maintenance Request Multi-company rule</field> <field name="model_id" ref="model_maintenance_request"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="maintenance_equipment_comp_rule" model="ir.rule"> <field name="name">Maintenance Equipment Multi-company rule</field> <field name="model_id" ref="model_maintenance_equipment"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="maintenance_team_comp_rule" model="ir.rule"> <field name="name">Maintenance Team Multi-company rule</field> <field name="model_id" ref="model_maintenance_team"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="maintenance_equipment_category_comp_rule" model="ir.rule"> <field name="name">Maintenance Equipment Category Multi-company rule</field> <field name="model_id" ref="model_maintenance_equipment_category"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="base.user_admin" model="res.users"> diff --git a/addons/maintenance/tests/test_maintenance_multicompany.py b/addons/maintenance/tests/test_maintenance_multicompany.py index e9c3df06e54..39b4be27a8d 100644 --- a/addons/maintenance/tests/test_maintenance_multicompany.py +++ b/addons/maintenance/tests/test_maintenance_multicompany.py @@ -34,10 +34,10 @@ class TestEquipmentMulticompany(TransactionCase): company_b = ResCompany.create({ 'name': 'Company B', 'currency_id': self.env.ref('base.USD').id, - 'parent_id': company_a.id, }) # Create equipment manager. + cids = [company_a.id, company_b.id] equipment_manager = ResUsers.create({ 'name': 'Equipment Manager', 'company_id': company_a.id, @@ -63,7 +63,7 @@ class TestEquipmentMulticompany(TransactionCase): 'company_id': company_a.id, }) # create a maintenance team for company B user - teamb = MaintenanceTeam.sudo(equipment_manager).create({ + teamb = MaintenanceTeam.sudo(equipment_manager).with_context(allowed_company_ids=cids).create({ 'name': 'Subcontractor', 'company_id': company_b.id, }) @@ -77,14 +77,14 @@ class TestEquipmentMulticompany(TransactionCase): }) # create equipment category for equipment manager - category_1 = Category.sudo(equipment_manager).create({ + category_1 = Category.sudo(equipment_manager).with_context(allowed_company_ids=cids).create({ 'name': 'Monitors', 'company_id': company_b.id, 'technician_user_id': equipment_manager.id, }) # create equipment category for equipment manager - Category.sudo(equipment_manager).create({ + Category.sudo(equipment_manager).with_context(allowed_company_ids=cids).create({ 'name': 'Computers', 'company_id': company_b.id, 'technician_user_id': equipment_manager.id, @@ -98,7 +98,7 @@ class TestEquipmentMulticompany(TransactionCase): }) # Check category for user equipment_manager and user - self.assertEquals(Category.sudo(equipment_manager).search_count([]), 3) + self.assertEquals(Category.sudo(equipment_manager).with_context(allowed_company_ids=cids).search_count([]), 3) self.assertEquals(Category.sudo(user).search_count([]), 2) # User should not able to create equipment. @@ -111,16 +111,16 @@ class TestEquipmentMulticompany(TransactionCase): 'owner_user_id': user.id, }) - Equipment.sudo(equipment_manager).create({ - 'name': 'Acer Laptop', - 'category_id': category_1.id, - 'assign_date': time.strftime('%Y-%m-%d'), - 'company_id': company_b.id, - 'owner_user_id': user.id, - }) + Equipment.sudo(equipment_manager).with_context(allowed_company_ids=cids).create({ + 'name': 'Acer Laptop', + 'category_id': category_1.id, + 'assign_date': time.strftime('%Y-%m-%d'), + 'company_id': company_b.id, + 'owner_user_id': user.id, + }) # create an equipment for user - Equipment.sudo(equipment_manager).create({ + Equipment.sudo(equipment_manager).with_context(allowed_company_ids=cids).create({ 'name': 'HP Laptop', 'category_id': category_1.id, 'assign_date': time.strftime('%Y-%m-%d'), @@ -128,7 +128,7 @@ class TestEquipmentMulticompany(TransactionCase): 'owner_user_id': equipment_manager.id, }) # Now there are total 2 equipments created and can view by equipment_manager user - self.assertEquals(Equipment.sudo(equipment_manager).search_count([]), 2) + self.assertEquals(Equipment.sudo(equipment_manager).with_context(allowed_company_ids=cids).search_count([]), 2) # And there is total 1 equipment can be view by Normal User ( Which user is followers) self.assertEquals(Equipment.sudo(user).search_count([]), 1) @@ -171,5 +171,5 @@ class TestEquipmentMulticompany(TransactionCase): }) # Now here is total 1 maintenance request can be view by Normal User - self.assertEquals(MaintenanceRequest.sudo(equipment_manager).search_count([]), 2) + self.assertEquals(MaintenanceRequest.sudo(equipment_manager).with_context(allowed_company_ids=cids).search_count([]), 2) self.assertEquals(MaintenanceRequest.sudo(user).search_count([]), 1) diff --git a/addons/mrp/models/mrp_bom.py b/addons/mrp/models/mrp_bom.py index 4aa6117ac35..35469a354f1 100644 --- a/addons/mrp/models/mrp_bom.py +++ b/addons/mrp/models/mrp_bom.py @@ -59,7 +59,7 @@ class MrpBom(models.Model): "to define stock rules which trigger different manufacturing orders with different BoMs.") company_id = fields.Many2one( 'res.company', 'Company', - default=lambda self: self.env['res.company']._company_default_get('mrp.bom'), + default=lambda self: self.env.company_id, required=True) consumption = fields.Selection([ ('strict', 'Strict'), diff --git a/addons/mrp/models/mrp_production.py b/addons/mrp/models/mrp_production.py index 86ddf6bc6fc..dee10ac4f15 100644 --- a/addons/mrp/models/mrp_production.py +++ b/addons/mrp/models/mrp_production.py @@ -23,7 +23,7 @@ class MrpProduction(models.Model): def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'mrp_operation'), - ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], + ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.company_id.id), False])], limit=1).id @api.model @@ -36,7 +36,7 @@ class MrpProduction(models.Model): try: location.check_access_rule('read') except (AttributeError, AccessError): - location = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.company_id.id)], limit=1).lot_stock_id + location = self.env['stock.warehouse'].search([('company_id', '=', self.env.company_id.id)], limit=1).lot_stock_id return location and location.id or False @api.model @@ -49,7 +49,7 @@ class MrpProduction(models.Model): try: location.check_access_rule('read') except (AttributeError, AccessError): - location = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.company_id.id)], limit=1).lot_stock_id + location = self.env['stock.warehouse'].search([('company_id', '=', self.env.company_id.id)], limit=1).lot_stock_id return location and location.id or False name = fields.Char( @@ -180,7 +180,7 @@ class MrpProduction(models.Model): user_id = fields.Many2one('res.users', 'Responsible', default=lambda self: self._uid) company_id = fields.Many2one( 'res.company', 'Company', - default=lambda self: self.env['res.company']._company_default_get('mrp.production'), + default=lambda self: self.env.company_id, required=True) qty_produced = fields.Float(compute="_get_produced_qty", string="Quantity Produced") @@ -420,7 +420,7 @@ class MrpProduction(models.Model): try: location.check_access_rule('read') except (AttributeError, AccessError): - location = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.company_id.id)], limit=1).lot_stock_id + location = self.env['stock.warehouse'].search([('company_id', '=', self.env.company_id.id)], limit=1).lot_stock_id self.move_raw_ids.update({'picking_type_id': self.picking_type_id}) self.location_src_id = self.picking_type_id.default_location_src_id.id or location.id self.location_dest_id = self.picking_type_id.default_location_dest_id.id or location.id diff --git a/addons/mrp/models/mrp_routing.py b/addons/mrp/models/mrp_routing.py index 3c907802074..e2149c8b516 100644 --- a/addons/mrp/models/mrp_routing.py +++ b/addons/mrp/models/mrp_routing.py @@ -22,7 +22,7 @@ class MrpRouting(models.Model): copy=True, oldname='workcenter_lines') company_id = fields.Many2one( 'res.company', 'Company', - default=lambda self: self.env['res.company']._company_default_get('mrp.routing')) + default=lambda self: self.env.company_id) @api.model def create(self, vals): diff --git a/addons/mrp/models/mrp_unbuild.py b/addons/mrp/models/mrp_unbuild.py index 2bac0c1d0f7..0b907d38d37 100644 --- a/addons/mrp/models/mrp_unbuild.py +++ b/addons/mrp/models/mrp_unbuild.py @@ -18,7 +18,7 @@ class MrpUnbuild(models.Model): stock_location.check_access_rule('read') return stock_location.id except (AttributeError, AccessError): - return self.env['stock.warehouse'].search([('company_id', '=', self.env.user.company_id.id)], limit=1).lot_stock_id.id + return self.env['stock.warehouse'].search([('company_id', '=', self.env.company_id.id)], limit=1).lot_stock_id.id def _get_default_location_dest_id(self): stock_location = self.env.ref('stock.stock_location_stock', raise_if_not_found=False) @@ -26,7 +26,7 @@ class MrpUnbuild(models.Model): stock_location.check_access_rule('read') return stock_location.id except (AttributeError, AccessError): - return self.env['stock.warehouse'].search([('company_id', '=', self.env.user.company_id.id)], limit=1).lot_stock_id.id + return self.env['stock.warehouse'].search([('company_id', '=', self.env.company_id.id)], limit=1).lot_stock_id.id name = fields.Char('Reference', copy=False, readonly=True, default=lambda x: _('New')) product_id = fields.Many2one( diff --git a/addons/mrp/report/mrp_report_bom_structure.py b/addons/mrp/report/mrp_report_bom_structure.py index b95c1bcf658..1ac6cee9dce 100644 --- a/addons/mrp/report/mrp_report_bom_structure.py +++ b/addons/mrp/report/mrp_report_bom_structure.py @@ -58,7 +58,7 @@ class ReportBomStructure(models.AbstractModel): lines = self._get_operation_line(bom.routing_id, float_round(qty / bom.product_qty, precision_rounding=1, rounding_method='UP'), level) values = { 'bom_id': bom_id, - 'currency': self.env.user.company_id.currency_id, + 'currency': self.env.company_id.currency_id, 'operations': lines, } return self.env.ref('mrp.report_mrp_operation_line').render({'data': values}) @@ -111,7 +111,7 @@ class ReportBomStructure(models.AbstractModel): 'bom': bom, 'bom_qty': bom_quantity, 'bom_prod_name': product.display_name, - 'currency': self.env.user.company_id.currency_id, + 'currency': self.env.company_id.currency_id, 'product': product, 'code': bom and bom.display_name or '', 'price': product.uom_id._compute_price(product.standard_price, bom.product_uom_id) * bom_quantity, @@ -140,14 +140,14 @@ class ReportBomStructure(models.AbstractModel): sub_total = self._get_price(line.child_bom_id, factor, line.product_id) else: sub_total = price - sub_total = self.env.user.company_id.currency_id.round(sub_total) + sub_total = self.env.company_id.currency_id.round(sub_total) components.append({ 'prod_id': line.product_id.id, 'prod_name': line.product_id.display_name, 'code': line.child_bom_id and line.child_bom_id.display_name or '', 'prod_qty': line_quantity, 'prod_uom': line.product_uom_id.name, - 'prod_cost': self.env.user.company_id.currency_id.round(price), + 'prod_cost': self.env.company_id.currency_id.round(price), 'parent_id': bom.id, 'line_id': line.id, 'level': level or 0, @@ -173,7 +173,7 @@ class ReportBomStructure(models.AbstractModel): 'operation': operation, 'name': operation.name + ' - ' + operation.workcenter_id.name, 'duration_expected': duration_expected, - 'total': self.env.user.company_id.currency_id.round(total), + 'total': self.env.company_id.currency_id.round(total), }) return operations @@ -200,7 +200,7 @@ class ReportBomStructure(models.AbstractModel): else: prod_qty = line.product_qty * factor not_rounded_price = line.product_id.uom_id._compute_price(line.product_id.standard_price, line.product_uom_id) * prod_qty - price += self.env.user.company_id.currency_id.round(not_rounded_price) + price += self.env.company_id.currency_id.round(not_rounded_price) return price def _get_pdf_line(self, bom_id, product_id=False, qty=1, child_bom_ids=[], unfolded=False): diff --git a/addons/mrp/security/mrp_security.xml b/addons/mrp/security/mrp_security.xml index cc5a3562435..6c346375b9f 100644 --- a/addons/mrp/security/mrp_security.xml +++ b/addons/mrp/security/mrp_security.xml @@ -35,35 +35,35 @@ <field name="name">mrp_production multi-company</field> <field name="model_id" search="[('model','=','mrp.production')]" model="ir.model"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','child_of',[user.company_id.id]),('company_id','=',False)]</field> + <field name="domain_force">['|',('company_id', 'in', company_ids),('company_id','=',False)]</field> </record> <record model="ir.rule" id="mrp_workcenter_rule"> <field name="name">mrp_workcenter multi-company</field> <field name="model_id" search="[('model','=','mrp.workcenter')]" model="ir.model"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','child_of',[user.company_id.id]),('company_id','=',False)]</field> + <field name="domain_force">['|',('company_id', 'in', company_ids),('company_id','=',False)]</field> </record> <record model="ir.rule" id="mrp_bom_rule"> <field name="name">mrp_bom multi-company</field> <field name="model_id" search="[('model','=','mrp.bom')]" model="ir.model"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','child_of',[user.company_id.id]),('company_id','=',False)]</field> + <field name="domain_force">['|',('company_id', 'in', company_ids),('company_id','=',False)]</field> </record> <record model="ir.rule" id="mrp_routing_rule"> <field name="name">mrp_routing multi-company</field> <field name="model_id" search="[('model','=','mrp.routing')]" model="ir.model"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','child_of',[user.company_id.id]),('company_id','=',False)]</field> + <field name="domain_force">['|',('company_id', 'in', company_ids),('company_id','=',False)]</field> </record> <record model="ir.rule" id="mrp_routing_workcenter_rule"> <field name="name">mrp_routing_workcenter multi-company</field> <field name="model_id" search="[('model','=','mrp.routing.workcenter')]" model="ir.model"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','child_of',[user.company_id.id]),('company_id','=',False)]</field> + <field name="domain_force">['|',('company_id', 'in', company_ids),('company_id','=',False)]</field> </record> </data> diff --git a/addons/mrp_subcontracting/models/res_partner.py b/addons/mrp_subcontracting/models/res_partner.py index d4d565120e6..08cac056884 100644 --- a/addons/mrp_subcontracting/models/res_partner.py +++ b/addons/mrp_subcontracting/models/res_partner.py @@ -49,7 +49,7 @@ class ResPartner(models.Model): def write(self, vals): if vals.get('type') == 'subcontractor': - subcontracting_location = self.env.user.company_id.subcontracting_location_id + subcontracting_location = self.env.company_id.subcontracting_location_id if not vals.get('property_stock_supplier') and not vals.get('property_stock_customer'): vals['property_stock_supplier'] = subcontracting_location.id vals['property_stock_customer'] = subcontracting_location.id diff --git a/addons/pad/models/pad.py b/addons/pad/models/pad.py index 6e3476099fd..22cfe84af72 100644 --- a/addons/pad/models/pad.py +++ b/addons/pad/models/pad.py @@ -22,7 +22,7 @@ class PadCommon(models.AbstractModel): @api.model def pad_is_configured(self): - return bool(self.env.user.company_id.pad_server) + return bool(self.env.company_id.pad_server) @api.model def pad_generate_url(self): diff --git a/addons/partner_autocomplete/models/res_partner.py b/addons/partner_autocomplete/models/res_partner.py index 9d357fec6d8..a15d1626258 100644 --- a/addons/partner_autocomplete/models/res_partner.py +++ b/addons/partner_autocomplete/models/res_partner.py @@ -90,8 +90,8 @@ class ResPartner(models.Model): params.update({ 'db_uuid': self.env['ir.config_parameter'].sudo().get_param('database.uuid'), 'account_token': account.account_token, - 'country_code': self.env.user.company_id.country_id.code, - 'zip': self.env.user.company_id.zip, + 'country_code': self.env.company_id.country_id.code, + 'zip': self.env.company_id.zip, }) try: return jsonrpc(url=url, params=params, timeout=timeout), False diff --git a/addons/partner_autocomplete/static/src/js/partner_autocomplete_fieldchar.js b/addons/partner_autocomplete/static/src/js/partner_autocomplete_fieldchar.js index f1dd023b885..c1fab81a194 100644 --- a/addons/partner_autocomplete/static/src/js/partner_autocomplete_fieldchar.js +++ b/addons/partner_autocomplete/static/src/js/partner_autocomplete_fieldchar.js @@ -127,9 +127,6 @@ var FieldAutocomplete = FieldChar.extend(AutocompleteMixin, { }); } - self._setOne2ManyField('child_ids', data.company.child_ids); - delete data.company.child_ids; - self._setOne2ManyField('bank_ids', data.company.bank_ids); delete data.company.bank_ids; diff --git a/addons/payment/controllers/portal.py b/addons/payment/controllers/portal.py index 55a4d08e4b9..3d9ac23861b 100644 --- a/addons/payment/controllers/portal.py +++ b/addons/payment/controllers/portal.py @@ -106,7 +106,7 @@ class WebsitePayment(http.Controller): def payment_method(self, **kwargs): acquirers = list(request.env['payment.acquirer'].search([ ('website_published', '=', True), ('registration_view_template_id', '!=', False), - ('payment_flow', '=', 's2s'), ('company_id', '=', request.env.user.company_id.id) + ('payment_flow', '=', 's2s'), ('company_id', '=', request.env.company_id.id) ])) partner = request.env.user.partner_id payment_tokens = partner.payment_token_ids diff --git a/addons/payment/models/payment_acquirer.py b/addons/payment/models/payment_acquirer.py index 9de056039df..087899880f2 100644 --- a/addons/payment/models/payment_acquirer.py +++ b/addons/payment/models/payment_acquirer.py @@ -72,7 +72,7 @@ class PaymentAcquirer(models.Model): default='manual', required=True) company_id = fields.Many2one( 'res.company', 'Company', - default=lambda self: self.env.user.company_id.id, required=True) + default=lambda self: self.env.company_id.id, required=True) view_template_id = fields.Many2one( 'ir.ui.view', 'Form Button Template', default=_get_default_view_template_id) @@ -267,7 +267,7 @@ class PaymentAcquirer(models.Model): acquirer_names = [a.name.split('_')[1] for a in acquirer_modules] # Search for acquirers having no journal - company = company or self.env.user.company_id + company = company or self.env.company_id acquirers = self.env['payment.acquirer'].search( [('provider', 'in', acquirer_names), ('journal_id', '=', False), ('company_id', '=', company.id)]) @@ -328,7 +328,7 @@ class PaymentAcquirer(models.Model): * pms: record set of stored credit card data (aka payment.token) connected to a given partner to allow customers to reuse them """ if not company: - company = self.env.user.company_id + company = self.env.company_id if not partner: partner = self.env.user.partner_id active_acquirers = self.sudo().search([('website_published', '=', True), ('company_id', '=', company.id)]) @@ -384,7 +384,7 @@ class PaymentAcquirer(models.Model): if currency_id: currency = self.env['res.currency'].browse(currency_id) else: - currency = self.env.user.company_id.currency_id + currency = self.env.company_id.currency_id values['currency'] = currency # Fill partner_* using values['partner_id'] or partner_id argument @@ -569,7 +569,7 @@ class PaymentTransaction(models.Model): @api.model def _get_default_partner_country_id(self): - return self.env['res.company']._company_default_get('payment.transaction').country_id.id + return self.env.company_id.country_id.id date = fields.Datetime('Validation Date', readonly=True) acquirer_id = fields.Many2one('payment.acquirer', string='Acquirer', readonly=True, required=True) diff --git a/addons/payment/models/res_company.py b/addons/payment/models/res_company.py index de21668f496..a98ea1aac14 100644 --- a/addons/payment/models/res_company.py +++ b/addons/payment/models/res_company.py @@ -20,7 +20,7 @@ class ResCompany(models.Model): def action_open_payment_onboarding_payment_acquirer(self): """ Called by onboarding panel above the customer invoice list.""" # Fail if there are no existing accounts - self.env.user.company_id.get_chart_of_accounts_or_fail() + self.env.company_id.get_chart_of_accounts_or_fail() action = self.env.ref('payment.action_open_payment_onboarding_payment_acquirer_wizard').read()[0] return action diff --git a/addons/payment/views/payment_portal_templates.xml b/addons/payment/views/payment_portal_templates.xml index c6a81cbe55b..2b0c147260e 100644 --- a/addons/payment/views/payment_portal_templates.xml +++ b/addons/payment/views/payment_portal_templates.xml @@ -33,7 +33,7 @@ <!-- TDE FIXME: was customize_show=True --> <template id="pay_meth_link" inherit_id="portal.portal_layout"> <xpath expr="//div[hasclass('o_portal_my_details')]" position="inside"> - <t t-if="request.env['payment.acquirer'].search([('website_published', '=', True), ('registration_view_template_id', '!=', False), ('payment_flow', '=', 's2s'), ('company_id', '=', request.env.user.company_id.id)])"> + <t t-if="request.env['payment.acquirer'].search([('website_published', '=', True), ('registration_view_template_id', '!=', False), ('payment_flow', '=', 's2s'), ('company_id', '=', request.env.company_id.id)])"> <div class='manage_payment_method mt16'><a href="/my/payment_method">Manage payment methods</a></div> </t> </xpath> diff --git a/addons/payment/wizards/payment_acquirer_onboarding_wizard.py b/addons/payment/wizards/payment_acquirer_onboarding_wizard.py index 1b23489460c..38545771ae7 100644 --- a/addons/payment/wizards/payment_acquirer_onboarding_wizard.py +++ b/addons/payment/wizards/payment_acquirer_onboarding_wizard.py @@ -31,7 +31,7 @@ class PaymentWizard(models.TransientModel): @api.onchange('journal_name', 'acc_number') def _set_manual_post_msg_value(self): self.manual_post_msg = _('<h3>Please make a payment to: </h3><ul><li>Bank: %s</li><li>Account Number: %s</li><li>Account Holder: %s</li></ul>') %\ - (self.journal_name or _("Bank") , self.acc_number or _("Account"), self.env.user.company_id.name) + (self.journal_name or _("Bank") , self.acc_number or _("Account"), self.env.company_id.name) _payment_acquirer_onboarding_cache = {} _data_fetched = False @@ -41,7 +41,7 @@ class PaymentWizard(models.TransientModel): env = self.env module_id = env.ref('base.module_payment_transfer').id return env['payment.acquirer'].search([('module_id', '=', module_id), - ('company_id', '=', env.user.company_id.id)], limit=1) + ('company_id', '=', env.company_id.id)], limit=1) def _get_default_payment_acquirer_onboarding_value(self, key): if not self.env.user._is_admin(): @@ -52,7 +52,7 @@ class PaymentWizard(models.TransientModel): self._data_fetched = True - self._payment_acquirer_onboarding_cache['payment_method'] = self.env.user.company_id.payment_onboarding_payment_method + self._payment_acquirer_onboarding_cache['payment_method'] = self.env.company_id.payment_onboarding_payment_method installed_modules = self.env['ir.module.module'].sudo().search([ ('name', 'in', ('payment_paypal', 'payment_stripe')), @@ -103,7 +103,7 @@ class PaymentWizard(models.TransientModel): self._on_save_payment_acquirer() - self.env.user.company_id.payment_onboarding_payment_method = self.payment_method + self.env.company_id.payment_onboarding_payment_method = self.payment_method # create a new env including the freshly installed module(s) new_env = api.Environment(self.env.cr, self.env.uid, self.env.context) @@ -149,7 +149,7 @@ class PaymentWizard(models.TransientModel): return {'type': 'ir.actions.act_window_close'} def _set_payment_acquirer_onboarding_step_done(self): - self.env.user.company_id.set_onboarding_step_done('payment_acquirer_onboarding_state') + self.env.company_id.set_onboarding_step_done('payment_acquirer_onboarding_state') def action_onboarding_other_payment_acquirer(self): self._set_payment_acquirer_onboarding_step_done() diff --git a/addons/payment_transfer/models/payment.py b/addons/payment_transfer/models/payment.py index e7bc14e3f79..98dd28aaa67 100644 --- a/addons/payment_transfer/models/payment.py +++ b/addons/payment_transfer/models/payment.py @@ -18,7 +18,7 @@ class TransferPaymentAcquirer(models.Model): @api.model def _create_missing_journal_for_acquirers(self, company=None): # By default, the wire transfer method uses the default Bank journal. - company = company or self.env.user.company_id + company = company or self.env.company_id acquirers = self.env['payment.acquirer'].search( [('provider', '=', 'transfer'), ('journal_id', '=', False), ('company_id', '=', company.id)]) @@ -32,7 +32,7 @@ class TransferPaymentAcquirer(models.Model): return '/payment/transfer/feedback' def _format_transfer_data(self): - company_id = self.env.user.company_id.id + company_id = self.env.company_id.id # filter only bank accounts marked as visible journals = self.env['account.journal'].search([('type', '=', 'bank'), ('company_id', '=', company_id)]) accounts = journals.mapped('bank_account_id').name_get() diff --git a/addons/phone_validation/models/phone_validation_mixin.py b/addons/phone_validation/models/phone_validation_mixin.py index 0c86bad81bb..3ac75179a1e 100644 --- a/addons/phone_validation/models/phone_validation_mixin.py +++ b/addons/phone_validation/models/phone_validation_mixin.py @@ -12,12 +12,12 @@ class PhoneValidationMixin(models.AbstractModel): def _phone_get_country(self): if 'country_id' in self and self.country_id: return self.country_id - return self.env.user.company_id.country_id + return self.env.company_id.country_id def _phone_get_always_international(self): if 'company_id' in self and self.company_id: return self.company_id.phone_international_format == 'prefix' - return self.env.user.company_id.phone_international_format == 'prefix' + return self.env.company_id.phone_international_format == 'prefix' def phone_format(self, number, country=None, company=None): country = country or self._phone_get_country() diff --git a/addons/point_of_sale/models/pos_config.py b/addons/point_of_sale/models/pos_config.py index ef8a8479260..1fbb51dacd8 100644 --- a/addons/point_of_sale/models/pos_config.py +++ b/addons/point_of_sale/models/pos_config.py @@ -41,18 +41,18 @@ class PosConfig(models.Model): def _default_sale_journal(self): journal = self.env.ref('point_of_sale.pos_sale_journal', raise_if_not_found=False) - if journal and journal.sudo().company_id == self.env.user.company_id: + if journal and journal.sudo().company_id == self.env.company_id: return journal return self._default_invoice_journal() def _default_invoice_journal(self): - return self.env['account.journal'].search([('type', '=', 'sale'), ('company_id', '=', self.env.user.company_id.id)], limit=1) + return self.env['account.journal'].search([('type', '=', 'sale'), ('company_id', '=', self.env.company_id.id)], limit=1) def _default_pricelist(self): - return self.env['product.pricelist'].search([('currency_id', '=', self.env.user.company_id.currency_id.id)], limit=1) + return self.env['product.pricelist'].search([('currency_id', '=', self.env.company_id.currency_id.id)], limit=1) def _get_default_location(self): - return self.env['stock.warehouse'].search([('company_id', '=', self.env.user.company_id.id)], limit=1).lot_stock_id + return self.env['stock.warehouse'].search([('company_id', '=', self.env.company_id.id)], limit=1).lot_stock_id def _get_group_pos_manager(self): return self.env.ref('point_of_sale.group_pos_manager') @@ -137,10 +137,10 @@ class PosConfig(models.Model): help="The pricelist used if no customer is selected or if the customer has no Sale Pricelist configured.") available_pricelist_ids = fields.Many2many('product.pricelist', string='Available Pricelists', default=_default_pricelist, help="Make several pricelists available in the Point of Sale. You can also apply a pricelist to specific customers from their contact form (in Sales tab). To be valid, this pricelist must be listed here as an available pricelist. Otherwise the default pricelist will apply.") - company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company_id) barcode_nomenclature_id = fields.Many2one('barcode.nomenclature', string='Barcode Nomenclature', help='Defines what kind of barcodes are available and how they are assigned to products, customers and cashiers.', - default=lambda self: self.env.user.company_id.nomenclature_id, required=True) + default=lambda self: self.env.company_id.nomenclature_id, required=True) group_pos_manager_id = fields.Many2one('res.groups', string='Point of Sale Manager Group', default=_get_group_pos_manager, help='This field is there to pass the id of the pos manager group to the point of sale client.') group_pos_user_id = fields.Many2one('res.groups', string='Point of Sale User Group', default=_get_group_pos_user, @@ -178,7 +178,7 @@ class PosConfig(models.Model): if pos_config.journal_id: pos_config.currency_id = pos_config.journal_id.currency_id.id or pos_config.journal_id.company_id.currency_id.id else: - pos_config.currency_id = self.env.user.company_id.currency_id.id + pos_config.currency_id = self.env.company_id.currency_id.id @api.depends('session_ids') def _compute_current_session(self): diff --git a/addons/point_of_sale/models/pos_order.py b/addons/point_of_sale/models/pos_order.py index af69cf30990..22bbe7ed734 100644 --- a/addons/point_of_sale/models/pos_order.py +++ b/addons/point_of_sale/models/pos_order.py @@ -536,7 +536,7 @@ class PosOrder(models.Model): return self._default_session().config_id.pricelist_id name = fields.Char(string='Order Ref', required=True, readonly=True, copy=False, default='/') - company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, default=lambda self: self.env.company_id) date_order = fields.Datetime(string='Order Date', readonly=True, index=True, default=fields.Datetime.now) user_id = fields.Many2one( comodel_name='res.users', string='User', @@ -1047,7 +1047,7 @@ class PosOrderLine(models.Model): line[2]['tax_ids'] = [(6, 0, [x.id for x in product.taxes_id])] return line - company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company_id) name = fields.Char(string='Line No', required=True, copy=False) notice = fields.Char(string='Discount Notice') product_id = fields.Many2one('product.product', string='Product', domain=[('sale_ok', '=', True)], required=True, change_default=True) @@ -1211,7 +1211,7 @@ class ReportSaleDetails(models.AbstractModel): ('state', 'in', ['paid','invoiced','done']), ('config_id', 'in', configs.ids)]) - user_currency = self.env.user.company_id.currency_id + user_currency = self.env.company_id.currency_id total = 0.0 products_sold = {} @@ -1259,7 +1259,7 @@ class ReportSaleDetails(models.AbstractModel): 'currency_precision': user_currency.decimal_places, 'total_paid': user_currency.round(total), 'payments': payments, - 'company_name': self.env.user.company_id.name, + 'company_name': self.env.company_id.name, 'taxes': list(taxes.values()), 'products': sorted([{ 'product_id': product.id, diff --git a/addons/point_of_sale/security/point_of_sale_security.xml b/addons/point_of_sale/security/point_of_sale_security.xml index db70f713fbb..34366e90353 100644 --- a/addons/point_of_sale/security/point_of_sale_security.xml +++ b/addons/point_of_sale/security/point_of_sale_security.xml @@ -51,25 +51,25 @@ <field name="name">Point Of Sale Order</field> <field name="model_id" ref="model_pos_order" /> <field name="global" eval="True" /> - <field name="domain_force">[('company_id', '=', user.company_id.id)]</field> + <field name="domain_force">[('company_id', 'in', company_ids)]</field> </record> <record id="rule_pos_session_multi_company" model="ir.rule"> <field name="name">Point Of Sale Session</field> <field name="model_id" ref="model_pos_session" /> <field name="global" eval="True" /> - <field name="domain_force">[('config_id.company_id', '=', user.company_id.id)]</field> + <field name="domain_force">[('config_id.company_id', 'in', company_ids)]</field> </record> <record id="rule_pos_config_multi_company" model="ir.rule"> <field name="name">Point Of Sale Config</field> <field name="model_id" ref="model_pos_config" /> <field name="global" eval="True" /> - <field name="domain_force">[('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">[('company_id', 'in', company_ids)]</field> </record> <record id="rule_pos_order_report_multi_company" model="ir.rule"> <field name="name">Point Of Sale Order Analysis multi-company</field> <field name="model_id" ref="model_report_pos_order"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <data noupdate="1"> diff --git a/addons/point_of_sale/tests/test_point_of_sale_flow.py b/addons/point_of_sale/tests/test_point_of_sale_flow.py index d76c660d0fc..5b960c11959 100644 --- a/addons/point_of_sale/tests/test_point_of_sale_flow.py +++ b/addons/point_of_sale/tests/test_point_of_sale_flow.py @@ -559,7 +559,7 @@ class TestPointOfSaleFlow(TestPointOfSaleCommon): # Make sure the company is in USD self.env.cr.execute( "UPDATE res_company SET currency_id = %s WHERE id = %s", - [self.env.ref('base.USD').id, self.env.user.company_id.id]) + [self.env.ref('base.USD').id, self.env.company_id.id]) # Demo data are crappy, clean-up the rates self.env['res.currency.rate'].search([]).unlink() diff --git a/addons/point_of_sale/wizard/pos_details.py b/addons/point_of_sale/wizard/pos_details.py index 06825a25f36..2ce2224a7f5 100644 --- a/addons/point_of_sale/wizard/pos_details.py +++ b/addons/point_of_sale/wizard/pos_details.py @@ -44,9 +44,9 @@ class PosDetails(models.TransientModel): @api.multi def generate_report(self): - if (not self.env.user.company_id.logo): + if (not self.env.company_id.logo): raise UserError(_("You have to set a logo or a layout for your company.")) - elif (not self.env.user.company_id.external_report_layout_id): + elif (not self.env.company_id.external_report_layout_id): raise UserError(_("You have to set your reports's header and footer layout.")) data = {'date_start': self.start_date, 'date_stop': self.end_date, 'config_ids': self.pos_config_ids.ids} return self.env.ref('point_of_sale.sale_details_report').report_action([], data=data) diff --git a/addons/portal/wizard/portal_wizard.py b/addons/portal/wizard/portal_wizard.py index 8ac87a59ee6..4c6942bbef7 100644 --- a/addons/portal/wizard/portal_wizard.py +++ b/addons/portal/wizard/portal_wizard.py @@ -134,7 +134,7 @@ class PortalWizardUser(models.TransientModel): if wizard_user.partner_id.company_id: company_id = wizard_user.partner_id.company_id.id else: - company_id = self.env['res.company']._company_default_get('res.users').id + company_id = self.env.company_id.id user_portal = wizard_user.sudo().with_context(company_id=company_id)._create_user() else: user_portal = user diff --git a/addons/product/models/decimal_precision.py b/addons/product/models/decimal_precision.py index 3347bc167b4..2fe33eed246 100644 --- a/addons/product/models/decimal_precision.py +++ b/addons/product/models/decimal_precision.py @@ -11,7 +11,7 @@ class DecimalPrecision(models.Model): @api.constrains('digits') def _check_main_currency_rounding(self): if any(precision.name == 'Account' and - tools.float_compare(self.env.user.company_id.currency_id.rounding, 10 ** - precision.digits, precision_digits=6) == -1 + tools.float_compare(self.env.company_id.currency_id.rounding, 10 ** - precision.digits, precision_digits=6) == -1 for precision in self): raise ValidationError(_("You cannot define the decimal precision of 'Account' as greater than the rounding factor of the company's main currency")) return True diff --git a/addons/product/models/product.py b/addons/product/models/product.py index 4d566f2b100..0ead3c2e231 100644 --- a/addons/product/models/product.py +++ b/addons/product/models/product.py @@ -71,7 +71,7 @@ class ProductPriceHistory(models.Model): _description = 'Product Price List History' def _get_default_company_id(self): - return self._context.get('force_company', self.env.user.company_id.id) + return self._context.get('force_company', self.env.company_id.id) company_id = fields.Many2one('res.company', string='Company', default=_get_default_company_id, required=True) @@ -651,7 +651,7 @@ class ProductProduct(models.Model): # standard_price field can only be seen by users in base.group_user # Thus, in order to compute the sale price from the cost for users not in this group # We fetch the standard price as the superuser - products = self.with_context(force_company=company and company.id or self._context.get('force_company', self.env.user.company_id.id)).sudo() + products = self.with_context(force_company=company and company.id or self._context.get('force_company', self.env.company_id.id)).sudo() prices = dict.fromkeys(self.ids, 0.0) for product in products: @@ -689,7 +689,7 @@ class ProductProduct(models.Model): PriceHistory.create({ 'product_id': product.id, 'cost': value, - 'company_id': self._context.get('force_company', self.env.user.company_id.id), + 'company_id': self._context.get('force_company', self.env.company_id.id), }) @api.multi @@ -814,10 +814,10 @@ class SupplierInfo(models.Model): required=True, help="The price to purchase a product") company_id = fields.Many2one( 'res.company', 'Company', - default=lambda self: self.env.user.company_id.id, index=1) + default=lambda self: self.env.company_id.id, index=1) currency_id = fields.Many2one( 'res.currency', 'Currency', - default=lambda self: self.env.user.company_id.currency_id.id, + default=lambda self: self.env.company_id.currency_id.id, required=True) date_start = fields.Date('Start Date', help="Start date for this vendor price") date_end = fields.Date('End Date', help="End date for this vendor price") diff --git a/addons/product/models/product_pricelist.py b/addons/product/models/product_pricelist.py index 917bcb28882..5f5e56e3a45 100644 --- a/addons/product/models/product_pricelist.py +++ b/addons/product/models/product_pricelist.py @@ -15,7 +15,7 @@ class Pricelist(models.Model): _order = "sequence asc, id desc" def _get_default_currency_id(self): - return self.env.user.company_id.currency_id.id + return self.env.company_id.currency_id.id def _get_default_item_ids(self): ProductPricelistItem = self.env['product.pricelist.item'] @@ -221,7 +221,7 @@ class Pricelist(models.Model): if rule.base == 'pricelist' and rule.base_pricelist_id: price_tmp = rule.base_pricelist_id._compute_price_rule([(product, qty, partner)])[product.id][0] # TDE: 0 = price, 1 = rule - price = rule.base_pricelist_id.currency_id._convert(price_tmp, self.currency_id, self.env.user.company_id, date, round=False) + price = rule.base_pricelist_id.currency_id._convert(price_tmp, self.currency_id, self.env.company_id, date, round=False) else: # if base option is public price take sale price else cost price of product # price_compute returns the price in the context UoM, i.e. qty_uom_id @@ -260,7 +260,7 @@ class Pricelist(models.Model): cur = product.cost_currency_id else: cur = product.currency_id - price = cur._convert(price, self.currency_id, self.env.user.company_id, date, round=False) + price = cur._convert(price, self.currency_id, self.env.company_id, date, round=False) results[product.id] = (price, suitable_rule and suitable_rule.id or False) @@ -353,7 +353,7 @@ class Pricelist(models.Model): # as we will do a search() later (real case for website public user). Partner = self.env['res.partner'].with_context(active_test=False) - Property = self.env['ir.property'].with_context(force_company=company_id or self.env.user.company_id.id) + Property = self.env['ir.property'].with_context(force_company=company_id or self.env.company_id.id) Pricelist = self.env['product.pricelist'] pl_domain = self._get_partner_pricelist_multi_search_domain_hook() diff --git a/addons/product/models/product_template.py b/addons/product/models/product_template.py index 56f9e10a840..6db0fbf3f7d 100644 --- a/addons/product/models/product_template.py +++ b/addons/product/models/product_template.py @@ -109,7 +109,7 @@ class ProductTemplate(models.Model): help="Default unit of measure used for purchase orders. It must be in the same category as the default unit of measure.") company_id = fields.Many2one( 'res.company', 'Company', - default=lambda self: self.env['res.company']._company_default_get('product.template'), index=1) + default=lambda self: self.env.company_id, index=1) packaging_ids = fields.One2many( 'product.packaging', string="Product Packages", compute="_compute_packaging_ids", inverse="_set_packaging_ids", help="Gives the different ways to package the same product.") @@ -168,7 +168,7 @@ class ProductTemplate(models.Model): def _compute_cost_currency_id(self): for template in self: - template.cost_currency_id = self.env.user.company_id.currency_id.id + template.cost_currency_id = self.env.company_id.currency_id.id @api.multi def _compute_template_price(self): @@ -450,12 +450,12 @@ class ProductTemplate(models.Model): # standard_price field can only be seen by users in base.group_user # Thus, in order to compute the sale price from the cost for users not in this group # We fetch the standard price as the superuser - templates = self.with_context(force_company=company and company.id or self._context.get('force_company', self.env.user.company_id.id)).sudo() + templates = self.with_context(force_company=company and company.id or self._context.get('force_company', self.env.company_id.id)).sudo() if not company: if self._context.get('force_company'): company = self.env['res.company'].browse(self._context['force_company']) else: - company = self.env.user.company_id + company = self.env.company_id date = self.env.context.get('date') or fields.Date.today() prices = dict.fromkeys(self.ids, 0.0) @@ -1090,7 +1090,7 @@ class ProductTemplate(models.Model): :rtype: recordset of one `res.company` """ self.ensure_one() - return self.env.user.company_id + return self.env.company_id @api.model def get_empty_list_help(self, help): diff --git a/addons/product/models/res_partner.py b/addons/product/models/res_partner.py index 5eb0e652187..c36a791f043 100644 --- a/addons/product/models/res_partner.py +++ b/addons/product/models/res_partner.py @@ -34,7 +34,7 @@ class Partner(models.Model): # update at each change country, and so erase old pricelist if self.property_product_pricelist or (actual and default_for_country and default_for_country.id != actual.id): # keep the company of the current user before sudo - self.env['ir.property'].with_context(force_company=self.env.user.company_id.id).sudo().set_multi( + self.env['ir.property'].with_context(force_company=self.env.company_id.id).sudo().set_multi( 'property_product_pricelist', self._name, {self.id: self.property_product_pricelist or default_for_country.id}, diff --git a/addons/product/security/product_security.xml b/addons/product/security/product_security.xml index 422d7ac75ec..4ef8ea822d0 100644 --- a/addons/product/security/product_security.xml +++ b/addons/product/security/product_security.xml @@ -34,7 +34,7 @@ <field name="name" >Product multi-company</field> <field name="model_id" ref="model_product_template"/> <field name="global" eval="True"/> - <field name="domain_force"> ['|',('company_id','=',user.company_id.id),('company_id','=',False)]</field> + <field name="domain_force"> ['|', ('company_id', 'in', company_ids), ('company_id', '=', False)]</field> <field name="active" eval="False"/> </record> @@ -42,21 +42,21 @@ <field name="name">product pricelist company rule</field> <field name="model_id" ref="model_product_pricelist"/> <field name="global" eval="True"/> - <field name="domain_force"> ['|',('company_id','=',user.company_id.id),('company_id','=',False)]</field> + <field name="domain_force"> ['|', ('company_id', 'in', company_ids), ('company_id', '=', False)]</field> </record> <record model="ir.rule" id="product_pricelist_item_comp_rule"> <field name="name">product pricelist item company rule</field> <field name="model_id" ref="model_product_pricelist_item"/> <field name="global" eval="True"/> - <field name="domain_force"> ['|',('company_id','=',user.company_id.id),('company_id','=',False)]</field> + <field name="domain_force"> ['|', ('company_id', 'in', company_ids), ('company_id', '=', False)]</field> </record> <record model="ir.rule" id="product_supplierinfo_comp_rule"> <field name="name">product supplierinfo company rule</field> <field name="model_id" ref="model_product_supplierinfo"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','=',user.company_id.id)]</field> + <field name="domain_force">['|', ('company_id', '=', False), ('company_id', 'in', company_ids)]</field> </record> </data> diff --git a/addons/product/tests/test_seller.py b/addons/product/tests/test_seller.py index 830b277da1d..ee87f7833f6 100644 --- a/addons/product/tests/test_seller.py +++ b/addons/product/tests/test_seller.py @@ -33,7 +33,7 @@ class TestSeller(TransactionCase): self.assertEqual('C2CCODE', context_code, "Partner's code not used in product name with context set") def test_20_sellers_company(self): - company_a = self.env.user.company_id + company_a = self.env.company_id company_b = self.env['res.company'].create({ 'name': 'Saucisson Inc.', }) diff --git a/addons/product/wizard/product_price_list.py b/addons/product/wizard/product_price_list.py index bff0177f415..743b32f3855 100644 --- a/addons/product/wizard/product_price_list.py +++ b/addons/product/wizard/product_price_list.py @@ -22,9 +22,9 @@ class product_price_list(models.TransientModel): To get the date and print the report @return : return report """ - if (not self.env.user.company_id.logo): + if (not self.env.company_id.logo): raise UserError(_("You have to set a logo or a layout for your company.")) - elif (not self.env.user.company_id.external_report_layout_id): + elif (not self.env.company_id.external_report_layout_id): raise UserError(_("You have to set your reports's header and footer layout.")) datas = {'ids': self.env.context.get('active_ids', [])} diff --git a/addons/product_margin/models/product_product.py b/addons/product_margin/models/product_product.py index 9fc94ea6310..5f8ca4002d1 100644 --- a/addons/product_margin/models/product_product.py +++ b/addons/product_margin/models/product_product.py @@ -100,7 +100,7 @@ class ProductProduct(models.Model): if "force_company" in self.env.context: company_id = self.env.context['force_company'] else: - company_id = self.env.user.company_id.id + company_id = self.env.company_id.id #Cost price is calculated afterwards as it is a property sqlstr = """ diff --git a/addons/project/models/project.py b/addons/project/models/project.py index 98a437c1c6d..7fcdc3368ef 100644 --- a/addons/project/models/project.py +++ b/addons/project/models/project.py @@ -178,7 +178,7 @@ class Project(models.Model): help="If the active field is set to False, it will allow you to hide the project without removing it.") sequence = fields.Integer(default=10, help="Gives the sequence order when displaying a list of Projects.") partner_id = fields.Many2one('res.partner', string='Customer', auto_join=True, tracking=True) - company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company_id) currency_id = fields.Many2one('res.currency', related="company_id.currency_id", string="Currency", readonly=True) favorite_user_ids = fields.Many2many( @@ -191,7 +191,7 @@ class Project(models.Model): tasks = fields.One2many('project.task', 'project_id', string="Task Activities") resource_calendar_id = fields.Many2one( 'resource.calendar', string='Working Time', - default=lambda self: self.env.user.company_id.resource_calendar_id.id, + default=lambda self: self.env.company_id.resource_calendar_id.id, help="Timetable working hours to adjust the gantt diagram report") type_ids = fields.Many2many('project.task.type', 'project_task_type_rel', 'project_id', 'type_id', string='Tasks Stages') task_count = fields.Integer(compute='_compute_task_count', string="Task Count") @@ -481,7 +481,7 @@ class Task(models.Model): manager_id = fields.Many2one('res.users', string='Project Manager', related='project_id.user_id', readonly=True, related_sudo=False) company_id = fields.Many2one('res.company', string='Company', - default=lambda self: self.env['res.company']._company_default_get()) + default=lambda self: self.env.company_id) color = fields.Integer(string='Color Index') user_email = fields.Char(related='user_id.email', string='User Email', readonly=True, related_sudo=False) attachment_ids = fields.One2many('ir.attachment', compute='_compute_attachment_ids', string="Main Attachments", diff --git a/addons/project/security/project_security.xml b/addons/project/security/project_security.xml index e86850ed37d..c50386bb6ec 100644 --- a/addons/project/security/project_security.xml +++ b/addons/project/security/project_security.xml @@ -40,7 +40,7 @@ <field name="global" eval="True"/> <field name="domain_force">['|', ('company_id', '=', False), - ('company_id', 'child_of', [user.company_id.id]), + ('company_id', 'in', company_ids), ]</field> </record> @@ -69,7 +69,7 @@ <field name="global" eval="True"/> <field name="domain_force">['|', ('company_id', '=', False), - ('company_id', 'child_of', [user.company_id.id]), + ('company_id', 'in', company_ids), ]</field> </record> @@ -100,7 +100,7 @@ <field name="name">Task Analysis multi-company</field> <field name="model_id" ref="model_report_project_task_user"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <!-- Portal --> diff --git a/addons/project_timesheet_holidays/__init__.py b/addons/project_timesheet_holidays/__init__.py index d553cb8e270..cfae265bb38 100644 --- a/addons/project_timesheet_holidays/__init__.py +++ b/addons/project_timesheet_holidays/__init__.py @@ -13,7 +13,7 @@ def post_init(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) for hr_leave_type in env['hr.leave.type'].search([('timesheet_generate', '=', True), ('timesheet_project_id', '=', False)]): - company = hr_leave_type.company_id or env.user.company_id + company = hr_leave_type.company_id or env.company_id hr_leave_type.write({ 'timesheet_project_id': company.leave_timesheet_project_id.id, 'timesheet_task_id': company.leave_timesheet_task_id.id, diff --git a/addons/project_timesheet_holidays/models/hr_holidays.py b/addons/project_timesheet_holidays/models/hr_holidays.py index 3671df364e0..eacbae5e2ba 100644 --- a/addons/project_timesheet_holidays/models/hr_holidays.py +++ b/addons/project_timesheet_holidays/models/hr_holidays.py @@ -9,11 +9,11 @@ class HolidaysType(models.Model): _inherit = "hr.leave.type" def _default_project_id(self): - company = self.company_id if self.company_id else self.env.user.company_id + company = self.company_id if self.company_id else self.env.company_id return company.leave_timesheet_project_id.id def _default_task_id(self): - company = self.company_id if self.company_id else self.env.user.company_id + company = self.company_id if self.company_id else self.env.company_id return company.leave_timesheet_task_id.id timesheet_generate = fields.Boolean('Generate Timesheet', default=True, help="If checked, when validating a time off, timesheet will be generated in the Vacation Project of the company.") @@ -29,7 +29,7 @@ class HolidaysType(models.Model): @api.onchange('timesheet_project_id') def _onchange_timesheet_project(self): - company = self.company_id if self.company_id else self.env.user.company_id + company = self.company_id if self.company_id else self.env.company_id default_task_id = company.leave_timesheet_task_id if default_task_id and default_task_id.project_id == self.timesheet_project_id: self.timesheet_task_id = default_task_id diff --git a/addons/project_timesheet_holidays/tests/test_timesheet_holidays.py b/addons/project_timesheet_holidays/tests/test_timesheet_holidays.py index 74b73173972..5effe0e5c37 100644 --- a/addons/project_timesheet_holidays/tests/test_timesheet_holidays.py +++ b/addons/project_timesheet_holidays/tests/test_timesheet_holidays.py @@ -19,7 +19,7 @@ class TestTimesheetHolidaysCreate(common.TransactionCase): 'allocation_type': 'no' }) - company = self.env.user.company_id + company = self.env.company_id self.assertEqual(status.timesheet_project_id, company.leave_timesheet_project_id, 'The default project linked to the status should be the same as the company') self.assertEqual(status.timesheet_task_id, company.leave_timesheet_task_id, 'The default task linked to the status should be the same as the company') @@ -37,8 +37,8 @@ class TestTimesheetHolidays(TestCommonTimesheet): self.leave_end_datetime = self.leave_start_datetime + relativedelta(days=3) # all company have those internal project/task (created by default) - self.internal_project = self.env.user.company_id.leave_timesheet_project_id - self.internal_task_leaves = self.env.user.company_id.leave_timesheet_task_id + self.internal_project = self.env.company_id.leave_timesheet_project_id + self.internal_task_leaves = self.env.company_id.leave_timesheet_task_id self.hr_leave_type_with_ts = self.env['hr.leave.type'].create({ 'name': 'Leave Type with timesheet generation', diff --git a/addons/purchase/models/account_invoice.py b/addons/purchase/models/account_invoice.py index 6c7b1b9293d..5b5cfbb6b76 100644 --- a/addons/purchase/models/account_invoice.py +++ b/addons/purchase/models/account_invoice.py @@ -78,7 +78,7 @@ class AccountInvoice(models.Model): 'analytic_tag_ids': line.analytic_tag_ids.ids, 'invoice_line_tax_ids': invoice_line_tax_ids.ids } - account = invoice_line.get_invoice_line_account('in_invoice', line.product_id, line.order_id.fiscal_position_id, self.env.user.company_id) + account = invoice_line.get_invoice_line_account('in_invoice', line.product_id, line.order_id.fiscal_position_id, self.env.company_id) if account: data['account_id'] = account.id return data diff --git a/addons/purchase/models/product.py b/addons/purchase/models/product.py index 2642a2e926f..dcdccd180b6 100644 --- a/addons/purchase/models/product.py +++ b/addons/purchase/models/product.py @@ -97,4 +97,4 @@ class ProductSupplierinfo(models.Model): @api.onchange('name') def _onchange_name(self): - self.currency_id = self.name.property_purchase_currency_id.id or self.env.user.company_id.currency_id.id + self.currency_id = self.name.property_purchase_currency_id.id or self.env.company_id.currency_id.id diff --git a/addons/purchase/models/purchase.py b/addons/purchase/models/purchase.py index 4702fc85c29..3df63a42b87 100644 --- a/addons/purchase/models/purchase.py +++ b/addons/purchase/models/purchase.py @@ -91,7 +91,7 @@ class PurchaseOrder(models.Model): help="Put an address if you want to deliver directly from the vendor to the customer. " "Otherwise, keep empty to deliver to your own company.") currency_id = fields.Many2one('res.currency', 'Currency', required=True, states=READONLY_STATES, - default=lambda self: self.env.user.company_id.currency_id.id) + default=lambda self: self.env.company_id.currency_id.id) state = fields.Selection([ ('draft', 'RFQ'), ('sent', 'RFQ Sent'), @@ -124,7 +124,7 @@ class PurchaseOrder(models.Model): product_id = fields.Many2one('product.product', related='order_line.product_id', string='Product', readonly=False) user_id = fields.Many2one('res.users', string='Purchase Representative', index=True, tracking=True, default=lambda self: self.env.user) - company_id = fields.Many2one('res.company', 'Company', required=True, index=True, states=READONLY_STATES, default=lambda self: self.env.user.company_id.id) + company_id = fields.Many2one('res.company', 'Company', required=True, index=True, states=READONLY_STATES, default=lambda self: self.env.company_id.id) def _compute_access_url(self): super(PurchaseOrder, self)._compute_access_url() @@ -192,11 +192,11 @@ class PurchaseOrder(models.Model): if not self.partner_id: self.fiscal_position_id = False self.payment_term_id = False - self.currency_id = self.env.user.company_id.currency_id.id + self.currency_id = self.env.company_id.currency_id.id else: self.fiscal_position_id = self.env['account.fiscal.position'].with_context(company_id=self.company_id.id).get_fiscal_position(self.partner_id.id) self.payment_term_id = self.partner_id.property_supplier_payment_term_id.id - self.currency_id = self.partner_id.property_purchase_currency_id.id or self.env.user.company_id.currency_id.id + self.currency_id = self.partner_id.property_purchase_currency_id.id or self.env.company_id.currency_id.id return {} @api.onchange('fiscal_position_id') @@ -325,7 +325,7 @@ class PurchaseOrder(models.Model): # Deal with double validation process if order.company_id.po_double_validation == 'one_step'\ or (order.company_id.po_double_validation == 'two_step'\ - and order.amount_total < self.env.user.company_id.currency_id._convert( + and order.amount_total < self.env.company_id.currency_id._convert( order.company_id.po_double_validation_amount, order.currency_id, order.company_id, order.date_order or fields.Date.today()))\ or order.user_has_groups('purchase.group_purchase_manager'): order.button_approve() @@ -359,7 +359,7 @@ class PurchaseOrder(models.Model): # Do not add a contact as a supplier partner = self.partner_id if not self.partner_id.parent_id else self.partner_id.parent_id if partner not in line.product_id.seller_ids.mapped('name') and len(line.product_id.seller_ids) <= 10: - currency = partner.property_purchase_currency_id or self.env.user.company_id.currency_id + currency = partner.property_purchase_currency_id or self.env.company_id.currency_id supplierinfo = { 'name': partner.id, 'sequence': max(line.product_id.seller_ids.mapped('sequence')) + 1 if line.product_id.seller_ids else 1, @@ -610,7 +610,7 @@ class PurchaseOrderLine(models.Model): fpos = self.order_id.fiscal_position_id if self.env.uid == SUPERUSER_ID: - company_id = self.env.user.company_id.id + company_id = self.env.company_id.id self.taxes_id = fpos.map_tax(self.product_id.supplier_taxes_id.filtered(lambda r: r.company_id.id == company_id)) else: self.taxes_id = fpos.map_tax(self.product_id.supplier_taxes_id) diff --git a/addons/purchase/models/res_config_settings.py b/addons/purchase/models/res_config_settings.py index 39e409d63b8..72fc6c91f0b 100644 --- a/addons/purchase/models/res_config_settings.py +++ b/addons/purchase/models/res_config_settings.py @@ -7,9 +7,9 @@ from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' - lock_confirmed_po = fields.Boolean("Lock Confirmed Orders", default=lambda self: self.env.user.company_id.po_lock == 'lock') + lock_confirmed_po = fields.Boolean("Lock Confirmed Orders", default=lambda self: self.env.company_id.po_lock == 'lock') po_lock = fields.Selection(related='company_id.po_lock', string="Purchase Order Modification *", readonly=False) - po_order_approval = fields.Boolean("Purchase Order Approval", default=lambda self: self.env.user.company_id.po_double_validation == 'two_step') + po_order_approval = fields.Boolean("Purchase Order Approval", default=lambda self: self.env.company_id.po_double_validation == 'two_step') po_double_validation = fields.Selection(related='company_id.po_double_validation', string="Levels of Approvals *", readonly=False) po_double_validation_amount = fields.Monetary(related='company_id.po_double_validation_amount', string="Minimum Amount", currency_field='company_currency_id', readonly=False) company_currency_id = fields.Many2one('res.currency', related='company_id.currency_id', string="Company Currency", readonly=True, diff --git a/addons/purchase/security/purchase_security.xml b/addons/purchase/security/purchase_security.xml index 0d64458d47c..ebc26ae2041 100644 --- a/addons/purchase/security/purchase_security.xml +++ b/addons/purchase/security/purchase_security.xml @@ -40,14 +40,14 @@ <field name="name">Purchase Order multi-company</field> <field name="model_id" ref="model_purchase_order"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="purchase_order_line_comp_rule"> <field name="name">Purchase Order Line multi-company</field> <field name="model_id" ref="model_purchase_order_line"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="portal_purchase_order_user_rule" model="ir.rule"> @@ -71,14 +71,14 @@ <field name="name">Purchases & Bills Union multi-company</field> <field name="model_id" ref="model_purchase_bill_union"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record id="purchase_order_report_comp_rule" model="ir.rule"> <field name="name">Purchase Order Report multi-company</field> <field name="model_id" ref="model_purchase_report"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> </data> diff --git a/addons/purchase_requisition/models/purchase_requisition.py b/addons/purchase_requisition/models/purchase_requisition.py index 2cf546eab41..3e883757dea 100644 --- a/addons/purchase_requisition/models/purchase_requisition.py +++ b/addons/purchase_requisition/models/purchase_requisition.py @@ -56,7 +56,7 @@ class PurchaseRequisition(models.Model): schedule_date = fields.Date(string='Delivery Date', index=True, help="The expected and scheduled delivery date where all the products are received", tracking=True) user_id = fields.Many2one('res.users', string='Purchase Representative', default= lambda self: self.env.user) description = fields.Text() - company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env['res.company']._company_default_get('purchase.requisition')) + company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company_id) purchase_ids = fields.One2many('purchase.order', 'requisition_id', string='Purchase Orders', states={'done': [('readonly', True)]}) line_ids = fields.One2many('purchase.requisition.line', 'requisition_id', string='Products to Purchase', states={'done': [('readonly', True)]}, copy=True) state = fields.Selection(PURCHASE_REQUISITION_STATES, @@ -65,7 +65,7 @@ class PurchaseRequisition(models.Model): state_blanket_order = fields.Selection(PURCHASE_REQUISITION_STATES, compute='_set_state') is_quantity_copy = fields.Selection(related='type_id.quantity_copy', readonly=True) currency_id = fields.Many2one('res.currency', 'Currency', required=True, - default=lambda self: self.env.user.company_id.currency_id.id) + default=lambda self: self.env.company_id.currency_id.id) @api.depends('state') def _set_state(self): @@ -179,7 +179,7 @@ class PurchaseRequisitionLine(models.Model): price_unit = fields.Float(string='Unit Price', digits=dp.get_precision('Product Price')) qty_ordered = fields.Float(compute='_compute_ordered_qty', string='Ordered Quantities') requisition_id = fields.Many2one('purchase.requisition', required=True, string='Purchase Agreement', ondelete='cascade') - company_id = fields.Many2one('res.company', related='requisition_id.company_id', string='Company', store=True, readonly=True, default= lambda self: self.env['res.company']._company_default_get('purchase.requisition.line')) + company_id = fields.Many2one('res.company', related='requisition_id.company_id', string='Company', store=True, readonly=True, default= lambda self: self.env.company_id) account_analytic_id = fields.Many2one('account.analytic.account', string='Analytic Account') analytic_tag_ids = fields.Many2many('account.analytic.tag', string='Analytic Tags') schedule_date = fields.Date(string='Scheduled Date') diff --git a/addons/purchase_requisition/security/purchase_requisition_security.xml b/addons/purchase_requisition/security/purchase_requisition_security.xml index cefb083422e..161937c6e92 100644 --- a/addons/purchase_requisition/security/purchase_requisition_security.xml +++ b/addons/purchase_requisition/security/purchase_requisition_security.xml @@ -6,14 +6,14 @@ <field name="name">Purchase Requisition multi-company</field> <field name="model_id" ref="model_purchase_requisition"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="purchase_requisition_line_comp_rule"> <field name="name">Purchase requisition Line multi-company</field> <field name="model_id" ref="model_purchase_requisition_line"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> </data> diff --git a/addons/purchase_requisition_stock/models/purchase_requisition.py b/addons/purchase_requisition_stock/models/purchase_requisition.py index ecc9d681fc5..35950316af3 100644 --- a/addons/purchase_requisition_stock/models/purchase_requisition.py +++ b/addons/purchase_requisition_stock/models/purchase_requisition.py @@ -9,7 +9,7 @@ class PurchaseRequisition(models.Model): def _get_picking_in(self): pick_in = self.env.ref('stock.picking_type_in', raise_if_not_found=False) - company = self.env['res.company']._company_default_get('purchase.requisition') + company = self.env.company_id if not pick_in or pick_in.sudo().warehouse_id.company_id.id != company.id: pick_in = self.env['stock.picking.type'].search( [('warehouse_id.company_id', '=', company.id), ('code', '=', 'incoming')], diff --git a/addons/purchase_requisition_stock/tests/test_purchase_requisition_stock.py b/addons/purchase_requisition_stock/tests/test_purchase_requisition_stock.py index 4d0a7abb95e..b592d64f571 100644 --- a/addons/purchase_requisition_stock/tests/test_purchase_requisition_stock.py +++ b/addons/purchase_requisition_stock/tests/test_purchase_requisition_stock.py @@ -19,7 +19,7 @@ class TestPurchaseRequisitionStock(TestPurchaseRequisitionCommon): warehouse.lot_stock_id, '/', '/', - self.env.user.company_id, + self.env.company_id, { 'warehouse_id': warehouse, 'date_planned': date_planned, diff --git a/addons/purchase_stock/models/account_invoice.py b/addons/purchase_stock/models/account_invoice.py index efb494777cd..49c736204af 100644 --- a/addons/purchase_stock/models/account_invoice.py +++ b/addons/purchase_stock/models/account_invoice.py @@ -12,7 +12,7 @@ class AccountInvoice(models.Model): def invoice_line_move_line_get(self): res = super(AccountInvoice, self).invoice_line_move_line_get() - if self.env.user.company_id.anglo_saxon_accounting: + if self.env.company_id.anglo_saxon_accounting: if self.type in ['in_invoice', 'in_refund']: for i_line in self.invoice_line_ids: res.extend(self._anglo_saxon_purchase_move_lines(i_line, res)) diff --git a/addons/purchase_stock/models/purchase.py b/addons/purchase_stock/models/purchase.py index 720039e214c..40b14c52c7a 100644 --- a/addons/purchase_stock/models/purchase.py +++ b/addons/purchase_stock/models/purchase.py @@ -15,7 +15,7 @@ class PurchaseOrder(models.Model): @api.model def _default_picking_type(self): type_obj = self.env['stock.picking.type'] - company_id = self.env.context.get('company_id') or self.env.user.company_id.id + company_id = self.env.context.get('company_id') or self.env.company_id.id types = type_obj.search([('code', '=', 'incoming'), ('warehouse_id.company_id', '=', company_id)]) if not types: types = type_obj.search([('code', '=', 'incoming'), ('warehouse_id', '=', False)]) diff --git a/addons/purchase_stock/models/stock_rule.py b/addons/purchase_stock/models/stock_rule.py index e8873375ba9..dbf12ff96dd 100644 --- a/addons/purchase_stock/models/stock_rule.py +++ b/addons/purchase_stock/models/stock_rule.py @@ -266,7 +266,7 @@ class StockRule(models.Model): 'partner_id': partner.id, 'picking_type_id': self.picking_type_id.id, 'company_id': company_id.id, - 'currency_id': partner.with_context(force_company=company_id.id).property_purchase_currency_id.id or self.env.user.company_id.currency_id.id, + 'currency_id': partner.with_context(force_company=company_id.id).property_purchase_currency_id.id or self.env.company_id.currency_id.id, 'dest_address_id': values.get('partner_id', False), 'origin': ', '.join(origins), 'payment_term_id': partner.with_context(force_company=company_id.id).property_supplier_payment_term_id.id, diff --git a/addons/purchase_stock/tests/common.py b/addons/purchase_stock/tests/common.py index 41fe8beb451..1abed5a751e 100644 --- a/addons/purchase_stock/tests/common.py +++ b/addons/purchase_stock/tests/common.py @@ -19,7 +19,7 @@ class TestPurchase(TestStockCommon): } return ProcurementGroup.run([self.env['procurement.group'].Procurement( product, product_qty, self.uom_unit, self.warehouse_1.lot_stock_id, - product.name, '/', self.env.user.company_id, order_values) + product.name, '/', self.env.company_id, order_values) ]) def _load(self, module, *args): diff --git a/addons/purchase_stock/tests/test_create_picking.py b/addons/purchase_stock/tests/test_create_picking.py index 8a2e6c530c7..7beafab87e7 100644 --- a/addons/purchase_stock/tests/test_create_picking.py +++ b/addons/purchase_stock/tests/test_create_picking.py @@ -76,7 +76,7 @@ class TestCreatePicking(common.TestProductCommon): def test_01_check_double_validation(self): # make double validation two step - self.env.user.company_id.write({'po_double_validation': 'two_step','po_double_validation_amount':2000.00}) + self.env.company_id.write({'po_double_validation': 'two_step','po_double_validation_amount':2000.00}) # Draft purchase order created self.po = self.env['purchase.order'].sudo(self.user_purchase_user).create(self.po_vals) diff --git a/addons/purchase_stock/tests/test_purchase_lead_time.py b/addons/purchase_stock/tests/test_purchase_lead_time.py index 96dd98695e8..4d8fbb0ab28 100644 --- a/addons/purchase_stock/tests/test_purchase_lead_time.py +++ b/addons/purchase_stock/tests/test_purchase_lead_time.py @@ -102,7 +102,7 @@ class TestPurchaseLeadTime(TestPurchase): date_planned = fields.Datetime.to_string(fields.datetime.now() + timedelta(days=10)) # Create procurement order of product_1 self.env['procurement.group'].run([self.env['procurement.group'].Procurement( - self.product_1, 5.000, self.uom_unit, self.warehouse_1.lot_stock_id, 'Test scheduler for RFQ', '/', self.env.user.company_id, + self.product_1, 5.000, self.uom_unit, self.warehouse_1.lot_stock_id, 'Test scheduler for RFQ', '/', self.env.company_id, { 'warehouse_id': self.warehouse_1, 'date_planned': date_planned, # 10 days added to current date of procurement to get future schedule date and order date of purchase order. diff --git a/addons/purchase_stock/tests/test_stockvaluation.py b/addons/purchase_stock/tests/test_stockvaluation.py index 808a26d1ae0..211813c8b52 100644 --- a/addons/purchase_stock/tests/test_stockvaluation.py +++ b/addons/purchase_stock/tests/test_stockvaluation.py @@ -145,7 +145,7 @@ class TestStockValuation(TransactionCase): is set according to the last currency rate. """ usd_currency = self.env.ref('base.USD') - self.env.user.company_id.currency_id = usd_currency.id + self.env.company_id.currency_id = usd_currency.id eur_currency = self.env.ref('base.EUR') @@ -174,7 +174,7 @@ class TestStockValuation(TransactionCase): # convert the price unit in the company currency price_unit_usd = po1.currency_id._convert( po1.order_line.price_unit, po1.company_id.currency_id, - self.env.user.company_id, fields.Date.today(), round=False) + self.env.company_id, fields.Date.today(), round=False) # the unit price of the move is the unit price of the purchase order line converted in # the company's currency @@ -190,7 +190,7 @@ class TestStockValuation(TransactionCase): eur_currency._compute_current_rate() price_unit_usd_new_rate = po1.currency_id._convert( po1.order_line.price_unit, po1.company_id.currency_id, - self.env.user.company_id, fields.Date.today(), round=False) + self.env.company_id, fields.Date.today(), round=False) # the new price_unit is lower than th initial because of the rate's change self.assertLess(price_unit_usd_new_rate, price_unit_usd) @@ -320,7 +320,7 @@ class TestStockValuationWithCOA(AccountingTestCase): }) def test_fifo_anglosaxon_return(self): - self.env.user.company_id.anglo_saxon_accounting = True + self.env.company_id.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.product_tmpl_id.invoice_policy = 'delivery' @@ -421,7 +421,7 @@ class TestStockValuationWithCOA(AccountingTestCase): self.assertEqual(price_diff_entry.credit, 100) def test_anglosaxon_valuation(self): - self.env.user.company_id.anglo_saxon_accounting = True + self.env.company_id.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.product_tmpl_id.invoice_policy = 'delivery' diff --git a/addons/repair/models/repair.py b/addons/repair/models/repair.py index a102ec9762d..39ee2a4a8b1 100644 --- a/addons/repair/models/repair.py +++ b/addons/repair/models/repair.py @@ -108,7 +108,7 @@ class Repair(models.Model): quotation_notes = fields.Text('Quotation Notes') company_id = fields.Many2one( 'res.company', 'Company', - default=lambda self: self.env['res.company']._company_default_get('repair.order')) + default=lambda self: self.env.company_id) invoiced = fields.Boolean('Invoiced', copy=False, readonly=True) repaired = fields.Boolean('Repaired', copy=False, readonly=True) amount_untaxed = fields.Float('Untaxed Amount', compute='_amount_untaxed', store=True) diff --git a/addons/repair/security/repair_security.xml b/addons/repair/security/repair_security.xml index a87302b6418..bc0b04a0a0b 100644 --- a/addons/repair/security/repair_security.xml +++ b/addons/repair/security/repair_security.xml @@ -7,7 +7,7 @@ <field name="name">repair multi-company</field> <field name="model_id" search="[('model','=','repair.order')]" model="ir.model"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','child_of',[user.company_id.id]),('company_id','=',False)]</field> + <field name="domain_force">['|',('company_id', 'in', company_ids),('company_id','=',False)]</field> </record> </data> diff --git a/addons/resource/models/resource.py b/addons/resource/models/resource.py index 717fa0faae0..abc1c77c373 100644 --- a/addons/resource/models/resource.py +++ b/addons/resource/models/resource.py @@ -169,7 +169,7 @@ class ResourceCalendar(models.Model): name = fields.Char(required=True) company_id = fields.Many2one( 'res.company', 'Company', - default=lambda self: self.env['res.company']._company_default_get()) + default=lambda self: self.env.company_id) attendance_ids = fields.One2many( 'resource.calendar.attendance', 'calendar_id', 'Working Time', copy=True) @@ -446,7 +446,7 @@ class ResourceResource(models.Model): active = fields.Boolean( 'Active', default=True, tracking=True, help="If the active field is set to False, it will allow you to hide the resource record without removing it.") - company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env['res.company']._company_default_get()) + company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company_id) resource_type = fields.Selection([ ('user', 'Human'), ('material', 'Material')], string='Resource Type', @@ -457,7 +457,7 @@ class ResourceResource(models.Model): help="This field is used to calculate the the expected duration of a work order at this work center. For example, if a work order takes one hour and the efficiency factor is 100%, then the expected duration will be one hour. If the efficiency factor is 200%, however the expected duration will be 30 minutes.") calendar_id = fields.Many2one( "resource.calendar", string='Working Time', - default=lambda self: self.env['res.company']._company_default_get().resource_calendar_id, + default=lambda self: self.env.company_id.resource_calendar_id, required=True, help="Define the schedule of resource") tz = fields.Selection( diff --git a/addons/resource/models/resource_mixin.py b/addons/resource/models/resource_mixin.py index f1dc84564da..9fed050cddf 100644 --- a/addons/resource/models/resource_mixin.py +++ b/addons/resource/models/resource_mixin.py @@ -27,11 +27,11 @@ class ResourceMixin(models.AbstractModel): auto_join=True, index=True, ondelete='restrict', required=True) company_id = fields.Many2one( 'res.company', 'Company', - default=lambda self: self.env['res.company']._company_default_get(), + default=lambda self: self.env.company_id, index=True, related='resource_id.company_id', store=True, readonly=False) resource_calendar_id = fields.Many2one( 'resource.calendar', 'Working Hours', - default=lambda self: self.env['res.company']._company_default_get().resource_calendar_id, + default=lambda self: self.env.company_id.resource_calendar_id, index=True, related='resource_id.calendar_id', store=True, readonly=False) tz = fields.Selection( string='Timezone', related='resource_id.tz', readonly=False, diff --git a/addons/sale/controllers/onboarding.py b/addons/sale/controllers/onboarding.py index 0ab5067cdb3..aa8ad05a189 100644 --- a/addons/sale/controllers/onboarding.py +++ b/addons/sale/controllers/onboarding.py @@ -13,7 +13,7 @@ class OnboardingController(http.Controller): It can be empty if the user has closed it or if he doesn't have the permission to see it. """ - company = request.env.user.company_id + company = request.env.company_id if not request.env.user._is_admin() or \ company.sale_quotation_onboarding_state == 'closed': return {} diff --git a/addons/sale/models/account_invoice.py b/addons/sale/models/account_invoice.py index 6f9c3d2b567..f24dbf66d6a 100644 --- a/addons/sale/models/account_invoice.py +++ b/addons/sale/models/account_invoice.py @@ -43,7 +43,7 @@ class AccountInvoice(models.Model): self.partner_shipping_id = addr and addr.get('delivery') inv_type = self.type or self.env.context.get('type', 'out_invoice') if inv_type == 'out_invoice': - company = self.company_id or self.env.user.company_id + company = self.company_id or self.env.company_id self.comment = company.with_context(lang=self.partner_id.lang).invoice_terms @api.multi diff --git a/addons/sale/models/res_company.py b/addons/sale/models/res_company.py index 439061adafa..0e31c3110d5 100644 --- a/addons/sale/models/res_company.py +++ b/addons/sale/models/res_company.py @@ -27,12 +27,12 @@ class ResCompany(models.Model): @api.model def action_close_sale_quotation_onboarding(self): """ Mark the onboarding panel as closed. """ - self.env.user.company_id.sale_quotation_onboarding_state = 'closed' + self.env.company_id.sale_quotation_onboarding_state = 'closed' @api.model def action_open_sale_onboarding_payment_acquirer(self): """ Called by onboarding panel above the quotation list.""" - self.env.user.company_id.get_chart_of_accounts_or_fail() + self.env.company_id.get_chart_of_accounts_or_fail() action = self.env.ref('sale.action_open_sale_onboarding_payment_acquirer_wizard').read()[0] return action @@ -40,7 +40,7 @@ class ResCompany(models.Model): """ Get a sample quotation or create one if it does not exist. """ # use current user as partner partner = self.env.user.partner_id - company_id = self.env.user.company_id.id + company_id = self.env.company_id.id # is there already one? sample_sales_order = self.env['sale.order'].search( [('company_id', '=', company_id), ('partner_id', '=', partner.id), @@ -107,7 +107,7 @@ class ResCompany(models.Model): def action_open_sale_onboarding_quotation_layout(self): """ Onboarding step for the quotation layout. """ action = self.env.ref('sale.action_open_sale_onboarding_quotation_layout').read()[0] - action['res_id'] = self.env.user.company_id.id + action['res_id'] = self.env.company_id.id return action _sql_constraints = [('check_quotation_validity_days', 'CHECK(quotation_validity_days > 0)', 'Quotation Validity is required and must be greater than 0.')] diff --git a/addons/sale/models/sale.py b/addons/sale/models/sale.py index 219463e3189..4121c25ab3e 100644 --- a/addons/sale/models/sale.py +++ b/addons/sale/models/sale.py @@ -25,16 +25,16 @@ class SaleOrder(models.Model): def _default_validity_date(self): if self.env['ir.config_parameter'].sudo().get_param('sale.use_quotation_validity_days'): - days = self.env.user.company_id.quotation_validity_days + days = self.env.company_id.quotation_validity_days if days > 0: return fields.Date.to_string(datetime.now() + timedelta(days)) return False def _get_default_require_signature(self): - return self.env.user.company_id.portal_confirmation_sign + return self.env.company_id.portal_confirmation_sign def _get_default_require_payment(self): - return self.env.user.company_id.portal_confirmation_pay + return self.env.company_id.portal_confirmation_pay @api.depends('order_line.price_total') def _amount_all(self): @@ -101,7 +101,7 @@ class SaleOrder(models.Model): @api.model def _default_note(self): - return self.env['ir.config_parameter'].sudo().get_param('account.use_invoice_terms') and self.env.user.company_id.invoice_terms or '' + return self.env['ir.config_parameter'].sudo().get_param('account.use_invoice_terms') and self.env.company_id.invoice_terms or '' @api.model def _get_default_team(self): @@ -175,7 +175,7 @@ class SaleOrder(models.Model): payment_term_id = fields.Many2one('account.payment.term', string='Payment Terms', oldname='payment_term', help="Payment terms applies to all invoices issued from this order.") fiscal_position_id = fields.Many2one('account.fiscal.position', oldname='fiscal_position', string='Fiscal Position', help=" Fiscal positions are used to adapt taxes and accounts for particular customers or sales orders/invoices. The default value comes from the customer.") - company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env['res.company']._company_default_get('sale.order')) + company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env.company_id) team_id = fields.Many2one('crm.team', 'Sales Team', change_default=True, default=_get_default_team, oldname='section_id') signature = fields.Binary('Signature', help='Signature received through the portal.', copy=False, attachment=True) @@ -310,8 +310,8 @@ class SaleOrder(models.Model): 'partner_shipping_id': addr['delivery'], 'user_id': self.partner_id.user_id.id or self.partner_id.commercial_partner_id.user_id.id or self.env.uid } - if self.env['ir.config_parameter'].sudo().get_param('account.use_invoice_terms') and self.env.user.company_id.invoice_terms: - values['note'] = self.with_context(lang=self.partner_id.lang).env.user.company_id.invoice_terms + if self.env['ir.config_parameter'].sudo().get_param('account.use_invoice_terms') and self.env.company_id.invoice_terms: + values['note'] = self.with_context(lang=self.partner_id.lang).env.company_id.invoice_terms # Use team of saleman before to fallback on team of partner. values['team_id'] = self.partner_id.user_id and self.partner_id.user_id.sale_team_id.id or self.partner_id.team_id.id @@ -646,7 +646,7 @@ class SaleOrder(models.Model): def message_post(self, **kwargs): if self.env.context.get('mark_so_as_sent'): self.filtered(lambda o: o.state == 'draft').with_context(tracking_disable=True).write({'state': 'sent'}) - self.env.user.company_id.set_onboarding_step_done('sale_onboarding_sample_quotation_state') + self.env.company_id.set_onboarding_step_done('sale_onboarding_sample_quotation_state') return super(SaleOrder, self.with_context(mail_post_autofollow=True)).message_post(**kwargs) @api.multi @@ -1555,7 +1555,7 @@ class SaleOrderLine(models.Model): product_currency = pricelist_item.base_pricelist_id.currency_id currency_id = pricelist_item.pricelist_id.currency_id - product_currency = product_currency or(product.company_id and product.company_id.currency_id) or self.env.user.company_id.currency_id + product_currency = product_currency or(product.company_id and product.company_id.currency_id) or self.env.company_id.currency_id if not currency_id: currency_id = product_currency cur_factor = 1.0 diff --git a/addons/sale/security/sale_security.xml b/addons/sale/security/sale_security.xml index cdb77c39bbe..c779ca25ab3 100644 --- a/addons/sale/security/sale_security.xml +++ b/addons/sale/security/sale_security.xml @@ -42,21 +42,21 @@ <field name="name">Sales Order multi-company</field> <field name="model_id" ref="model_sale_order"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="sale_order_line_comp_rule"> <field name="name">Sales Order Line multi-company</field> <field name="model_id" ref="model_sale_order_line"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="sale_order_report_comp_rule"> <field name="name">Sales Order Analysis multi-company</field> <field name="model_id" ref="model_sale_report"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <!-- Portal Access Rules --> diff --git a/addons/sale/tests/test_onchange.py b/addons/sale/tests/test_onchange.py index de1e63af85b..768cd96f54b 100644 --- a/addons/sale/tests/test_onchange.py +++ b/addons/sale/tests/test_onchange.py @@ -226,9 +226,9 @@ class TestOnchangeProductId(TransactionCase): self.env['res.currency.rate'].create({'name': '2018-07-11', 'rate': 2.0, 'currency_id': other_currency.id, - 'company_id': self.env.user.company_id.id}) + 'company_id': self.env.company_id.id}) self.env['res.currency.rate'].search( - [('currency_id', '=', self.env.user.company_id.currency_id.id)] + [('currency_id', '=', self.env.company_id.currency_id.id)] ).unlink() new_uom = self.env['uom.uom'].create({ 'name': '10 units', diff --git a/addons/sale/tests/test_sale_product_attribute_value_config.py b/addons/sale/tests/test_sale_product_attribute_value_config.py index 087cbe78de5..5b95765dfb2 100644 --- a/addons/sale/tests/test_sale_product_attribute_value_config.py +++ b/addons/sale/tests/test_sale_product_attribute_value_config.py @@ -25,7 +25,7 @@ class TestSaleProductAttributeValueSetup(TestProductAttributeValueSetup): non-reliant on demo data.""" name = fields.Date.today() currency_id = currency.id - company_id = self.env.user.company_id.id + company_id = self.env.company_id.id CurrencyRate = self.env['res.currency.rate'] diff --git a/addons/sale/wizard/payment_acquirer_onboarding_wizard.py b/addons/sale/wizard/payment_acquirer_onboarding_wizard.py index f3a9b63fa24..1042c734977 100644 --- a/addons/sale/wizard/payment_acquirer_onboarding_wizard.py +++ b/addons/sale/wizard/payment_acquirer_onboarding_wizard.py @@ -12,7 +12,7 @@ class PaymentWizard(models.TransientModel): _description = 'Sale Payment acquire onboarding wizard' def _get_default_payment_method(self): - return self.env.user.company_id.sale_onboarding_payment_method or 'digital_signature' + return self.env.company_id.sale_onboarding_payment_method or 'digital_signature' payment_method = fields.Selection([ ('digital_signature', 'Online signature'), @@ -25,7 +25,7 @@ class PaymentWizard(models.TransientModel): def _set_payment_acquirer_onboarding_step_done(self): """ Override. """ - self.env.user.company_id.set_onboarding_step_done('sale_onboarding_order_confirmation_state') + self.env.company_id.set_onboarding_step_done('sale_onboarding_order_confirmation_state') def _on_save_payment_acquirer(self, *args, **kwargs): """ Override """ @@ -34,10 +34,10 @@ class PaymentWizard(models.TransientModel): @api.multi def add_payment_methods(self, *args, **kwargs): - self.env.user.company_id.sale_onboarding_payment_method = self.payment_method + self.env.company_id.sale_onboarding_payment_method = self.payment_method if self.payment_method == 'digital_signature': - self.env.user.company_id.portal_confirmation_sign = True + self.env.company_id.portal_confirmation_sign = True if self.payment_method in ('paypal', 'stripe', 'manual'): - self.env.user.company_id.portal_confirmation_pay = True + self.env.company_id.portal_confirmation_pay = True return super(PaymentWizard, self).add_payment_methods(*args, **kwargs) diff --git a/addons/sale_coupon/models/sale_coupon_program.py b/addons/sale_coupon/models/sale_coupon_program.py index d35734f098b..d7294a23e46 100644 --- a/addons/sale_coupon/models/sale_coupon_program.py +++ b/addons/sale_coupon/models/sale_coupon_program.py @@ -48,7 +48,7 @@ class SaleCouponProgram(models.Model): coupon_count = fields.Integer(compute='_compute_coupon_count') order_count = fields.Integer(compute='_compute_order_count') order_line_ids = fields.Many2many('sale.order.line', store=False, search='_search_order_line_ids') - company_id = fields.Many2one('res.company', string="Company", default=lambda self: self.env.user.company_id) + company_id = fields.Many2one('res.company', string="Company", default=lambda self: self.env.company_id) currency_id = fields.Many2one(string="Currency", related='company_id.currency_id', readonly=True) validity_duration = fields.Integer(default=1, help="Validity duration for a coupon after its generation") diff --git a/addons/sale_crm/models/crm_lead.py b/addons/sale_crm/models/crm_lead.py index e5fe4e07203..11d5e6fdd4f 100644 --- a/addons/sale_crm/models/crm_lead.py +++ b/addons/sale_crm/models/crm_lead.py @@ -20,7 +20,7 @@ class CrmLead(models.Model): total = 0.0 quotation_cnt = 0 sale_order_cnt = 0 - company_currency = lead.company_currency or self.env.user.company_id.currency_id + company_currency = lead.company_currency or self.env.company_id.currency_id for order in lead.order_ids: if order.state in ('draft', 'sent'): quotation_cnt += 1 diff --git a/addons/sale_management/models/sale_order_template.py b/addons/sale_management/models/sale_order_template.py index 493386f33c7..8d1dc596d01 100644 --- a/addons/sale_management/models/sale_order_template.py +++ b/addons/sale_management/models/sale_order_template.py @@ -11,10 +11,10 @@ class SaleOrderTemplate(models.Model): _description = "Quotation Template" def _get_default_require_signature(self): - return self.env.user.company_id.portal_confirmation_sign + return self.env.company_id.portal_confirmation_sign def _get_default_require_payment(self): - return self.env.user.company_id.portal_confirmation_pay + return self.env.company_id.portal_confirmation_pay name = fields.Char('Quotation Template', required=True) sale_order_template_line_ids = fields.One2many('sale.order.template.line', 'sale_order_template_id', 'Lines', copy=True) diff --git a/addons/sale_margin/models/sale_order.py b/addons/sale_margin/models/sale_order.py index 85ada359385..47e7bee47c8 100644 --- a/addons/sale_margin/models/sale_order.py +++ b/addons/sale_margin/models/sale_order.py @@ -12,7 +12,7 @@ class SaleOrderLine(models.Model): purchase_price = fields.Float(string='Cost', digits=dp.get_precision('Product Price')) def _compute_margin(self, order_id, product_id, product_uom_id): - frm_cur = self.env.user.company_id.currency_id + frm_cur = self.env.company_id.currency_id to_cur = order_id.pricelist_id.currency_id purchase_price = product_id.standard_price if product_uom_id != product_id.uom_id: @@ -23,14 +23,14 @@ class SaleOrderLine(models.Model): @api.model def _get_purchase_price(self, pricelist, product, product_uom, date): - frm_cur = self.env.user.company_id.currency_id + frm_cur = self.env.company_id.currency_id to_cur = pricelist.currency_id purchase_price = product.standard_price if product_uom != product.uom_id: purchase_price = product.uom_id._compute_price(purchase_price, product_uom) price = frm_cur._convert( purchase_price, to_cur, - self.order_id.company_id or self.env.user.company_id, + self.order_id.company_id or self.env.company_id, date or fields.Date.today(), round=False) return {'purchase_price': price} diff --git a/addons/sale_purchase/models/sale_order.py b/addons/sale_purchase/models/sale_order.py index 8960907f9ed..4b06daeac78 100644 --- a/addons/sale_purchase/models/sale_order.py +++ b/addons/sale_purchase/models/sale_order.py @@ -192,7 +192,7 @@ class SaleOrderLine(models.Model): 'partner_id': partner_supplier.id, 'partner_ref': partner_supplier.ref, 'company_id': self.company_id.id, - 'currency_id': partner_supplier.property_purchase_currency_id.id or self.env.user.company_id.currency_id.id, + 'currency_id': partner_supplier.property_purchase_currency_id.id or self.env.company_id.currency_id.id, 'dest_address_id': self.order_id.partner_shipping_id.id, 'origin': self.order_id.name, 'payment_term_id': partner_supplier.property_supplier_payment_term_id.id, diff --git a/addons/sale_stock/models/sale_order.py b/addons/sale_stock/models/sale_order.py index 6e7106a930c..6ca313643e5 100644 --- a/addons/sale_stock/models/sale_order.py +++ b/addons/sale_stock/models/sale_order.py @@ -13,7 +13,7 @@ class SaleOrder(models.Model): @api.model def _default_warehouse_id(self): - company = self.env.user.company_id.id + company = self.env.company_id.id warehouse_ids = self.env['stock.warehouse'].search([('company_id', '=', company)], limit=1) return warehouse_ids diff --git a/addons/sale_timesheet/models/project_overview.py b/addons/sale_timesheet/models/project_overview.py index 640288ddba1..a703914b7c7 100644 --- a/addons/sale_timesheet/models/project_overview.py +++ b/addons/sale_timesheet/models/project_overview.py @@ -26,7 +26,7 @@ class Project(models.Model): return values def _plan_prepare_values(self): - currency = self.env.user.company_id.currency_id + currency = self.env.company_id.currency_id uom_hour = self.env.ref('uom.product_uom_hour') hour_rounding = uom_hour.rounding billable_types = ['non_billable', 'non_billable_project', 'billable_time', 'billable_fixed'] diff --git a/addons/sale_timesheet/models/sale_order.py b/addons/sale_timesheet/models/sale_order.py index 542696fdcf7..66600ea170b 100644 --- a/addons/sale_timesheet/models/sale_order.py +++ b/addons/sale_timesheet/models/sale_order.py @@ -221,7 +221,7 @@ class SaleOrderLine(models.Model): ########################################### def _convert_qty_company_hours(self): - company_time_uom_id = self.env.user.company_id.project_time_mode_id + company_time_uom_id = self.env.company_id.project_time_mode_id if self.product_uom.id != company_time_uom_id.id and self.product_uom.category_id.id == company_time_uom_id.category_id.id: planned_hours = self.product_uom._compute_quantity(self.product_uom_qty, company_time_uom_id) else: diff --git a/addons/sale_timesheet/tests/test_reporting.py b/addons/sale_timesheet/tests/test_reporting.py index 19191ba784e..bf9eb378c9c 100644 --- a/addons/sale_timesheet/tests/test_reporting.py +++ b/addons/sale_timesheet/tests/test_reporting.py @@ -121,7 +121,7 @@ class TestReporting(TestCommonSaleTimesheetNoChart): def test_profitability_report(self): # this test suppose everything is in the same currency as the current one - currency = self.env.user.company_id.currency_id + currency = self.env.company_id.currency_id rounding = currency.rounding project_global_stat = self.env['project.profitability.report'].search([('project_id', '=', self.project_global.id)]).read()[0] diff --git a/addons/sales_team/models/crm_team.py b/addons/sales_team/models/crm_team.py index 19ed667dea4..80016cfc24d 100644 --- a/addons/sales_team/models/crm_team.py +++ b/addons/sales_team/models/crm_team.py @@ -24,10 +24,9 @@ class CrmTeam(models.Model): def _get_default_team_id(self, user_id=None): if not user_id: user_id = self.env.uid - company_id = self.sudo(user_id).env.user.company_id.id team_id = self.env['crm.team'].sudo().search([ '|', ('user_id', '=', user_id), ('member_ids', '=', user_id), - '|', ('company_id', '=', False), ('company_id', 'child_of', [company_id]) + '|', ('company_id', '=', False), ('company_id', '=', self.env.company_id.id) ], limit=1) if not team_id and 'default_team_id' in self.env.context: team_id = self.env['crm.team'].browse(self.env.context.get('default_team_id')) @@ -49,7 +48,7 @@ class CrmTeam(models.Model): name = fields.Char('Sales Team', required=True, translate=True) active = fields.Boolean(default=True, help="If the active field is set to false, it will allow you to hide the Sales Team without removing it.") company_id = fields.Many2one('res.company', string='Company', - default=lambda self: self.env['res.company']._company_default_get('crm.team')) + default=lambda self: self.env.company_id) currency_id = fields.Many2one( "res.currency", related='company_id.currency_id', string="Currency", readonly=True) diff --git a/addons/sales_team/security/sales_team_security.xml b/addons/sales_team/security/sales_team_security.xml index 73b8f5e8b8b..6d95bb22adc 100644 --- a/addons/sales_team/security/sales_team_security.xml +++ b/addons/sales_team/security/sales_team_security.xml @@ -37,7 +37,7 @@ <record model="ir.rule" id="sale_team_comp_rule"> <field name="name">Sales Team multi-company</field> <field name="model_id" ref="model_crm_team"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.ui.menu" id="sales_team.menu_sale_config"> diff --git a/addons/sms/wizard/send_sms.py b/addons/sms/wizard/send_sms.py index 786a5e2af76..ba6c709fcdf 100644 --- a/addons/sms/wizard/send_sms.py +++ b/addons/sms/wizard/send_sms.py @@ -32,7 +32,7 @@ class SendSMS(models.TransientModel): def _phone_get_country(self, partner): if 'country_id' in partner: return partner.country_id - return self.env.user.company_id.country_id + return self.env.company_id.country_id def _sms_sanitization(self, partner, field_name): number = partner[field_name] diff --git a/addons/snailmail/models/snailmail_letter.py b/addons/snailmail/models/snailmail_letter.py index bddadf07290..5fd49dd892c 100644 --- a/addons/snailmail/models/snailmail_letter.py +++ b/addons/snailmail/models/snailmail_letter.py @@ -32,15 +32,15 @@ class SnailmailLetter(models.Model): res_id = fields.Integer('Document ID', required=True) partner_id = fields.Many2one('res.partner', string='Recipient', required=True) company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, - default=lambda self: self.env.user.company_id.id) + default=lambda self: self.env.company_id.id) report_template = fields.Many2one('ir.actions.report', 'Optional report to print and attach') attachment_id = fields.Many2one('ir.attachment', string='Attachment', ondelete='cascade') attachment_datas = fields.Binary('Document', related='attachment_id.datas') attachment_fname = fields.Char('Attachment Filename', related='attachment_id.datas_fname') - color = fields.Boolean(string='Color', default=lambda self: self.env.user.company_id.snailmail_color) - cover = fields.Boolean(string='Cover Page', default=lambda self: self.env.user.company_id.snailmail_cover) - duplex = fields.Boolean(string='Both side', default=lambda self: self.env.user.company_id.snailmail_duplex) + color = fields.Boolean(string='Color', default=lambda self: self.env.company_id.snailmail_color) + cover = fields.Boolean(string='Cover Page', default=lambda self: self.env.company_id.snailmail_cover) + duplex = fields.Boolean(string='Both side', default=lambda self: self.env.company_id.snailmail_duplex) state = fields.Selection([ ('pending', 'In Queue'), ('sent', 'Sent'), @@ -402,8 +402,8 @@ class SnailmailLetter(models.Model): 'account_token': "", 'documents': doc_list, 'options': { - 'color': self.env.user.company_id.snailmail_color, - 'duplex': self.env.user.company_id.snailmail_duplex, + 'color': self.env.company_id.snailmail_color, + 'duplex': self.env.company_id.snailmail_duplex, 'currency_name': 'EUR', }, } diff --git a/addons/snailmail/wizard/snailmail_letter_format_error.py b/addons/snailmail/wizard/snailmail_letter_format_error.py index 1eb92654e42..37390cbe78b 100644 --- a/addons/snailmail/wizard/snailmail_letter_format_error.py +++ b/addons/snailmail/wizard/snailmail_letter_format_error.py @@ -11,7 +11,7 @@ class SnailmailLetterFormatError(models.TransientModel): @api.model def default_get(self, fields): res = super(SnailmailLetterFormatError, self).default_get(fields) - snailmail_cover = self.env.user.company_id.snailmail_cover + snailmail_cover = self.env.company_id.snailmail_cover res.update({ 'message_id': self.env.context.get('message_id'), 'snailmail_cover': snailmail_cover, @@ -20,7 +20,7 @@ class SnailmailLetterFormatError(models.TransientModel): @api.multi def update_resend_action(self): - self.env.user.company_id.write({'snailmail_cover': self.snailmail_cover}) + self.env.company_id.write({'snailmail_cover': self.snailmail_cover}) letters_to_resend = self.env['snailmail.letter'].search([ ('error_code', '=', 'FORMAT_ERROR'), ]) diff --git a/addons/snailmail_account/wizard/account_invoice_send.py b/addons/snailmail_account/wizard/account_invoice_send.py index e8575b645d8..24461afc19d 100644 --- a/addons/snailmail_account/wizard/account_invoice_send.py +++ b/addons/snailmail_account/wizard/account_invoice_send.py @@ -11,7 +11,7 @@ class AccountInvoiceSend(models.TransientModel): _description = 'Account Invoice Send' partner_id = fields.Many2one('res.partner', compute='_get_partner', string='Partner') - snailmail_is_letter = fields.Boolean('Send by Post', help='Allows to send the document by Snailmail (coventional posting delivery service)', default=lambda self: self.env.user.company_id.invoice_is_snailmail) + snailmail_is_letter = fields.Boolean('Send by Post', help='Allows to send the document by Snailmail (coventional posting delivery service)', default=lambda self: self.env.company_id.invoice_is_snailmail) snailmail_cost = fields.Float(string='Stamp(s)', compute='_compute_snailmail_cost', readonly=True) invalid_addresses = fields.Integer('Invalid Addresses Count', compute='_compute_invalid_addresses') invalid_invoice_ids = fields.Many2many('account.invoice', string='Invalid Addresses', compute='_compute_invalid_addresses') diff --git a/addons/stock/data/stock_demo.xml b/addons/stock/data/stock_demo.xml index d92c6a69c54..8a119887f22 100644 --- a/addons/stock/data/stock_demo.xml +++ b/addons/stock/data/stock_demo.xml @@ -157,8 +157,8 @@ <record id="res_company_1" model="res.company"> <field name="currency_id" ref="base.USD"/> <field name="partner_id" ref="res_partner_company_1"/> - <field name="parent_id" ref="base.main_company"/> <field name="name">My Company (Chicago)</field> + <field name="user_ids" eval="[(4, ref('base.user_admin')), (4, ref('base.user_demo'))]"/> </record> <record id="base.main_company" model="res.company"> diff --git a/addons/stock/models/product.py b/addons/stock/models/product.py index 1a8c9f7dbb4..e142fe8886f 100644 --- a/addons/stock/models/product.py +++ b/addons/stock/models/product.py @@ -174,7 +174,7 @@ class Product(models.Model): Warehouse = self.env['stock.warehouse'] if self.env.context.get('company_owned', False): - company_id = self.env.user.company_id.id + company_id = self.env.company_id.id return ( [('location_id.company_id', '=', company_id), ('location_id.usage', 'in', ['internal', 'transit'])], [('location_id.company_id', '=', False), ('location_dest_id.company_id', '=', company_id)], diff --git a/addons/stock/models/stock_inventory.py b/addons/stock/models/stock_inventory.py index 4710ff88851..547f2f1858d 100644 --- a/addons/stock/models/stock_inventory.py +++ b/addons/stock/models/stock_inventory.py @@ -14,7 +14,7 @@ class Inventory(models.Model): @api.model def _default_location_id(self): - company_user = self.env.user.company_id + company_user = self.env.company_id warehouse = self.env['stock.warehouse'].search([('company_id', '=', company_user.id)], limit=1) if warehouse: return warehouse.lot_stock_id.id @@ -49,7 +49,7 @@ class Inventory(models.Model): 'res.company', 'Company', readonly=True, index=True, required=True, states={'draft': [('readonly', False)]}, - default=lambda self: self.env['res.company']._company_default_get('stock.inventory')) + default=lambda self: self.env.company_id) location_id = fields.Many2one( 'stock.location', 'Inventoried Location', readonly=True, required=True, diff --git a/addons/stock/models/stock_location.py b/addons/stock/models/stock_location.py index 0656bc6e9ca..628f252f5e1 100644 --- a/addons/stock/models/stock_location.py +++ b/addons/stock/models/stock_location.py @@ -55,7 +55,7 @@ class Location(models.Model): parent_path = fields.Char(index=True) company_id = fields.Many2one( 'res.company', 'Company', - default=lambda self: self.env['res.company']._company_default_get('stock.location'), index=True, + default=lambda self: self.env.company_id, index=True, help='Let this field empty if this location is shared between companies') scrap_location = fields.Boolean('Is a Scrap Location?', default=False, help='Check this box to allow using this location to put scrapped/damaged goods.') return_location = fields.Boolean('Is a Return Location?', help='Check this box to allow using this location as a return location.') @@ -191,7 +191,7 @@ class Route(models.Model): supplier_wh_id = fields.Many2one('stock.warehouse', 'Supplying Warehouse') company_id = fields.Many2one( 'res.company', 'Company', - default=lambda self: self.env['res.company']._company_default_get('stock.location.route'), index=True, + default=lambda self: self.env.company_id, index=True, help='Leave this field empty if this route is shared between all companies') product_ids = fields.Many2many('product.template', 'stock_route_product', 'route_id', 'product_id', 'Products', copy=False) categ_ids = fields.Many2many('product.category', 'stock_location_route_categ', 'route_id', 'categ_id', 'Product Categories', copy=False) diff --git a/addons/stock/models/stock_move.py b/addons/stock/models/stock_move.py index 1595ef7c5cc..c2959a88fe6 100644 --- a/addons/stock/models/stock_move.py +++ b/addons/stock/models/stock_move.py @@ -36,7 +36,7 @@ class StockMove(models.Model): help="Move date: scheduled date until move is done, then date of actual move processing") company_id = fields.Many2one( 'res.company', 'Company', - default=lambda self: self.env['res.company']._company_default_get('stock.move'), + default=lambda self: self.env.company_id, index=True, required=True) date_expected = fields.Datetime( 'Expected Date', default=fields.Datetime.now, index=True, required=True, diff --git a/addons/stock/models/stock_move_line.py b/addons/stock/models/stock_move_line.py index 3e37b6b670b..cdc3db62744 100644 --- a/addons/stock/models/stock_move_line.py +++ b/addons/stock/models/stock_move_line.py @@ -21,7 +21,7 @@ class StockMoveLine(models.Model): move_id = fields.Many2one( 'stock.move', 'Stock Move', help="Change to a better name", index=True) - company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env['res.users']._get_company(), readonly=True) + company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company_id, readonly=True) product_id = fields.Many2one('product.product', 'Product', ondelete="cascade") product_uom_id = fields.Many2one('uom.uom', 'Unit of Measure', required=True) product_qty = fields.Float( @@ -188,7 +188,7 @@ class StockMoveLine(models.Model): 'picking_id': picking.id, }) vals['move_id'] = new_move.id - + mls = super(StockMoveLine, self).create(vals_list) for ml in mls: diff --git a/addons/stock/models/stock_picking.py b/addons/stock/models/stock_picking.py index 6576e00616d..ed1ddf80ab8 100644 --- a/addons/stock/models/stock_picking.py +++ b/addons/stock/models/stock_picking.py @@ -41,7 +41,7 @@ class PickingType(models.Model): show_entire_packs = fields.Boolean('Move Entire Packages', help="If ticked, you will be able to select entire packages to move") warehouse_id = fields.Many2one( 'stock.warehouse', 'Warehouse', ondelete='cascade', - default=lambda self: self.env['stock.warehouse'].search([('company_id', '=', self.env.user.company_id.id)], limit=1)) + default=lambda self: self.env['stock.warehouse'].search([('company_id', '=', self.env.company_id.id)], limit=1)) active = fields.Boolean('Active', default=True) use_create_lots = fields.Boolean( 'Create New Lots/Serial Numbers', default=True, @@ -260,7 +260,7 @@ class Picking(models.Model): states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}) company_id = fields.Many2one( 'res.company', 'Company', - default=lambda self: self.env['res.company']._company_default_get('stock.picking'), + default=lambda self: self.env.company_id, index=True, required=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}) user_id = fields.Many2one( diff --git a/addons/stock/models/stock_quant.py b/addons/stock/models/stock_quant.py index 66a7aa90b8c..4cfaccd96f3 100644 --- a/addons/stock/models/stock_quant.py +++ b/addons/stock/models/stock_quant.py @@ -368,7 +368,7 @@ class QuantPackage(models.Model): @api.depends('quant_ids.package_id', 'quant_ids.location_id', 'quant_ids.company_id', 'quant_ids.owner_id', 'quant_ids.quantity', 'quant_ids.reserved_quantity') def _compute_package_info(self): for package in self: - values = {'location_id': False, 'company_id': self.env.user.company_id.id, 'owner_id': False} + values = {'location_id': False, 'company_id': self.env.company_id.id, 'owner_id': False} if package.quant_ids: values['location_id'] = package.quant_ids[0].location_id if all(q.owner_id == package.quant_ids[0].owner_id for q in package.quant_ids): diff --git a/addons/stock/models/stock_rule.py b/addons/stock/models/stock_rule.py index 84c7e44fe90..2199d4cdea0 100644 --- a/addons/stock/models/stock_rule.py +++ b/addons/stock/models/stock_rule.py @@ -38,7 +38,7 @@ class StockRule(models.Model): required=True) sequence = fields.Integer('Sequence', default=20) company_id = fields.Many2one('res.company', 'Company', - default=lambda self: self.env.user.company_id) + default=lambda self: self.env.company_id) location_id = fields.Many2one('stock.location', 'Destination Location', required=True) location_src_id = fields.Many2one('stock.location', 'Source Location') route_id = fields.Many2one('stock.location.route', 'Route', required=True, ondelete='cascade') @@ -338,7 +338,7 @@ class ProcurementGroup(models.Model): actions_to_run = defaultdict(list) errors = [] for procurement in procurements: - procurement.values.setdefault('company_id', self.env['res.company']._company_default_get('procurement.group')) + procurement.values.setdefault('company_id', self.env.company_id) procurement.values.setdefault('priority', '1') procurement.values.setdefault('date_planned', fields.Datetime.now()) rule = self._get_rule(procurement.product_id, procurement.location_id, procurement.values) @@ -479,7 +479,7 @@ class ProcurementGroup(models.Model): 1000 orderpoints. This is appropriate for batch jobs only. """ - if company_id and self.env.user.company_id.id != company_id: + if company_id and self.env.company_id.id != company_id: # To ensure that the company_id is taken into account for # all the processes triggered by this method # i.e. If a PO is generated by the run of the procurements the diff --git a/addons/stock/models/stock_scrap.py b/addons/stock/models/stock_scrap.py index fc7e9e65c94..950fae2429a 100644 --- a/addons/stock/models/stock_scrap.py +++ b/addons/stock/models/stock_scrap.py @@ -12,10 +12,10 @@ class StockScrap(models.Model): _description = 'Scrap' def _get_default_scrap_location_id(self): - return self.env['stock.location'].search([('scrap_location', '=', True), ('company_id', 'in', [self.env.user.company_id.id, False])], limit=1).id + return self.env['stock.location'].search([('scrap_location', '=', True), ('company_id', 'in', [self.env.company_id.id, False])], limit=1).id def _get_default_location_id(self): - company_user = self.env.user.company_id + company_user = self.env.company_id warehouse = self.env['stock.warehouse'].search([('company_id', '=', company_user.id)], limit=1) if warehouse: return warehouse.lot_stock_id.id diff --git a/addons/stock/models/stock_warehouse.py b/addons/stock/models/stock_warehouse.py index b2f9a934ff9..79f7e0ce3ed 100644 --- a/addons/stock/models/stock_warehouse.py +++ b/addons/stock/models/stock_warehouse.py @@ -22,10 +22,10 @@ class Warehouse(models.Model): # namedtuple used in helper methods generating values for routes Routing = namedtuple('Routing', ['from_loc', 'dest_loc', 'picking_type', 'action']) - name = fields.Char('Warehouse', index=True, required=True, default=lambda self: self.env['res.company']._company_default_get('stock.inventory').name) + name = fields.Char('Warehouse', index=True, required=True, default=lambda self: self.env.company_id.name) active = fields.Boolean('Active', default=True) company_id = fields.Many2one( - 'res.company', 'Company', default=lambda self: self.env['res.company']._company_default_get('stock.inventory'), + 'res.company', 'Company', default=lambda self: self.env.company_id, index=True, readonly=True, required=True, help='The company is automatically set from your user preferences.') partner_id = fields.Many2one('res.partner', 'Address') @@ -242,7 +242,7 @@ class Warehouse(models.Model): transit_loc = ResCompany.browse(company_id).internal_transit_location_id.id self.env['res.partner'].browse(partner_id).with_context(force_company=company_id).write({'property_stock_customer': transit_loc, 'property_stock_supplier': transit_loc}) else: - transit_loc = ResCompany._company_default_get('stock.warehouse').internal_transit_location_id.id + transit_loc = self.env.company_id.internal_transit_location_id.id self.env['res.partner'].browse(partner_id).write({'property_stock_customer': transit_loc, 'property_stock_supplier': transit_loc}) def _create_or_update_sequences_and_picking_types(self): @@ -959,7 +959,7 @@ class Orderpoint(models.Model): help="Moves created through this orderpoint will be put in this procurement group. If none is given, the moves generated by stock rules will be grouped into one big picking.") company_id = fields.Many2one( 'res.company', 'Company', required=True, - default=lambda self: self.env['res.company']._company_default_get('stock.warehouse.orderpoint')) + default=lambda self: self.env.company_id) lead_days = fields.Integer( 'Lead Time', default=1, help="Number of days after the orderpoint is triggered to receive the products or to order to the vendor") diff --git a/addons/stock/security/stock_security.xml b/addons/stock/security/stock_security.xml index b738306073a..df9955c9b5a 100644 --- a/addons/stock/security/stock_security.xml +++ b/addons/stock/security/stock_security.xml @@ -69,14 +69,14 @@ <field name="name">stock_picking multi-company</field> <field name="model_id" search="[('model','=','stock.picking')]" model="ir.model"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="stock_picking_type_rule"> <field name="name">Stock Operation Type multi-company</field> <field name="model_id" search="[('model','=','stock.picking.type')]" model="ir.model"/> <field name="global" eval="True"/> - <field name="domain_force">['|', ('warehouse_id', '=', False), '|',('warehouse_id.company_id','=',False),('warehouse_id.company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|', ('warehouse_id', '=', False), '|',('warehouse_id.company_id','=',False),('warehouse_id.company_id','in', company_ids)]</field> </record> @@ -85,78 +85,84 @@ <field name="name">Warehouse multi-company</field> <field name="model_id" ref="model_stock_warehouse"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="stock_location_comp_rule"> <field name="name">Location multi-company</field> <field name="model_id" ref="model_stock_location"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="stock_move_rule"> <field name="name">stock_move multi-company</field> <field name="model_id" search="[('model','=','stock.move')]" model="ir.model"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="stock_move_line_rule"> <field name="name">stock_move_line multi-company</field> <field name="model_id" search="[('model','=','stock.move.line')]" model="ir.model"/> <field name="global" eval="True"/> - <field name="domain_force">[('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">[('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="stock_quant_rule"> <field name="name">stock_quant multi-company</field> <field name="model_id" ref="model_stock_quant"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="stock_inventory_line_comp_rule"> <field name="name">Inventory Line multi-company</field> <field name="model_id" ref="model_stock_inventory_line"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="stock_inventory_comp_rule"> <field name="name">Inventory multi-company</field> <field name="model_id" ref="model_stock_inventory"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="stock_warehouse_orderpoint_rule"> <field name="name">stock_warehouse.orderpoint multi-company</field> <field name="model_id" search="[('model','=','stock.warehouse.orderpoint')]" model="ir.model"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','child_of',[user.company_id.id]),('company_id','=',False)]</field> + <field name="domain_force">['|',('company_id', 'in', company_ids),('company_id','=',False)]</field> </record> <record model="ir.rule" id="product_pulled_flow_comp_rule"> <field name="name">product_pulled_flow multi-company</field> <field name="model_id" ref="model_stock_rule"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="stock_location_route_comp_rule"> <field name="name">stock_location_route multi-company</field> <field name="model_id" ref="model_stock_location_route"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <record model="ir.rule" id="product_pulled_flow_comp_rule"> <field name="name">product_pulled_flow multi-company</field> <field name="model_id" ref="model_stock_rule"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> + <record model="ir.rule" id="stock_quant_package_comp_rule"> + <field name="name">stock_quant_package multi-company</field> + <field name="model_id" ref="model_stock_quant_package"/> + <field name="global" eval="True"/> + <field name="domain_force">['|', ('company_id', '=', False), ('company_id', 'in', company_ids)]</field> + </record> </data> </odoo> diff --git a/addons/stock/tests/test_move.py b/addons/stock/tests/test_move.py index e009fc5ee7d..6b308edef59 100644 --- a/addons/stock/tests/test_move.py +++ b/addons/stock/tests/test_move.py @@ -14,7 +14,7 @@ class StockMove(TransactionCase): self.pack_location = self.env.ref('stock.location_pack_zone') self.pack_location.active = True self.transit_location = self.env['stock.location'].search([ - ('company_id', '=', self.env.user.company_id.id), + ('company_id', '=', self.env.company_id.id), ('usage', '=', 'transit'), ], limit=1) self.uom_unit = self.env.ref('uom.product_uom_unit') diff --git a/addons/stock/tests/test_move2.py b/addons/stock/tests/test_move2.py index 982cddc5195..1ada2f45dbd 100644 --- a/addons/stock/tests/test_move2.py +++ b/addons/stock/tests/test_move2.py @@ -2030,7 +2030,7 @@ class TestRoutes(TestStockCommon): 'name': 'create a move to push location', 'location_src_id': stock_location.id, 'location_id': push_location.id, - 'company_id': self.env.user.company_id.id, + 'company_id': self.env.company_id.id, 'action': 'push', 'auto': 'manual', 'picking_type_id': self.env.ref('stock.picking_type_in').id, diff --git a/addons/stock/tests/test_stock_flow.py b/addons/stock/tests/test_stock_flow.py index d8260ec90a2..37cbcaaf605 100644 --- a/addons/stock/tests/test_stock_flow.py +++ b/addons/stock/tests/test_stock_flow.py @@ -1857,11 +1857,11 @@ class TestStockFlow(TestStockCommon): # Need to add a new company on user. self.env.user.write({'company_ids': [(4, company_2.id)]}) - warehouse_company_1 = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.company_id.id)], limit=1) + warehouse_company_1 = self.env['stock.warehouse'].search([('company_id', '=', self.env.company_id.id)], limit=1) f = Form(self.env['stock.location.route']) f.name = 'From Company 1 to InterCompany' - f.company_id = self.env.user.company_id + f.company_id = self.env.company_id with f.rule_ids.new() as rule: rule.name = 'From Company 1 to InterCompany' rule.action = 'pull' @@ -1898,8 +1898,8 @@ class TestStockFlow(TestStockCommon): incoming_picking = self.env['stock.picking'].search([('product_id', '=', product.id), ('picking_type_id', '=', warehouse_company_1.in_type_id.id)]) outgoing_picking = self.env['stock.picking'].search([('product_id', '=', product.id), ('picking_type_id', '=', warehouse_company_2.out_type_id.id)]) - self.assertEqual(incoming_picking.company_id, self.env.user.company_id) - self.assertEqual(incoming_picking.move_lines.company_id, self.env.user.company_id) + self.assertEqual(incoming_picking.company_id, self.env.company_id) + self.assertEqual(incoming_picking.move_lines.company_id, self.env.company_id) self.assertEqual(outgoing_picking.company_id, company_2) self.assertEqual(outgoing_picking.move_lines.company_id, company_2) @@ -1921,11 +1921,11 @@ class TestStockFlow(TestStockCommon): # Need to add a new company on user. self.env.user.write({'company_ids': [(4, company_2.id)]}) - warehouse_company_1 = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.company_id.id)], limit=1) + warehouse_company_1 = self.env['stock.warehouse'].search([('company_id', '=', self.env.company_id.id)], limit=1) f = Form(self.env['stock.location.route']) f.name = 'From Company 1 to InterCompany' - f.company_id = self.env.user.company_id + f.company_id = self.env.company_id with f.rule_ids.new() as rule: rule.name = 'From Company 1 to InterCompany' rule.action = 'pull' @@ -1990,15 +1990,15 @@ class TestStockFlow(TestStockCommon): incoming_picking = self.env['stock.picking'].search([('product_id', '=', product_from_company_2.id), ('picking_type_id', '=', warehouse_company_1.in_type_id.id)]) outgoing_picking = self.env['stock.picking'].search([('product_id', '=', product_from_company_2.id), ('picking_type_id', '=', warehouse_company_2.out_type_id.id)]) - self.assertEqual(incoming_picking.company_id, self.env.user.company_id) - self.assertEqual(incoming_picking.move_lines.mapped('company_id'), self.env.user.company_id) + self.assertEqual(incoming_picking.company_id, self.env.company_id) + self.assertEqual(incoming_picking.move_lines.mapped('company_id'), self.env.company_id) self.assertEqual(outgoing_picking.company_id, company_2) self.assertEqual(outgoing_picking.move_lines.company_id, company_2) incoming_picking = self.env['stock.picking'].search([('product_id', '=', product_from_company_3.id), ('picking_type_id', '=', warehouse_company_1.in_type_id.id)]) outgoing_picking = self.env['stock.picking'].search([('product_id', '=', product_from_company_3.id), ('picking_type_id', '=', warehouse_company_3.out_type_id.id)]) - self.assertEqual(incoming_picking.company_id, self.env.user.company_id) - self.assertEqual(incoming_picking.move_lines.mapped('company_id'), self.env.user.company_id) + self.assertEqual(incoming_picking.company_id, self.env.company_id) + self.assertEqual(incoming_picking.move_lines.mapped('company_id'), self.env.company_id) self.assertEqual(outgoing_picking.company_id, company_3) self.assertEqual(outgoing_picking.move_lines.company_id, company_3) diff --git a/addons/stock/views/stock_move_line_views.xml b/addons/stock/views/stock_move_line_views.xml index a76db3150c1..8e95caf13f6 100644 --- a/addons/stock/views/stock_move_line_views.xml +++ b/addons/stock/views/stock_move_line_views.xml @@ -13,6 +13,7 @@ <field name="qty_done" string="Quantity Done"/> <field name="product_uom_id" options="{'no_open': True, 'no_create': True}" string="Unit of Measure" groups="uom.group_uom"/> <field name="state"/> + <field name="company_id" groups="base.group_multi_company"/> </tree> </field> </record> diff --git a/addons/stock/views/stock_move_views.xml b/addons/stock/views/stock_move_views.xml index e3a2d5674c4..e1ee126c51a 100644 --- a/addons/stock/views/stock_move_views.xml +++ b/addons/stock/views/stock_move_views.xml @@ -62,6 +62,7 @@ <field name="product_uom_qty"/> <field name="product_uom" options="{'no_open': True, 'no_create': True}" string="Unit of Measure" groups="uom.group_uom"/> <field name="state"/> + <field name="company_id" groups="base.group_multi_company"/> </tree> </field> </record> diff --git a/addons/stock/views/stock_picking_views.xml b/addons/stock/views/stock_picking_views.xml index 1a2d1f37cea..a43a8fb8edd 100644 --- a/addons/stock/views/stock_picking_views.xml +++ b/addons/stock/views/stock_picking_views.xml @@ -331,7 +331,7 @@ <field name="priority" widget="priority"/> <field name="user_id"/> <field name="group_id" groups="base.group_no_one"/> - <field name="company_id" groups="base.group_multi_company" options="{'no_create': True}"/> + <field name="company_id" groups="base.group_multi_company" options="{'no_create': True}" readonly="1"/> </group> </group> </page> diff --git a/addons/stock/wizard/product_replenish.py b/addons/stock/wizard/product_replenish.py index d615943aa7e..ad4ce418c70 100644 --- a/addons/stock/wizard/product_replenish.py +++ b/addons/stock/wizard/product_replenish.py @@ -25,7 +25,7 @@ class ProductReplenish(models.TransientModel): @api.model def default_get(self, fields): res = super(ProductReplenish, self).default_get(fields) - company_user = self.env.user.company_id + company_user = self.env.company_id warehouse = self.env['stock.warehouse'].search([('company_id', '=', company_user.id)], limit=1) product_tmpl_id = False if 'product_id' in fields: diff --git a/addons/stock/wizard/stock_change_product_qty.py b/addons/stock/wizard/stock_change_product_qty.py index f33a6c10e36..211d2004227 100644 --- a/addons/stock/wizard/stock_change_product_qty.py +++ b/addons/stock/wizard/stock_change_product_qty.py @@ -24,7 +24,7 @@ class ProductChangeQuantity(models.TransientModel): def default_get(self, fields): res = super(ProductChangeQuantity, self).default_get(fields) if 'location_id' in fields and not res.get('location_id'): - company_user = self.env.user.company_id + company_user = self.env.company_id warehouse = self.env['stock.warehouse'].search([('company_id', '=', company_user.id)], limit=1) if warehouse: res['location_id'] = warehouse.lot_stock_id.id diff --git a/addons/stock/wizard/stock_scheduler_compute.py b/addons/stock/wizard/stock_scheduler_compute.py index 0aedafb0bf1..9c13e79b1a8 100644 --- a/addons/stock/wizard/stock_scheduler_compute.py +++ b/addons/stock/wizard/stock_scheduler_compute.py @@ -35,7 +35,8 @@ class StockSchedulerCompute(models.TransientModel): return {} for company in self.env.user.company_ids: - self.env['procurement.group'].run_scheduler( + cids = (self.env.user.company_id | self.env.user.company_ids).ids + self.env['procurement.group'].with_context(allowed_company_ids=cids).run_scheduler( use_new_cursor=self._cr.dbname, company_id=company.id) new_cr.close() diff --git a/addons/stock_account/models/product.py b/addons/stock_account/models/product.py index 3ba8f85bf26..0f637b507e1 100644 --- a/addons/stock_account/models/product.py +++ b/addons/stock_account/models/product.py @@ -67,7 +67,7 @@ class ProductProduct(models.Model): quant_locs = self.env['stock.quant'].sudo().read_group([('product_id', 'in', self.ids)], ['location_id'], ['location_id']) quant_loc_ids = [loc['location_id'][0] for loc in quant_locs] - locations = self.env['stock.location'].search([('usage', '=', 'internal'), ('company_id', '=', self.env.user.company_id.id), ('id', 'in', quant_loc_ids)]) + locations = self.env['stock.location'].search([('usage', '=', 'internal'), ('company_id', '=', self.env.company_id.id), ('id', 'in', quant_loc_ids)]) product_accounts = {product.id: product.product_tmpl_id.get_product_accounts() for product in self} @@ -128,7 +128,7 @@ class ProductProduct(models.Model): @api.multi def _compute_stock_value_currency(self): - currency_id = self.env.user.company_id.currency_id + currency_id = self.env.company_id.currency_id for product in self: product.stock_value_currency_id = currency_id @@ -146,7 +146,7 @@ class ProductProduct(models.Model): FROM account_move_line AS aml WHERE aml.product_id IN %%s AND aml.company_id=%%s %s GROUP BY aml.product_id, aml.account_id""" - params = (tuple(real_time_product_ids), self.env.user.company_id.id) + params = (tuple(real_time_product_ids), self.env.company_id.id) if to_date: query = query % ('AND aml.date <= %s',) params = params + (to_date,) @@ -177,7 +177,7 @@ class ProductProduct(models.Model): price_used = product.standard_price if to_date: price_used = product.get_history_price( - self.env.user.company_id.id, + self.env.company_id.id, date=to_date, ) product.stock_value = price_used * qty_available diff --git a/addons/stock_account/models/stock.py b/addons/stock_account/models/stock.py index 82981e657cb..aa8267cb5fd 100644 --- a/addons/stock_account/models/stock.py +++ b/addons/stock_account/models/stock.py @@ -166,8 +166,8 @@ class StockMove(models.Model): ('location_id.company_id', '=', False), '&', ('location_id.usage', 'in', ['inventory', 'production']), - ('location_id.company_id', '=', company_id or self.env.user.company_id.id), - ('location_dest_id.company_id', '=', company_id or self.env.user.company_id.id), + ('location_id.company_id', '=', company_id or self.env.company_id.id), + ('location_dest_id.company_id', '=', company_id or self.env.company_id.id), ] return domain @@ -190,15 +190,15 @@ class StockMove(models.Model): ('location_id.company_id', '=', False), '&', ('location_id.usage', 'in', ['inventory', 'production']), - ('location_id.company_id', '=', company_id or self.env.user.company_id.id), - ('location_dest_id.company_id', '=', company_id or self.env.user.company_id.id), + ('location_id.company_id', '=', company_id or self.env.company_id.id), + ('location_dest_id.company_id', '=', company_id or self.env.company_id.id), '&', - ('location_id.company_id', '=', company_id or self.env.user.company_id.id), + ('location_id.company_id', '=', company_id or self.env.company_id.id), '|', ('location_dest_id.company_id', '=', False), '&', ('location_dest_id.usage', '=', 'inventory'), - ('location_dest_id.company_id', '=', company_id or self.env.user.company_id.id), + ('location_dest_id.company_id', '=', company_id or self.env.company_id.id), ] return domain diff --git a/addons/stock_account/security/stock_account_security.xml b/addons/stock_account/security/stock_account_security.xml index afbbbf7ca80..ea222a0fcc5 100644 --- a/addons/stock_account/security/stock_account_security.xml +++ b/addons/stock_account/security/stock_account_security.xml @@ -9,7 +9,7 @@ <field name="name">Stock History multi-company</field> <field name="model_id" search="[('model','=','stock.history')]" model="ir.model"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> --> </data> diff --git a/addons/stock_account/tests/test_anglo_saxon_valuation_reconciliation_common.py b/addons/stock_account/tests/test_anglo_saxon_valuation_reconciliation_common.py index cb254a392ab..ca4aab2f749 100644 --- a/addons/stock_account/tests/test_anglo_saxon_valuation_reconciliation_common.py +++ b/addons/stock_account/tests/test_anglo_saxon_valuation_reconciliation_common.py @@ -53,7 +53,7 @@ class ValuationReconciliationTestCase(AccountingTestCase): def setUp(self): super(ValuationReconciliationTestCase, self).setUp() - self.company = self.env['res.company']._company_default_get() + self.company = self.env.company_id self.company.anglo_saxon_accounting = True self.currency_one = self.company.currency_id currency_two_name = 'USD' if self.currency_one.name != 'USD' else 'EUR' diff --git a/addons/stock_account/tests/test_stockvaluation.py b/addons/stock_account/tests/test_stockvaluation.py index 7b2af95cddd..17a797aee69 100644 --- a/addons/stock_account/tests/test_stockvaluation.py +++ b/addons/stock_account/tests/test_stockvaluation.py @@ -941,7 +941,7 @@ class TestStockValuation(TransactionCase): # send 10 units in our transit location, the valorisation should not be impacted transit_location = self.env['stock.location'].search([ - ('company_id', '=', self.env.user.company_id.id), + ('company_id', '=', self.env.company_id.id), ('usage', '=', 'transit'), ], limit=1) move8 = self.env['stock.move'].create({ diff --git a/addons/stock_dropshipping/tests/test_stockvaluation.py b/addons/stock_dropshipping/tests/test_stockvaluation.py index 03cae895d0f..14fcd02f69d 100644 --- a/addons/stock_dropshipping/tests/test_stockvaluation.py +++ b/addons/stock_dropshipping/tests/test_stockvaluation.py @@ -107,7 +107,7 @@ class TestStockValuation(AccountingTestCase): # Continental # ------------------------------------------------------------------------- def test_dropship_standard_perpetual_continental_ordered(self): - self.env.user.company_id.anglo_saxon_accounting = False + self.env.company_id.anglo_saxon_accounting = False self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' @@ -125,7 +125,7 @@ class TestStockValuation(AccountingTestCase): self._check_results(expected_aml, 4, all_amls) def test_dropship_standard_perpetual_continental_delivered(self): - self.env.user.company_id.anglo_saxon_accounting = False + self.env.company_id.anglo_saxon_accounting = False self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' @@ -143,7 +143,7 @@ class TestStockValuation(AccountingTestCase): self._check_results(expected_aml, 4, all_amls) def test_dropship_fifo_perpetual_continental_ordered(self): - self.env.user.company_id.anglo_saxon_accounting = False + self.env.company_id.anglo_saxon_accounting = False self.product1.product_tmpl_id.categ_id.proprty_cost_method = 'fifo' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' @@ -161,7 +161,7 @@ class TestStockValuation(AccountingTestCase): self._check_results(expected_aml, 4, all_amls) def test_dropship_fifo_perpetual_continental_delivered(self): - self.env.user.company_id.anglo_saxon_accounting = False + self.env.company_id.anglo_saxon_accounting = False self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.standard_price = 10 @@ -183,7 +183,7 @@ class TestStockValuation(AccountingTestCase): # Anglosaxon # ------------------------------------------------------------------------- def test_dropship_standard_perpetual_anglosaxon_ordered(self): - self.env.user.company_id.anglo_saxon_accounting = True + self.env.company_id.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' @@ -206,7 +206,7 @@ class TestStockValuation(AccountingTestCase): self._check_results(expected_aml, 8, all_amls) def test_dropship_standard_perpetual_anglosaxon_delivered(self): - self.env.user.company_id.anglo_saxon_accounting = True + self.env.company_id.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' @@ -229,7 +229,7 @@ class TestStockValuation(AccountingTestCase): self._check_results(expected_aml, 8, all_amls) def test_dropship_fifo_perpetual_anglosaxon_ordered(self): - self.env.user.company_id.anglo_saxon_accounting = True + self.env.company_id.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' @@ -249,7 +249,7 @@ class TestStockValuation(AccountingTestCase): self._check_results(expected_aml, 8, all_amls) def test_dropship_fifo_perpetual_anglosaxon_delivered(self): - self.env.user.company_id.anglo_saxon_accounting = True + self.env.company_id.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' @@ -269,7 +269,7 @@ class TestStockValuation(AccountingTestCase): self._check_results(expected_aml, 8, all_amls) def test_dropship_standard_perpetual_anglosaxon_ordered_return(self): - self.env.user.company_id.anglo_saxon_accounting = True + self.env.company_id.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' diff --git a/addons/stock_landed_costs/models/stock_landed_cost.py b/addons/stock_landed_costs/models/stock_landed_cost.py index e47e00a9ed1..7f21cfafa6c 100644 --- a/addons/stock_landed_costs/models/stock_landed_cost.py +++ b/addons/stock_landed_costs/models/stock_landed_cost.py @@ -128,7 +128,7 @@ class LandedCost(models.Model): def _check_sum(self): """ Check if each cost line its valuation lines sum to the correct amount and if the overall total amount is correct also """ - prec_digits = self.env.user.company_id.currency_id.decimal_places + prec_digits = self.env.company_id.currency_id.decimal_places for landed_cost in self: total_amount = sum(landed_cost.valuation_adjustment_lines.mapped('additional_landed_cost')) if not tools.float_compare(total_amount, landed_cost.amount_total, precision_digits=prec_digits) == 0: @@ -365,7 +365,7 @@ class AdjustmentLines(models.Model): AccountMoveLine.append([0, 0, credit_line]) # TDE FIXME: oh dear - if self.env.user.company_id.anglo_saxon_accounting: + if self.env.company_id.anglo_saxon_accounting: debit_line = dict(base_line, name=(self.name + ": " + str(qty_out) + _(' already out')), quantity=0, diff --git a/addons/stock_landed_costs/security/stock_landed_cost_security.xml b/addons/stock_landed_costs/security/stock_landed_cost_security.xml index 1182f9c687a..8dcbc0e9762 100644 --- a/addons/stock_landed_costs/security/stock_landed_cost_security.xml +++ b/addons/stock_landed_costs/security/stock_landed_cost_security.xml @@ -6,7 +6,7 @@ <field name="name">stock_landed_cost multi-company</field> <field name="model_id" search="[('model','=','stock.landed.cost')]" model="ir.model"/> <field name="global" eval="True"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> </data> diff --git a/addons/stock_landed_costs/tests/test_stock_landed_costs.py b/addons/stock_landed_costs/tests/test_stock_landed_costs.py index 9735d5eb696..793b913dc59 100644 --- a/addons/stock_landed_costs/tests/test_stock_landed_costs.py +++ b/addons/stock_landed_costs/tests/test_stock_landed_costs.py @@ -58,7 +58,7 @@ class TestStockLandedCosts(TestStockLandedCostsCommon): picking_landed_cost_1 = self.env['stock.picking'].create(vals) # Confirm and assign picking - self.env.user.company_id.anglo_saxon_accounting = True + self.env.company_id.anglo_saxon_accounting = True picking_landed_cost_1.action_confirm() picking_landed_cost_1.action_assign() picking_landed_cost_1.move_lines.quantity_done = 5 diff --git a/addons/stock_landed_costs/tests/test_stock_landed_costs_purchase.py b/addons/stock_landed_costs/tests/test_stock_landed_costs_purchase.py index 9c2abe7fa29..4a7ab6e6eff 100644 --- a/addons/stock_landed_costs/tests/test_stock_landed_costs_purchase.py +++ b/addons/stock_landed_costs/tests/test_stock_landed_costs_purchase.py @@ -48,7 +48,7 @@ class TestLandedCosts(TestStockLandedCostsCommon): 'location_dest_id': self.customer_location_id}) def test_00_landed_costs_on_incoming_shipment(self): - chart_of_accounts = self.env.user.company_id.chart_template_id + chart_of_accounts = self.env.company_id.chart_template_id generic_coa = self.env.ref('l10n_generic_coa.configurable_chart_template') if chart_of_accounts != generic_coa: raise unittest.SkipTest('Skip this test as it works only with %s (%s loaded)' % (generic_coa.name, chart_of_accounts.name)) @@ -101,7 +101,7 @@ class TestLandedCosts(TestStockLandedCostsCommon): self.assertEqual(account_entry['debit'], 430.0, 'Wrong Account Entry') def test_01_negative_landed_costs_on_incoming_shipment(self): - chart_of_accounts = self.env.user.company_id.chart_template_id + chart_of_accounts = self.env.company_id.chart_template_id generic_coa = self.env.ref('l10n_generic_coa.configurable_chart_template') if chart_of_accounts != generic_coa: raise unittest.SkipTest('Skip this test as it works only with %s (%s loaded)' % (generic_coa.name, chart_of_accounts.name)) diff --git a/addons/survey/wizard/survey_invite.py b/addons/survey/wizard/survey_invite.py index 305b85b39d8..557b3f7d119 100644 --- a/addons/survey/wizard/survey_invite.py +++ b/addons/survey/wizard/survey_invite.py @@ -227,7 +227,7 @@ class SurveyInvite(models.TransientModel): template_ctx = { 'message': self.env['mail.message'].sudo().new(dict(body=mail_values['body_html'], record_name=self.survey_id.title)), 'model_description': self.env['ir.model']._get('survey.survey').display_name, - 'company': self.env.user.company_id, + 'company': self.env.company_id, } body = template.render(template_ctx, engine='ir.qweb', minimal_qcontext=True) mail_values['body_html'] = self.env['mail.thread']._replace_local_links(body) diff --git a/addons/test_mail/tests/test_mail_channel.py b/addons/test_mail/tests/test_mail_channel.py index c95f562332d..9994fcf76a0 100644 --- a/addons/test_mail/tests/test_mail_channel.py +++ b/addons/test_mail/tests/test_mail_channel.py @@ -248,7 +248,7 @@ class TestChannelModeration(common.Moderation): self._init_mock_build_email() self.channel_1.sudo(self.user_employee).send_guidelines() self.env['mail.mail'].process_email_queue() - self.assertEmails(False, self.partner_employee | self.partner_employee_2, email_from=self.env.user.company_id.catchall or self.env.user.company_id.email) + self.assertEmails(False, self.partner_employee | self.partner_employee_2, email_from=self.env.company_id.catchall or self.env.company_id.email) def test_send_guidelines_crash(self): with self.assertRaises(UserError): diff --git a/addons/test_mail/tests/test_mail_message.py b/addons/test_mail/tests/test_mail_message.py index c5962339f68..eb11145423b 100644 --- a/addons/test_mail/tests/test_mail_message.py +++ b/addons/test_mail/tests/test_mail_message.py @@ -62,7 +62,7 @@ class TestMessageValues(common.BaseFunctionalTest, common.MockEmails): msg = self.Message.create({}) self.assertIn('-private', msg.message_id.split('@')[0], 'mail_message: message_id for a void message should be a "private" one') - reply_to_name = self.env.user.company_id.name + reply_to_name = self.env.company_id.name reply_to_email = '%s@%s' % (alias_catchall, alias_domain) self.assertEqual(msg.reply_to, formataddr((reply_to_name, reply_to_email))) self.assertEqual(msg.email_from, formataddr((self.user_employee.name, self.user_employee.email))) @@ -89,7 +89,7 @@ class TestMessageValues(common.BaseFunctionalTest, common.MockEmails): 'res_id': self.alias_record.id }) self.assertIn('-openerp-%d-mail.test' % self.alias_record.id, msg.message_id.split('@')[0]) - reply_to_name = '%s %s' % (self.env.user.company_id.name, self.alias_record.name) + reply_to_name = '%s %s' % (self.env.company_id.name, self.alias_record.name) reply_to_email = '%s@%s' % (self.alias_record.alias_name, alias_domain) self.assertEqual(msg.reply_to, formataddr((reply_to_name, reply_to_email))) self.assertEqual(msg.email_from, '%s <%s>' % (self.user_employee.name, self.user_employee.email)) @@ -105,7 +105,7 @@ class TestMessageValues(common.BaseFunctionalTest, common.MockEmails): 'res_id': self.alias_record.id }) self.assertIn('-openerp-%d-mail.test' % self.alias_record.id, msg.message_id.split('@')[0]) - reply_to_name = '%s %s' % (self.env.user.company_id.name, self.alias_record.name) + reply_to_name = '%s %s' % (self.env.company_id.name, self.alias_record.name) reply_to_email = '%s@%s' % (self.alias_record.alias_name, alias_domain) self.assertEqual(msg.reply_to, formataddr((reply_to_name, reply_to_email))) self.assertEqual(msg.email_from, '%s <%s>' % (self.user_employee.name, self.user_employee.email)) @@ -452,4 +452,4 @@ class TestMessageModeration(common.Moderation): msg_emp_pending_c2 = self._create_new_message(self.channel_2.id, status='pending_moderation', author=self.partner_employee) self.env['mail.message']._notify_moderators() - self.assertEmails(False, self.partner_employee | self.partner_employee_2, subject='Message are pending moderation', email_from=self.env.user.company_id.catchall or self.env.user.company_id.email) + self.assertEmails(False, self.partner_employee | self.partner_employee_2, subject='Message are pending moderation', email_from=self.env.company_id.catchall or self.env.company_id.email) diff --git a/addons/test_mail/tests/test_mail_template.py b/addons/test_mail/tests/test_mail_template.py index 40fa3f8b634..2a48312b12e 100644 --- a/addons/test_mail/tests/test_mail_template.py +++ b/addons/test_mail/tests/test_mail_template.py @@ -207,7 +207,7 @@ class TestMailTemplate(BaseFunctionalTest, MockEmails, TestRecipients): def test_create_partner_from_tracking_multicompany(self): company1 = self.env['res.company'].create({'name': 'company1'}) self.env.user.write({'company_ids': [(4, company1.id, False)]}) - self.assertNotEqual(self.env.user.company_id, company1) + self.assertNotEqual(self.env.company_id, company1) email_new_partner = "diamonds@rust.com" Partner = self.env['res.partner'] diff --git a/addons/test_mail/tests/test_performance.py b/addons/test_mail/tests/test_performance.py index 5faafe266b8..2cdce3872b3 100644 --- a/addons/test_mail/tests/test_performance.py +++ b/addons/test_mail/tests/test_performance.py @@ -390,7 +390,7 @@ class TestHeavyMailPerformance(TransactionCase): self.env['mail.mail'].browse(mail_ids).send() self.assertEqual(mail.body_html, '<p>Test</p>') - self.assertEqual(mail.reply_to, formataddr(('%s %s' % (self.env.user.company_id.name, self.umbrella.name), 'test-alias@example.com'))) + self.assertEqual(mail.reply_to, formataddr(('%s %s' % (self.env.company_id.name, self.umbrella.name), 'test-alias@example.com'))) @mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink') @users('__system__', 'emp') diff --git a/addons/web/models/ir_http.py b/addons/web/models/ir_http.py index 414df12d8c5..15fc49cff29 100644 --- a/addons/web/models/ir_http.py +++ b/addons/web/models/ir_http.py @@ -20,7 +20,6 @@ class Http(models.AbstractModel): def session_info(self): user = request.env.user - display_switch_company_menu = user.has_group('base.group_multi_company') and len(user.company_ids) > 1 version_info = odoo.service.common.exp_version() return { "uid": request.session.uid, @@ -33,12 +32,16 @@ class Http(models.AbstractModel): "name": user.name, "username": user.login, "partner_display_name": user.partner_id.display_name, - "company_id": user.company_id.id if request.session.uid else None, + "company_id": user.company_id.id if request.session.uid else None, # YTI TODO: Remove this from the user context "partner_id": user.partner_id.id if request.session.uid and user.partner_id else None, - "user_companies": {'current_company': (user.company_id.id, user.company_id.name), 'allowed_companies': [(comp.id, comp.name) for comp in user.company_ids]} if display_switch_company_menu else False, + # current_company should be default_company + "user_companies": {'current_company': (user.company_id.id, user.company_id.name), 'allowed_companies': [(comp.id, comp.name) for comp in user.company_ids]}, "currencies": self.get_currencies() if request.session.uid else {}, "web.base.url": self.env['ir.config_parameter'].sudo().get_param('web.base.url', default=''), - "show_effect": True + "show_effect": True, + "display_switch_company_menu": user.has_group('base.group_multi_company') and len(user.company_ids) > 1, + "toggle_company": user.has_group('base.group_toggle_company'), + } def get_currencies(self): 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; }); diff --git a/addons/web/static/src/scss/switch_company_menu.scss b/addons/web/static/src/scss/switch_company_menu.scss new file mode 100644 index 00000000000..cae7c3d6522 --- /dev/null +++ b/addons/web/static/src/scss/switch_company_menu.scss @@ -0,0 +1,24 @@ + +.o_main_navbar { + .o_switch_company_menu { + .dropdown-item { + cursor: pointer; + + &:hover { + background-color: white; + } + + .toggle_company { + &:hover { + background-color: #e9ecef; + } + } + + .log_into { + &:hover { + background-color: #e9ecef; + } + } + } + } +} diff --git a/addons/web/static/src/xml/base.xml b/addons/web/static/src/xml/base.xml index 84af548222b..bb8e5e1c81a 100644 --- a/addons/web/static/src/xml/base.xml +++ b/addons/web/static/src/xml/base.xml @@ -1559,9 +1559,43 @@ <t t-name="SwitchCompanyMenu"> <li class="o_switch_company_menu"> <a role="button" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false" href="#" aria-label="Dropdown menu" title="Dropdown menu"> - <span t-attf-class="#{widget.isMobile ? 'fa fa-building-o' : 'oe_topbar_name'}"/> + <span t-attf-class="#{widget.isMobile ? 'fa fa-building-o' : 'oe_topbar_name'}"> + <t t-if="!widget.isMobile"><t t-raw="widget.current_company_name"/></t> + </span> </a> - <div class="dropdown-menu dropdown-menu-right" role="menu"/> + <div class="dropdown-menu dropdown-menu-right" role="menu"> + <t t-if="widget.isMobile"> + <li class="bg-info">Tap on the list to change company</li> + </t> + <t t-foreach="widget.user_companies" t-as="company"> + <span role="menuitem" href="#" class="dropdown-item d-flex align-items-center py-0 px-0" data-menu="company" t-att-data-company-id="company[0]"> + <div class="d-flex flex-grow-1 align-items-center py-0 log_into pl-3" t-att-style="company[0] === widget.current_company ? 'background-color: lightgrey;' : ''"> + <t t-if="widget.allowed_company_ids.includes(company[0].toString())"> + <span class='mr-3 company_label'> + <t t-esc="company[1]"/> + </span> + </t> + <t t-if="!widget.allowed_company_ids.includes(company[0].toString())"> + <span class='mr-3 company_label text-muted'> + <t t-esc="company[1]"/> + </span> + </t> + </div> + <t t-if="widget.toggle_company"> + <div class="ml-auto pl-3 pr-3 border border-top-0 border-right-0 border-bottom-0 toggle_company"> + <span style="height: 2rem;"> + <t t-if="widget.allowed_company_ids.includes(company[0].toString())"> + <i class="fa fa-fw fa-check-square pt-2"></i> + </t> + <t t-if="!widget.allowed_company_ids.includes(company[0].toString())"> + <i class="fa fa-fw fa-square-o pt-2"></i> + </t> + </span> + </div> + </t> + </span> + </t> + </div> </li> </t> diff --git a/addons/web/static/tests/views/basic_model_tests.js b/addons/web/static/tests/views/basic_model_tests.js index d840210d4ff..8bc9a01465e 100644 --- a/addons/web/static/tests/views/basic_model_tests.js +++ b/addons/web/static/tests/views/basic_model_tests.js @@ -1929,6 +1929,7 @@ odoo.define('web.basic_model_tests', function (require) { active_model: "partner", bar: 1, category: [12], + current_company_id: false, current_date: moment().format('YYYY-MM-DD'), date: "2017-01-25", display_name: "first partner", diff --git a/addons/web/views/webclient_templates.xml b/addons/web/views/webclient_templates.xml index 4447be53227..3bb49fb237e 100644 --- a/addons/web/views/webclient_templates.xml +++ b/addons/web/views/webclient_templates.xml @@ -168,6 +168,7 @@ <link rel="stylesheet" type="text/scss" href="/web/static/src/scss/dropdown.scss"/> <link rel="stylesheet" type="text/scss" href="/web/static/src/scss/dropdown_extra.scss"/> <link rel="stylesheet" type="text/scss" href="/web/static/src/scss/tooltip.scss"/> + <link rel="stylesheet" type="text/scss" href="/web/static/src/scss/switch_company_menu.scss"/> <link rel="stylesheet" type="text/scss" href="/web/static/src/scss/debug_manager.scss"/> <link rel="stylesheet" type="text/scss" href="/web/static/src/scss/control_panel.scss"/> <link rel="stylesheet" type="text/scss" href="/web/static/src/scss/fields.scss"/> diff --git a/addons/web_settings_dashboard/controllers/main.py b/addons/web_settings_dashboard/controllers/main.py index d2a23fc7c65..e25a65d42b0 100644 --- a/addons/web_settings_dashboard/controllers/main.py +++ b/addons/web_settings_dashboard/controllers/main.py @@ -77,7 +77,7 @@ class WebSettingsDashboard(http.Controller): 'demo_active': demo_active, }, 'company': { - 'company_id': request.env.user.company_id.id, - 'company_name': request.env.user.company_id.name + 'company_id': request.env.company_id.id, + 'company_name': request.env.company_id.name } } diff --git a/addons/website/controllers/backend.py b/addons/website/controllers/backend.py index b558620a0f5..65286d4c2d4 100644 --- a/addons/website/controllers/backend.py +++ b/addons/website/controllers/backend.py @@ -18,7 +18,7 @@ class WebsiteBackend(http.Controller): 'system': has_group_system, 'website_designer': has_group_designer }, - 'currency': request.env.user.company_id.currency_id.id, + 'currency': request.env.company_id.currency_id.id, 'dashboards': { 'visits': {}, } diff --git a/addons/website/models/ir_http.py b/addons/website/models/ir_http.py index b91e9435782..50dc84a07c8 100644 --- a/addons/website/models/ir_http.py +++ b/addons/website/models/ir_http.py @@ -107,6 +107,9 @@ class Http(models.AbstractModel): request.website = request.env['website'].get_current_website() # can use `request.env` since auth methods are called context['website_id'] = request.website.id + # This is mainly to avoid access errors in website controllers where there is no + # context (eg: /shop), and it's not going to propagate to the global context of the tab + context['allowed_company_ids'] = [request.website.company_id.id] # modify bound context request.context = dict(request.context, **context) diff --git a/addons/website/models/ir_ui_view.py b/addons/website/models/ir_ui_view.py index a396b676940..f7406cf562d 100644 --- a/addons/website/models/ir_ui_view.py +++ b/addons/website/models/ir_ui_view.py @@ -339,7 +339,7 @@ class View(models.Model): for website in Website.search([]) if website != cur ] - cur_company = self.env.user.company_id + cur_company = self.env.company_id qcontext['multi_website_companies_current'] = {'company_id': cur_company.id, 'name': cur_company.name} qcontext['multi_website_companies'] = [ {'company_id': comp.id, 'name': comp.name} diff --git a/addons/website/models/res_config_settings.py b/addons/website/models/res_config_settings.py index 875e9d1ff0c..e9b6ab5cc8f 100644 --- a/addons/website/models/res_config_settings.py +++ b/addons/website/models/res_config_settings.py @@ -10,7 +10,7 @@ class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' def _default_website(self): - return self.env['website'].search([('company_id', '=', self.env.user.company_id.id)], limit=1) + return self.env['website'].search([('company_id', '=', self.env.company_id.id)], limit=1) website_id = fields.Many2one('website', string="website", default=_default_website, ondelete='cascade') @@ -18,7 +18,8 @@ class ResConfigSettings(models.TransientModel): website_domain = fields.Char('Website Domain', related='website_id.domain', readonly=False) website_country_group_ids = fields.Many2many(related='website_id.country_group_ids', readonly=False) website_company_id = fields.Many2one(related='website_id.company_id', string='Website Company', readonly=False) - language_ids = fields.Many2many(related='website_id.language_ids', relation='res.lang', readonly=False, required=True) + language_ids = fields.Many2many(related='website_id.language_ids', relation='res.lang', + readonly=False) language_count = fields.Integer(string='Number of languages', compute='_compute_language_count', readonly=True) website_default_lang_id = fields.Many2one( string='Default language', related='website_id.default_lang_id', readonly=False, diff --git a/addons/website/static/src/js/content/website_root.js b/addons/website/static/src/js/content/website_root.js index 9f16c94b38b..22c71890643 100644 --- a/addons/website/static/src/js/content/website_root.js +++ b/addons/website/static/src/js/content/website_root.js @@ -15,7 +15,6 @@ var WebsiteRoot = publicRootData.PublicRoot.extend({ 'click .js_change_lang': '_onLangChangeClick', 'click .js_publish_management .js_publish_btn': '_onPublishBtnClick', 'click .js_multi_website_switch': '_onWebsiteSwitch', - 'click .js_multi_company_switch': '_onCompanySwitch', 'shown.bs.modal': '_onModalShown', }), custom_events: _.extend({}, publicRootData.PublicRoot.prototype.custom_events || {}, { @@ -171,19 +170,6 @@ var WebsiteRoot = publicRootData.PublicRoot.extend({ * @private * @param {Event} ev */ - _onCompanySwitch: function (ev) { - var companyID = parseInt(ev.currentTarget.getAttribute('company-id'), 10); - this._rpc({model: 'res.users', - method: 'write', - args: [odoo.session_info.user_id, {'company_id': companyID}], - }).then(function () { - window.location.reload(true); - }); - }, - /** - * @private - * @param {Event} ev - */ _onModalShown: function (ev) { $(ev.target).addClass('modal_shown'); }, diff --git a/addons/website/static/src/js/tours/rte.js b/addons/website/static/src/js/tours/rte.js index eacc2b89e67..e29f40e45ed 100644 --- a/addons/website/static/src/js/tours/rte.js +++ b/addons/website/static/src/js/tours/rte.js @@ -14,6 +14,7 @@ var ready = Promise.all([domReady, session.is_bound, ajax.loadXML()]); tour.register('rte_translator', { test: true, wait_for: ready, + url: '/', }, [{ content: "click on Add a language", trigger: '.js_language_selector a:has(i.fa)', diff --git a/addons/website/views/res_config_settings_views.xml b/addons/website/views/res_config_settings_views.xml index dbf552b4ad2..f2a8d0b3e02 100644 --- a/addons/website/views/res_config_settings_views.xml +++ b/addons/website/views/res_config_settings_views.xml @@ -69,7 +69,8 @@ </div> <div class="content-group"> <div class="mt16"> - <field name="language_ids" widget="many2many_tags" options="{'no_create': True, 'no_open': True}"/> + <field name="language_ids" widget="many2many_tags" options="{'no_create': True, 'no_open': True}" + attrs="{'required': [('website_id', '!=', False)]}"/> </div> <field name="language_count" invisible="1"/> <div class="mt8" attrs="{'invisible':[('language_count', '<', 2)]}"> diff --git a/addons/website/views/website_navbar_templates.xml b/addons/website/views/website_navbar_templates.xml index d5db7ab3a22..fc05b72b794 100644 --- a/addons/website/views/website_navbar_templates.xml +++ b/addons/website/views/website_navbar_templates.xml @@ -76,27 +76,6 @@ <li class="o_mobile_preview" id="mobile-menu"> <a data-action="show-mobile-preview" href="#"><span title="Mobile preview" role="img" aria-label="Mobile preview" class="fa fa-mobile"/></a> </li> - <li t-if="user_id.has_group('base.group_multi_company') and user_id.has_group('website.group_multi_website') and len(multi_website_companies)"> - <a class="dropdown-toggle" data-toggle="dropdown" href="#"> - <i class="fa fa-building d-lg-none"/> - <span class="d-none d-lg-inline-block"> - <t t-esc="multi_website_companies_current['name']"/> - </span> - </a> - <div class="dropdown-menu" role="menu"> - <div class="d-lg-none dropdown-item active"> - <span t-esc="multi_website_companies_current['name']"/> - </div> - <t t-foreach="multi_website_companies" t-as="multi_website_company"> - <a role="menuitem" href="#" - class="dropdown-item oe_menu_text js_multi_company_switch" - t-att-company-id="str(multi_website_company['company_id'])" - > - <span t-esc="multi_website_company['name']" /> - </a> - </t> - </div> - </li> <li groups="website.group_multi_website" t-if="multi_website_websites"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="fa fa-globe d-lg-none"/> diff --git a/addons/website_gengo/controllers/main.py b/addons/website_gengo/controllers/main.py index d3e274a2430..506ccf025f1 100644 --- a/addons/website_gengo/controllers/main.py +++ b/addons/website_gengo/controllers/main.py @@ -27,7 +27,7 @@ class WebsiteGengo(http.Controller): @http.route('/website/set_gengo_config', type='json', auth='user', website=True) def set_gengo_config(self, config): - request.env.user.company_id.write(config) + request.env.company_id.write(config) return True @http.route('/website/post_gengo_jobs', type='json', auth='user', website=True) diff --git a/addons/website_sale/controllers/main.py b/addons/website_sale/controllers/main.py index dd088419362..1489d1f5906 100644 --- a/addons/website_sale/controllers/main.py +++ b/addons/website_sale/controllers/main.py @@ -389,7 +389,7 @@ class WebsiteSale(http.Controller): from_currency = order.company_id.currency_id to_currency = order.pricelist_id.currency_id compute_currency = lambda price: from_currency._convert( - price, to_currency, request.env.user.company_id, fields.Date.today()) + price, to_currency, request.env.company_id, fields.Date.today()) else: compute_currency = lambda price: price diff --git a/addons/website_sale/models/product.py b/addons/website_sale/models/product.py index 5d8bb08465c..d96477a4e83 100644 --- a/addons/website_sale/models/product.py +++ b/addons/website_sale/models/product.py @@ -21,7 +21,7 @@ class ProductPricelist(models.Model): def _default_website(self): """ Find the first company's website, if there is one. """ - company_id = self.env.user.company_id.id + company_id = self.env.company_id.id if self._context.get('default_company_id'): company_id = self._context.get('default_company_id') diff --git a/addons/website_sale/models/res_company.py b/addons/website_sale/models/res_company.py index aeaa4ffcbcf..f8d571e78c1 100644 --- a/addons/website_sale/models/res_company.py +++ b/addons/website_sale/models/res_company.py @@ -12,6 +12,6 @@ class ResCompany(models.Model): @api.model def action_open_website_sale_onboarding_payment_acquirer(self): """ Called by onboarding panel above the quotation list.""" - self.env.user.company_id.get_chart_of_accounts_or_fail() + self.env.company_id.get_chart_of_accounts_or_fail() action = self.env.ref('website_sale.action_open_website_sale_onboarding_payment_acquirer_wizard').read()[0] return action diff --git a/addons/website_sale/wizard/payment_acquirer_onboarding_wizard.py b/addons/website_sale/wizard/payment_acquirer_onboarding_wizard.py index 18531d1c337..2d5a0de5154 100644 --- a/addons/website_sale/wizard/payment_acquirer_onboarding_wizard.py +++ b/addons/website_sale/wizard/payment_acquirer_onboarding_wizard.py @@ -10,4 +10,4 @@ class PaymentWizard(models.TransientModel): def _set_payment_acquirer_onboarding_step_done(self): """ Override. """ - self.env.user.company_id.set_onboarding_step_done('website_sale_onboarding_payment_acquirer_state') + self.env.company_id.set_onboarding_step_done('website_sale_onboarding_payment_acquirer_state') diff --git a/addons/website_slides/wizard/slide_channel_invite.py b/addons/website_slides/wizard/slide_channel_invite.py index 094e82f57b4..99cdf3ae55a 100644 --- a/addons/website_slides/wizard/slide_channel_invite.py +++ b/addons/website_slides/wizard/slide_channel_invite.py @@ -123,7 +123,7 @@ class SlideChannelInvite(models.TransientModel): template_ctx = { 'message': self.env['mail.message'].sudo().new(dict(body=mail_values['body_html'], record_name=self.channel_id.name)), 'model_description': self.env['ir.model']._get('website_slides.slide_channel').display_name, - 'company': self.env.user.company_id, + 'company': self.env.company_id, } body = template.render(template_ctx, engine='ir.qweb', minimal_qcontext=True) mail_values['body_html'] = self.env['mail.thread']._replace_local_links(body) diff --git a/odoo/addons/base/__manifest__.py b/odoo/addons/base/__manifest__.py index d47214a5ce9..f32d529a487 100644 --- a/odoo/addons/base/__manifest__.py +++ b/odoo/addons/base/__manifest__.py @@ -80,6 +80,7 @@ The kernel of Odoo, needed for all installation. 'data/res_bank_demo.xml', 'data/res_partner_demo.xml', 'data/res_partner_image_demo.xml', + 'data/res_groups_demo.xml', ], 'test': [], 'installable': True, diff --git a/odoo/addons/base/data/ir_module_category_data.xml b/odoo/addons/base/data/ir_module_category_data.xml index d99fed12077..7b06f7437d6 100644 --- a/odoo/addons/base/data/ir_module_category_data.xml +++ b/odoo/addons/base/data/ir_module_category_data.xml @@ -110,5 +110,9 @@ <field name="category_id" ref="module_category_usability"/> </record> + <record id="group_toggle_company" model="res.groups"> + <field name="category_id" ref="module_category_hidden"/> + </record> + </data> </odoo> diff --git a/odoo/addons/base/data/res_company_data.xml b/odoo/addons/base/data/res_company_data.xml index 3759ae13143..50c19767c40 100644 --- a/odoo/addons/base/data/res_company_data.xml +++ b/odoo/addons/base/data/res_company_data.xml @@ -5,6 +5,7 @@ <field name="name">My Company</field> <field name="partner_id" ref="main_partner"/> <field name="currency_id" ref="base.EUR"/> + <field name="favicon" model="res.company" eval="obj()._get_default_favicon(original=True)"/> </record> <record id="main_partner" model="res.partner"> diff --git a/odoo/addons/base/data/res_groups_demo.xml b/odoo/addons/base/data/res_groups_demo.xml new file mode 100644 index 00000000000..66d728ff776 --- /dev/null +++ b/odoo/addons/base/data/res_groups_demo.xml @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="utf-8"?> +<odoo> + <data noupdate="1"> + <record id="group_toggle_company" model="res.groups"> + <field name="users" eval="[(4, ref('base.user_root')), (4, ref('base.user_admin'))]"/> + </record> + </data> +</odoo> diff --git a/odoo/addons/base/models/ir_actions_report.py b/odoo/addons/base/models/ir_actions_report.py index 515387f672d..27fa49da4f9 100644 --- a/odoo/addons/base/models/ir_actions_report.py +++ b/odoo/addons/base/models/ir_actions_report.py @@ -202,7 +202,7 @@ class IrActionsReport(models.Model): @api.model def get_paperformat(self): - return self.paperformat_id or self.env.user.company_id.paperformat_id + return self.paperformat_id or self.env.company_id.paperformat_id @api.model def _build_wkhtmltopdf_args( @@ -760,7 +760,7 @@ class IrActionsReport(models.Model): :param report_name: Name of the template to generate an action for """ discard_logo_check = self.env.context.get('discard_logo_check') - if (self.env.user._is_admin()) and ((not self.env.user.company_id.external_report_layout_id) or (not discard_logo_check and not self.env.user.company_id.logo)) and config: + if (self.env.user._is_admin()) and ((not self.env.company_id.external_report_layout_id) or (not discard_logo_check and not self.env.company_id.logo)) and config: template = self.env.ref('base.view_company_report_form_with_print') if self.env.context.get('from_transient_model', False) else self.env.ref('base.view_company_report_form') return { 'name': _('Choose Your Document Layout'), @@ -768,7 +768,7 @@ class IrActionsReport(models.Model): 'context': {'default_report_name': self.report_name, 'discard_logo_check': True}, 'view_type': 'form', 'view_mode': 'form', - 'res_id': self.env.user.company_id.id, + 'res_id': self.env.company_id.id, 'res_model': 'res.company', 'views': [(template.id, 'form')], 'view_id': template.id, diff --git a/odoo/addons/base/models/ir_attachment.py b/odoo/addons/base/models/ir_attachment.py index b0944e5ebd4..03b29aaacec 100644 --- a/odoo/addons/base/models/ir_attachment.py +++ b/odoo/addons/base/models/ir_attachment.py @@ -282,7 +282,7 @@ class IrAttachment(models.Model): res_field = fields.Char('Resource Field', readonly=True) res_id = fields.Integer('Resource ID', readonly=True, help="The record id this is attached to.") company_id = fields.Many2one('res.company', string='Company', change_default=True, - default=lambda self: self.env['res.company']._company_default_get('ir.attachment')) + default=lambda self: self.env.company_id) type = fields.Selection([('url', 'URL'), ('binary', 'File')], string='Type', required=True, default='binary', change_default=True, help="You can either upload a file from your computer or copy/paste an internet link to your file.") diff --git a/odoo/addons/base/models/ir_default.py b/odoo/addons/base/models/ir_default.py index 38ab488b94e..282e12d211e 100644 --- a/odoo/addons/base/models/ir_default.py +++ b/odoo/addons/base/models/ir_default.py @@ -57,7 +57,7 @@ class IrDefault(models.Model): if user_id is True: user_id = self.env.uid if company_id is True: - company_id = self.env.user.company_id.id + company_id = self.env.company_id.id # check consistency of model_name, field_name, and value try: @@ -107,7 +107,7 @@ class IrDefault(models.Model): if user_id is True: user_id = self.env.uid if company_id is True: - company_id = self.env.user.company_id.id + company_id = self.env.company_id.id field = self.env['ir.model.fields']._get(model_name, field_name) default = self.search([ diff --git a/odoo/addons/base/models/ir_module.py b/odoo/addons/base/models/ir_module.py index e2870d74b3c..1afe44bb05c 100644 --- a/odoo/addons/base/models/ir_module.py +++ b/odoo/addons/base/models/ir_module.py @@ -439,6 +439,13 @@ class Module(models.Model): :rtype: dict[str, object] """ _logger.info('User #%d triggered module installation', self.env.uid) + # We use here the request object (which is thread-local) as a kind of + # "global" env because the env is not usable in the following use case. + # When installing a Chart of Account, I would like to send the + # allowed companies to configure it on the correct company. + # Otherwise, the SUPERUSER won't be aware of that and will try to + # configure the CoA on his own company, which makes no sense. + request.allowed_company_ids = self.env.company_ids.ids return self._button_immediate_function(type(self).button_install) @assert_log_admin_access diff --git a/odoo/addons/base/models/ir_property.py b/odoo/addons/base/models/ir_property.py index 0690080670f..c605d027b1a 100644 --- a/odoo/addons/base/models/ir_property.py +++ b/odoo/addons/base/models/ir_property.py @@ -178,10 +178,8 @@ class Property(models.Model): return False # only cache Property.get(res_id=False) as that's - # sub-optimally, we can only call _company_default_get without a field - # unless we want to create a more complete helper which does the - # returning-a-company-id-from-a-model-and-name - COMPANY_KEY = "self.env.context.get('force_company') or self.env['res.company']._company_default_get(model).id" + # sub-optimally. + COMPANY_KEY = "self.env.context.get('force_company') or self.env.company_id.id" @ormcache(COMPANY_KEY, 'name', 'model') def _get_default_property(self, name, model): prop = self._get_property(name, model, res_id=False) @@ -205,7 +203,7 @@ class Property(models.Model): res = self._cr.fetchone() if not res: return None - company_id = self._context.get('force_company') or self.env['res.company']._company_default_get(model, res[0]).id + company_id = self._context.get('force_company') or self.env.company_id.id return [('fields_id', '=', res[0]), ('company_id', 'in', [company_id, False])] @api.model @@ -221,7 +219,7 @@ class Property(models.Model): field_id = self.env['ir.model.fields']._get(model, name).id company_id = ( self._context.get('force_company') - or self.env['res.company']._company_default_get(model, field_id).id + or self.env.company_id.id ) if field.type == 'many2one': @@ -301,7 +299,7 @@ class Property(models.Model): # retrieve the properties corresponding to the given record ids self._cr.execute("SELECT id FROM ir_model_fields WHERE name=%s AND model=%s", (name, model)) field_id = self._cr.fetchone()[0] - company_id = self.env.context.get('force_company') or self.env['res.company']._company_default_get(model, field_id).id + company_id = self.env.context.get('force_company') or self.env.company_id.id refs = {('%s,%s' % (model, id)): id for id in values} props = self.search([ ('fields_id', '=', field_id), diff --git a/odoo/addons/base/models/ir_qweb_fields.py b/odoo/addons/base/models/ir_qweb_fields.py index c71427b7647..8209ebc81ce 100644 --- a/odoo/addons/base/models/ir_qweb_fields.py +++ b/odoo/addons/base/models/ir_qweb_fields.py @@ -420,7 +420,7 @@ class MonetaryConverter(models.AbstractModel): if company_id: company = self.env['res.company'].browse(company_id) else: - company = self.env.user.company_id + company = self.env.company_id value = options['from_currency']._convert(value, display_currency, company, date) lang = self.user_lang() diff --git a/odoo/addons/base/models/ir_rule.py b/odoo/addons/base/models/ir_rule.py index 092641e7f0d..a832795e5a9 100644 --- a/odoo/addons/base/models/ir_rule.py +++ b/odoo/addons/base/models/ir_rule.py @@ -43,8 +43,16 @@ class IrRule(models.Model): @api.model def _eval_context(self): """Returns a dictionary to use as evaluation context for - ir.rule domains.""" - return {'user': self.env.user, 'time': time} + ir.rule domains. + Note: company_ids contains the ids of the activated companies + by the user with the switch company menu. These companies are + filtered and trusted. + """ + return { + 'user': self.env.user, + 'time': time, + 'company_ids': self.env.company_ids.ids, + } @api.depends('groups') def _compute_global(self): @@ -64,7 +72,7 @@ class IrRule(models.Model): def _compute_domain_keys(self): """ Return the list of context keys to use for caching ``_compute_domain``. """ - return [] + return ['allowed_company_ids'] def _get_failing(self, for_records, mode='read'): """ Returns the rules for the mode for the current user which fail on @@ -196,22 +204,26 @@ class IrRule(models.Model): 'document_kind': description, 'document_model': model, 'operation': operation, - }) + }) - # debug mode, provide more info + # This extended AccessError is only displayed in debug mode. + # Note that by default, public and portal users do not have + # the group "base.group_no_one", even if debug mode is enabled, + # so it is relatively safe here to include the list of rules and + # record names. rules = self._get_failing(records, mode=operation).sudo() return AccessError(_("""The requested operation ("%(operation)s" on "%(document_kind)s" (%(document_model)s)) was rejected because of the following rules: %(rules_list)s %(multi_company_warning)s -(records: %(example_records)s, uid: %(user_id)d)""") % { +(Records: %(example_records)s, User: %(user_id)s)""") % { 'operation': operation, 'document_kind': description, 'document_model': model, 'rules_list': '\n'.join('- %s' % rule.name for rule in rules), 'multi_company_warning': ('\n' + _('Note: this might be a multi-company issue.') + '\n') if any( 'company_id' in r.domain_force for r in rules) else '', - 'example_records': list(records.ids[:6]), - 'user_id': self.env.user.id, + 'example_records': ' - '.join(['%s (id=%s)' % (rec.display_name, rec.id) for rec in records[:6].sudo()]), + 'user_id': '%s (id=%s)' % (self.env.user.name, self.env.user.id), }) # diff --git a/odoo/addons/base/models/ir_sequence.py b/odoo/addons/base/models/ir_sequence.py index 7e97e2fa05c..e08729fe62a 100644 --- a/odoo/addons/base/models/ir_sequence.py +++ b/odoo/addons/base/models/ir_sequence.py @@ -136,7 +136,7 @@ class IrSequence(models.Model): help="Odoo will automatically adds some '0' on the left of the " "'Next Number' to get the required padding size.") company_id = fields.Many2one('res.company', string='Company', - default=lambda s: s.env['res.company']._company_default_get('ir.sequence')) + default=lambda s: s.env.company_id) use_date_range = fields.Boolean(string='Use subsequences per date_range') date_range_ids = fields.One2many('ir.sequence.date_range', 'sequence_id', string='Subsequences') @@ -277,7 +277,7 @@ class IrSequence(models.Model): self.check_access_rights('read') force_company = self._context.get('force_company') if not force_company: - force_company = self.env.user.company_id.id + force_company = self.env.company_id.id seq_ids = self.search([('code', '=', sequence_code), ('company_id', 'in', [force_company, False])], order='company_id') if not seq_ids: _logger.debug("No ir.sequence has been found for code '%s'. Please make sure a sequence is set for current company." % sequence_code) diff --git a/odoo/addons/base/models/ir_ui_view.py b/odoo/addons/base/models/ir_ui_view.py index ddae4f21642..e60af844439 100644 --- a/odoo/addons/base/models/ir_ui_view.py +++ b/odoo/addons/base/models/ir_ui_view.py @@ -1016,6 +1016,8 @@ actual arch. 'context_today', 'active_id', 'active_ids', + 'allowed_company_ids', + 'current_company_id', 'active_model', 'time', 'datetime', @@ -1351,7 +1353,7 @@ actual arch. qcontext = dict( env=self.env, user_id=self.env["res.users"].browse(self.env.user.id), - res_company=self.env.user.company_id.sudo(), + res_company=self.env.company_id.sudo(), keep_query=keep_query, request=request, # might be unbound if we're not in an httprequest context debug=request.debug if request else False, diff --git a/odoo/addons/base/models/res_bank.py b/odoo/addons/base/models/res_bank.py index d9a0433ecc2..414d2aed444 100644 --- a/odoo/addons/base/models/res_bank.py +++ b/odoo/addons/base/models/res_bank.py @@ -86,7 +86,7 @@ class ResPartnerBank(models.Model): bank_bic = fields.Char(related='bank_id.bic', readonly=False) sequence = fields.Integer(default=10) currency_id = fields.Many2one('res.currency', string='Currency') - company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env.user.company_id, ondelete='cascade') + company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env.company_id, ondelete='cascade') qr_code_valid = fields.Boolean(string="Has all required arguments", compute="_validate_qr_code_arguments") _sql_constraints = [ diff --git a/odoo/addons/base/models/res_company.py b/odoo/addons/base/models/res_company.py index db64a8265a3..9dfbf9bdced 100644 --- a/odoo/addons/base/models/res_company.py +++ b/odoo/addons/base/models/res_company.py @@ -1,11 +1,20 @@ # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. + import base64 +import io +import logging import os import re from odoo import api, fields, models, tools, _ from odoo.exceptions import ValidationError, UserError +from odoo.modules.module import get_resource_path + +from random import randrange +from PIL import Image + +_logger = logging.getLogger(__name__) class Company(models.Model): @@ -29,6 +38,29 @@ class Company(models.Model): currency_id = self.env['res.users'].browse(self._uid).company_id.currency_id return currency_id or self._get_euro() + def _get_default_favicon(self, original=False): + img_path = get_resource_path('web', 'static/src/img/favicon.ico') + with tools.file_open(img_path, 'rb') as f: + if original: + return base64.b64encode(f.read()) + # Modify the source image to change the color of the 'O'. + # This could seem overkill to modify the pixels 1 by 1, but + # Pillow doesn't provide an easy way to do it, and this + # is acceptable for a 16x16 image. + color = (randrange(32, 224, 24), randrange(32, 224, 24), randrange(32, 224, 24)) + original = Image.open(f) + new_image = Image.new('RGBA', original.size) + for y in range(original.size[1]): + for x in range(original.size[0]): + pixel = original.getpixel((x, y)) + if pixel[0] == 0 and pixel[1] == 0 and pixel[2] == 0: + new_image.putpixel((x, y), (0, 0, 0, 0)) + else: + new_image.putpixel((x, y), (color[0], color[1], color[2], pixel[3])) + stream = io.BytesIO() + new_image.save(stream, format="ICO") + return base64.b64encode(stream.getvalue()) + name = fields.Char(related='partner_id.name', string='Company Name', required=True, store=True, readonly=False) sequence = fields.Integer(help='Used to order Companies in the company switcher', default=10) parent_id = fields.Many2one('res.company', string='Parent Company', index=True) @@ -57,12 +89,15 @@ class Company(models.Model): company_registry = fields.Char() paperformat_id = fields.Many2one('report.paperformat', 'Paper format', default=lambda self: self.env.ref('base.paperformat_euro', raise_if_not_found=False)) external_report_layout_id = fields.Many2one('ir.ui.view', 'Document Template') + base_onboarding_company_state = fields.Selection([ + ('not_done', "Not done"), ('just_done', "Just done"), ('done', "Done")], string="State of the onboarding company step", default='not_done') + favicon = fields.Binary(string="Company Favicon", help="This field holds the image used to display a favicon for a given company.", default=_get_default_favicon) + + _sql_constraints = [ ('name_uniq', 'unique (name)', 'The company name must be unique !') ] - base_onboarding_company_state = fields.Selection([ - ('not_done', "Not done"), ('just_done', "Just done"), ('done', "Done")], string="State of the onboarding company step", default='not_done') @api.model_cr def init(self): @@ -154,7 +189,7 @@ class Company(models.Model): # select only the currently visible companies (according to rules, # which are probably to allow to see the child companies) even if # she belongs to some other companies. - companies = self.env.user.company_id + self.env.user.company_ids + companies = self.env.user.company_ids args = (args or []) + [('id', 'in', companies.ids)] newself = newself.sudo() return super(Company, newself.with_context(context))._name_search(name=name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid) @@ -162,36 +197,11 @@ class Company(models.Model): @api.model @api.returns('self', lambda value: value.id) def _company_default_get(self, object=False, field=False): - """ Returns the default company (usually the user's company). - The 'object' and 'field' arguments are ignored but left here for - backward compatibility and potential override. + """ Returns the user's company + - Deprecated """ - return self.env['res.users']._get_company() - - @api.model - @tools.ormcache('self.env.uid', 'company') - def _get_company_children(self, company=None): - if not company: - return [] - return self.search([('parent_id', 'child_of', [company])]).ids - - @api.multi - def _get_partner_hierarchy(self): - self.ensure_one() - parent = self.parent_id - if parent: - return parent._get_partner_hierarchy() - else: - return self._get_partner_descendance([]) - - @api.multi - def _get_partner_descendance(self, descendance): - self.ensure_one() - descendance.append(self.partner_id.id) - for child_id in self._get_company_children(self.id): - if child_id != self.id: - descendance = self.browse(child_id)._get_partner_descendance(descendance) - return descendance + _logger.warning(_("The method '_company_default_get' on res.company is deprecated and shouldn't be used anymore")) + return self.env.company_id # deprecated, use clear_caches() instead def cache_restart(self): @@ -199,6 +209,8 @@ class Company(models.Model): @api.model def create(self, vals): + if not vals.get('favicon'): + vals['favicon'] = self._get_default_favicon() if not vals.get('name') or vals.get('partner_id'): self.clear_caches() return super(Company, self).create(vals) @@ -266,7 +278,7 @@ class Company(models.Model): def action_open_base_onboarding_company(self): """ Onboarding step for company basic information. """ action = self.env.ref('base.action_open_base_onboarding_company').read()[0] - action['res_id'] = self.env.user.company_id.id + action['res_id'] = self.env.company_id.id return action def set_onboarding_step_done(self, step_name): diff --git a/odoo/addons/base/models/res_currency.py b/odoo/addons/base/models/res_currency.py index 09a6d019f38..a7ecad0a1ca 100644 --- a/odoo/addons/base/models/res_currency.py +++ b/odoo/addons/base/models/res_currency.py @@ -62,7 +62,7 @@ class Currency(models.Model): @api.depends('rate_ids.rate') def _compute_current_rate(self): date = self._context.get('date') or fields.Date.today() - company = self.env['res.company'].browse(self._context.get('company_id')) or self.env['res.users']._get_company() + company = self.env['res.company'].browse(self._context.get('company_id')) or self.env.company_id # the subquery selects the last rate before 'date' for the given currency/company currency_rates = self._get_rates(company, date) for currency in self: @@ -209,14 +209,14 @@ class Currency(models.Model): def _compute(self, from_currency, to_currency, from_amount, round=True): _logger.warning('The `_compute` method is deprecated. Use `_convert` instead') date = self._context.get('date') or fields.Date.today() - company = self.env['res.company'].browse(self._context.get('company_id')) or self.env['res.users']._get_company() + company = self.env['res.company'].browse(self._context.get('company_id')) or self.env.company_id return from_currency._convert(from_amount, to_currency, company, date) @api.multi def compute(self, from_amount, to_currency, round=True): _logger.warning('The `compute` method is deprecated. Use `_convert` instead') date = self._context.get('date') or fields.Date.today() - company = self.env['res.company'].browse(self._context.get('company_id')) or self.env['res.users']._get_company() + company = self.env['res.company'].browse(self._context.get('company_id')) or self.env.company_id return self._convert(from_amount, to_currency, company, date) def _select_companies_rates(self): @@ -247,7 +247,7 @@ class CurrencyRate(models.Model): rate = fields.Float(digits=(12, 6), default=1.0, help='The rate of the currency to the currency of rate 1') currency_id = fields.Many2one('res.currency', string='Currency', readonly=True) company_id = fields.Many2one('res.company', string='Company', - default=lambda self: self.env.user.company_id) + default=lambda self: self.env.company_id) _sql_constraints = [ ('unique_name_per_day', 'unique (name,currency_id,company_id)', 'Only one currency rate per day allowed!'), diff --git a/odoo/addons/base/models/res_lang.py b/odoo/addons/base/models/res_lang.py index 534c8cb248c..8d5990efbf6 100644 --- a/odoo/addons/base/models/res_lang.py +++ b/odoo/addons/base/models/res_lang.py @@ -175,7 +175,7 @@ class Lang(models.Model): if default_value is None: IrDefault.set('res.partner', 'lang', lang_code) # set language of main company, created directly by db bootstrap SQL - partner = self.env.user.company_id.partner_id + partner = self.env.company_id.partner_id if not partner.lang: partner.write({'lang': lang_code}) return True diff --git a/odoo/addons/base/models/res_partner.py b/odoo/addons/base/models/res_partner.py index fa23086b16a..2bc8144f128 100644 --- a/odoo/addons/base/models/res_partner.py +++ b/odoo/addons/base/models/res_partner.py @@ -48,7 +48,7 @@ class FormatAddressMixin(models.AbstractModel): def _fields_view_get_address(self, arch): # consider the country of the user, not the country of the partner we want to display - address_view_id = self.env.user.company_id.country_id.address_view_id + address_view_id = self.env.company_id.country_id.address_view_id if address_view_id and not self._context.get('no_address_format'): #render the partner address accordingly to address_view_id doc = etree.fromstring(arch) @@ -139,7 +139,7 @@ class Partner(models.Model): return self.env['res.partner.category'].browse(self._context.get('category_id')) def _default_company(self): - return self.env['res.company']._company_default_get('res.partner') + return self.env.company_id def _split_street_with_params(self, street_raw, street_format): return {'street': street_raw} diff --git a/odoo/addons/base/models/res_users.py b/odoo/addons/base/models/res_users.py index 0cfb40b0ffd..256e89cbb7d 100644 --- a/odoo/addons/base/models/res_users.py +++ b/odoo/addons/base/models/res_users.py @@ -240,17 +240,13 @@ class Users(models.Model): companies_count = fields.Integer(compute='_compute_companies_count', string="Number of Companies", default=_companies_count) tz_offset = fields.Char(compute='_compute_tz_offset', string='Timezone offset', invisible=True) - @api.model - def _get_company(self): - return self.env.user.company_id - # Special behavior for this field: res.company.search() will only return the companies # available to the current user (should be the user's companies?), when the user_preference # context is set. - company_id = fields.Many2one('res.company', string='Company', required=True, default=_get_company, + company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company_id.id, help='The company this user is currently working for.', context={'user_preference': True}) company_ids = fields.Many2many('res.company', 'res_company_users_rel', 'user_id', 'cid', - string='Companies', default=_get_company) + string='Companies', default=lambda self: self.env.company_id.ids) # overridden inherited fields to bypass access rights, in case you have # access to the user but not its corresponding partner @@ -787,7 +783,7 @@ class Users(models.Model): @api.model def get_company_currency_id(self): - return self.env.user.company_id.currency_id.id + return self.env.company_id.currency_id.id def _crypt_context(self): """ Passlib CryptContext instance used to encrypt and verify @@ -982,7 +978,7 @@ class UsersImplied(models.Model): res = super(UsersImplied, self).write(values) if values.get('groups_id'): # add implied groups for all users - for user in self.with_context({}): + for user in self: if not user.has_group('base.group_user'): vals = {'groups_id': [(5, 0, 0)] + values['groups_id']} super(UsersImplied, user).write(vals) diff --git a/odoo/addons/base/security/base_groups.xml b/odoo/addons/base/security/base_groups.xml index 3bdf8ee3928..10541a1a4df 100644 --- a/odoo/addons/base/security/base_groups.xml +++ b/odoo/addons/base/security/base_groups.xml @@ -41,6 +41,10 @@ <field name="users" eval="[(4, ref('base.user_root')), (4, ref('base.user_admin'))]"/> </record> + <record id="group_toggle_company" model="res.groups"> + <field name="name">Allow to toggle company visibility in the company switch bar</field> + </record> + <record model="res.groups" id="group_partner_manager"> <field name="name">Contact Creation</field> <field name="users" eval="[(4, ref('base.user_root')), (4, ref('base.user_admin'))]"/> diff --git a/odoo/addons/base/security/base_security.xml b/odoo/addons/base/security/base_security.xml index 21401d88b47..88872f49407 100644 --- a/odoo/addons/base/security/base_security.xml +++ b/odoo/addons/base/security/base_security.xml @@ -15,12 +15,7 @@ <record model="ir.rule" id="res_partner_rule"> <field name="name">res.partner company</field> <field name="model_id" ref="base.model_res_partner"/> - <!-- - Show partners from ancestors and descendants companies - (or company-less), this is usually a better default for - multicompany setups. - --> - <field name="domain_force">['|','|',('company_id.child_ids','child_of',[user.company_id.id]),('company_id','child_of',[user.company_id.id]),('company_id','=',False)]</field> + <field name="domain_force">['|', ('company_id', 'in', company_ids), ('company_id', '=', False)]</field> <field name="active" eval="False"/> </record> @@ -57,20 +52,17 @@ <field name="domain_force">[('user_id','=',user.id)]</field> </record> - <record id="res_partner_bank_rule" model="ir.rule"> - <field name="name">Partner bank company rule</field> - <field name="model_id" ref="model_res_partner_bank"/> - <field name="global" eval="True"/> - <!-- - Same as res_partner above. - --> - <field name="domain_force">['|','|',('company_id.child_ids','child_of',[user.company_id.id]),('company_id','child_of',[user.company_id.id]),('company_id','=',False)]</field> - </record> + <record id="res_partner_bank_rule" model="ir.rule"> + <field name="name">Partner bank company rule</field> + <field name="model_id" ref="model_res_partner_bank"/> + <field name="global" eval="True"/> + <field name="domain_force">['|', ('company_id', 'in', company_ids), ('company_id', '=', False)]</field> + </record> <record id="res_currency_rate_rule" model="ir.rule"> <field name="name">multi-company currency rate rule</field> <field name="model_id" ref="model_res_currency_rate"/> - <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field> + <field name="domain_force">['|',('company_id','=',False),('company_id', 'in', company_ids)]</field> </record> <!-- Security restriction for private addresses --> @@ -147,21 +139,21 @@ <field name="model_id" ref="model_res_company"/> <field eval="False" name="global"/> <field name="groups" eval="[(6, 0, [ref('base.group_portal')])]"/> - <field name="domain_force">[('id','child_of',[user.company_id.id])]</field> + <field name="domain_force">[('id','in', company_ids)]</field> </record> <record id="res_company_rule_employee" model="ir.rule"> <field name="name">company rule employee</field> <field name="model_id" ref="model_res_company"/> <field eval="False" name="global"/> <field name="groups" eval="[(6, 0, [ref('base.group_user')])]"/> - <field name="domain_force">[('id','child_of',[user.company_id.id])]</field> + <field name="domain_force">[('id','in', company_ids)]</field> </record> <record id="res_company_rule_public" model="ir.rule"> <field name="name">company rule public</field> <field name="model_id" ref="model_res_company"/> <field eval="False" name="global"/> <field name="groups" eval="[(6, 0, [ref('base.group_public')])]"/> - <field name="domain_force">[('id','child_of',[user.company_id.id])]</field> + <field name="domain_force">[('id','in', company_ids)]</field> </record> <record id="res_company_rule_erp_manager" model="ir.rule"> <field name="name">company rule erp manager</field> @@ -176,7 +168,7 @@ <field name="name">user rule</field> <field name="model_id" ref="model_res_users"/> <field eval="True" name="global"/> - <field name="domain_force">[('company_ids','child_of',[user.company_id.id])]</field> + <field name="domain_force">[('company_ids', 'in', company_ids)]</field> </record> </data> </odoo> diff --git a/odoo/addons/base/tests/test_acl.py b/odoo/addons/base/tests/test_acl.py index ee7708f2b67..c16b6753c09 100644 --- a/odoo/addons/base/tests/test_acl.py +++ b/odoo/addons/base/tests/test_acl.py @@ -214,7 +214,7 @@ class TestIrRule(TransactionCase): # modify the global rule on res_company which triggers a recursive check # of the rules on company global_rule = self.env.ref('base.res_company_rule_employee') - global_rule.domain_force = "[('id','child_of',[user.company_id.id])]" + global_rule.domain_force = "[('id','in', company_ids)]" # read as demo user (exercising the global company rule) partners = partners_demo.search([]) diff --git a/odoo/addons/base/tests/test_expression.py b/odoo/addons/base/tests/test_expression.py index b40035dadd6..adae9a6fe01 100644 --- a/odoo/addons/base/tests/test_expression.py +++ b/odoo/addons/base/tests/test_expression.py @@ -574,7 +574,6 @@ class TestExpression(TransactionCase): # To test the 64 characters limit for table aliases in PostgreSQL self.patch_order('res.users', 'partner_id') self.patch_order('res.partner', 'commercial_partner_id,company_id,name') - self.patch_order('res.company', 'parent_id') self.env['res.users'].search([('name', '=', 'test')]) @mute_logger('odoo.sql_db') diff --git a/odoo/addons/base/tests/test_ir_default.py b/odoo/addons/base/tests/test_ir_default.py index be5ce7d7236..d53c0b18914 100644 --- a/odoo/addons/base/tests/test_ir_default.py +++ b/odoo/addons/base/tests/test_ir_default.py @@ -9,7 +9,7 @@ class TestIrDefault(TransactionCase): def test_defaults(self): """ check the mechanism of user-defined defaults """ - companyA = self.env.user.company_id + companyA = self.env.company_id companyB = companyA.create({'name': 'CompanyB'}) user1 = self.env.user user2 = user1.create({'name': 'u2', 'login': 'u2'}) diff --git a/odoo/addons/base/views/ir_rule_views.xml b/odoo/addons/base/views/ir_rule_views.xml index 8fa3ec0c635..e598ab524e4 100644 --- a/odoo/addons/base/views/ir_rule_views.xml +++ b/odoo/addons/base/views/ir_rule_views.xml @@ -100,7 +100,7 @@ <field name="name">Property multi-company</field> <field name="model_id" ref="model_ir_property"/> <field eval="True" name="global"/> - <field name="domain_force">['|',('company_id','child_of',[user.company_id.id]),('company_id','=',False)]</field> + <field name="domain_force">['|',('company_id', 'in', company_ids),('company_id','=',False)]</field> </record> diff --git a/odoo/addons/base/views/res_company_views.xml b/odoo/addons/base/views/res_company_views.xml index 8a0773e98da..c0138c94529 100644 --- a/odoo/addons/base/views/res_company_views.xml +++ b/odoo/addons/base/views/res_company_views.xml @@ -38,6 +38,7 @@ <field name="currency_id" options="{'no_create': True, 'no_open': True}" id="company_currency" context="{'active_test': False}"/> <field name="parent_id" groups="base.group_multi_company"/> <field name="sequence" invisible="1"/> + <field name="favicon" widget="image" class="float-left oe_avatar"/> </group> <group name="social_media"/> </group> @@ -50,7 +51,6 @@ <record id="view_company_tree" model="ir.ui.view"> <field name="name">res.company.tree</field> <field name="model">res.company</field> - <field name="field_parent">child_ids</field> <field name="arch" type="xml"> <tree string="Companies"> <field name="sequence" widget="handle"/> @@ -137,7 +137,7 @@ <field name="name"/> </h2> </xpath> - <field name="parent_id" groups="base.group_multi_company" position="replace" invisible="1"/> + <field name="parent_id" position="replace"/> <xpath expr="//sheet" position="inside"> <hr /> <div class="row mt16"> @@ -147,7 +147,7 @@ }"/> </div> <footer> - <button string="Save" type="object" class="oe_highlight" name="write"/> + <button string="Save" type="object" class="oe_highlight" special="save"/> <button string="Cancel" class="oe_link" special="cancel" /> </footer> </xpath> @@ -161,7 +161,7 @@ <field name="inherit_id" ref="base.view_company_report_form" /> <field name="priority">1024</field> <field name="arch" type="xml"> - <xpath expr="//button[@name='write']" position="before" > + <xpath expr="//button[@special='save']" position="before" > <button string="Save and Print" type="object" class="oe_highlight" name="write_company_and_print_report"/> </xpath> </field> diff --git a/odoo/addons/base/views/res_users_views.xml b/odoo/addons/base/views/res_users_views.xml index 62ae356a73c..d77cee157ba 100644 --- a/odoo/addons/base/views/res_users_views.xml +++ b/odoo/addons/base/views/res_users_views.xml @@ -209,7 +209,7 @@ <page name="access_rights" string="Access Rights"> <group string="Multi Companies" attrs="{'invisible': [('companies_count', '<=', 1)]}"> <field string="Allowed Companies" name="company_ids" widget="many2many_tags" options="{'no_create': True}"/> - <field string="Current Company" name="company_id" context="{'user_preference': 0}"/> + <field string="Default Company" name="company_id" context="{'user_preference': 0}"/> <field string="Companies count" name="companies_count" invisible="1"/> </group> <field name="groups_id"/> diff --git a/odoo/addons/test_access_rights/tests/test_feedback.py b/odoo/addons/test_access_rights/tests/test_feedback.py index 660dd068199..56207f9ecbc 100644 --- a/odoo/addons/test_access_rights/tests/test_feedback.py +++ b/odoo/addons/test_access_rights/tests/test_feedback.py @@ -115,7 +115,7 @@ class TestIRRuleFeedback(Feedback): """The requested operation ("write" on "Object For Test Access Right" (test_access_right.some_obj)) was rejected because of the following rules: - rule 0 -(records: [%s], uid: %d)""" % (self.record.id, self.user.id) +(Records: %s (id=%s), User: %s (id=%s))""" % (self.record.display_name, self.record.id, self.user.name, self.user.id) ) @@ -140,7 +140,7 @@ class TestIRRuleFeedback(Feedback): - rule 0 - rule 1 -(records: [%s], uid: %d)""" % (self.record.id, self.user.id) +(Records: %s (id=%s), User: %s (id=%s))""" % (self.record.display_name, self.record.id, self.user.name, self.user.id) ) def test_globals_all(self): @@ -156,7 +156,7 @@ class TestIRRuleFeedback(Feedback): - rule 0 - rule 1 -(records: [%s], uid: %d)""" % (self.record.id, self.user.id) +(Records: %s (id=%s), User: %s (id=%s))""" % (self.record.display_name, self.record.id, self.user.name, self.user.id) ) def test_globals_any(self): @@ -174,7 +174,7 @@ class TestIRRuleFeedback(Feedback): """The requested operation ("write" on "Object For Test Access Right" (test_access_right.some_obj)) was rejected because of the following rules: - rule 0 -(records: [%s], uid: %d)""" % (self.record.id, self.user.id) +(Records: %s (id=%s), User: %s (id=%s))""" % (self.record.display_name, self.record.id, self.user.name, self.user.id) ) def test_combination(self): @@ -193,7 +193,7 @@ class TestIRRuleFeedback(Feedback): - rule 2 - rule 3 -(records: [%s], uid: %d)""" % (self.record.id, self.user.id) +(Records: %s (id=%s), User: %s (id=%s))""" % (self.record.display_name, self.record.id, self.user.name, self.user.id) ) def test_warn_company(self): @@ -202,7 +202,7 @@ class TestIRRuleFeedback(Feedback): """ self.env.ref('base.group_no_one').write( {'users': [(4, self.user.id)]}) - self._make_rule('rule 0', "[('company_id', 'child_of', user.company_id.id)]") + self._make_rule('rule 0', "[('company_id', '=', user.company_id.id)]") self._make_rule('rule 1', '[("val", "=", 0)]', global_=True) with self.assertRaises(AccessError) as ctx: self.record.write({'val': 1}) @@ -213,7 +213,7 @@ class TestIRRuleFeedback(Feedback): Note: this might be a multi-company issue. -(records: [%s], uid: %d)""" % (self.record.id, self.user.id) +(Records: %s (id=%s), User: %s (id=%s))""" % (self.record.display_name, self.record.id, self.user.name, self.user.id) ) def test_read(self): @@ -222,7 +222,7 @@ Note: this might be a multi-company issue. """ self.env.ref('base.group_no_one').write( {'users': [(4, self.user.id)]}) - self._make_rule('rule 0', "[('company_id', 'child_of', user.company_id.id)]", attr='read') + self._make_rule('rule 0', "[('company_id', '=', user.company_id.id)]", attr='read') self._make_rule('rule 1', '[("val", "=", 1)]', global_=True, attr='read') with self.assertRaises(AccessError) as ctx: _ = self.record.val @@ -234,7 +234,7 @@ Note: this might be a multi-company issue. Note: this might be a multi-company issue. -(records: [%s], uid: %d)""" % (self.record.id, self.user.id) +(Records: %s (id=%s), User: %s (id=%s))""" % (self.record.display_name, self.record.id, self.user.name, self.user.id) ) p = self.env['test_access_right.parent'].create({'obj_id': self.record.id}) diff --git a/odoo/addons/test_new_api/tests/test_new_fields.py b/odoo/addons/test_new_api/tests/test_new_fields.py index d9253aaba69..578ad04d6f1 100644 --- a/odoo/addons/test_new_api/tests/test_new_fields.py +++ b/odoo/addons/test_new_api/tests/test_new_fields.py @@ -771,8 +771,8 @@ class TestFields(common.TransactionCase): """ test company-dependent fields. """ # consider three companies company0 = self.env.ref('base.main_company') - company1 = self.env['res.company'].create({'name': 'A', 'parent_id': company0.id}) - company2 = self.env['res.company'].create({'name': 'B', 'parent_id': company1.id}) + company1 = self.env['res.company'].create({'name': 'A'}) + company2 = self.env['res.company'].create({'name': 'B'}) # create one user per company user0 = self.env['res.users'].create({'name': 'Foo', 'login': 'foo', diff --git a/odoo/api.py b/odoo/api.py index 4a177e668dc..94b02961063 100644 --- a/odoo/api.py +++ b/odoo/api.py @@ -855,6 +855,39 @@ class Environment(Mapping): return self(user=SUPERUSER_ID)['res.users'].browse(self.uid) @property + def company_id(self): + """ return the company in which the user is logged in (as an instance) """ + try: + company_id = int(self.context.get('allowed_company_ids')[0]) + if company_id in self.user.company_ids.ids: + return self['res.company'].browse(company_id) + return self.user.company_id + except Exception: + return self.user.company_id + + @property + def company_ids(self): + """ return a recordset of the enabled companies by the user """ + try: # In case the user tries to bidouille the url (eg: cids=1,foo,bar) + allowed_company_ids = self.context.get('allowed_company_ids') + # Prevent the user to enable companies for which he doesn't have any access + users_company_ids = self.user.company_ids.ids + allowed_company_ids = [company_id for company_id in allowed_company_ids if company_id in users_company_ids] + except Exception: + # By setting the default companies to all user companies instead of the main one + # we save a lot of potential trouble in all "out of context" calls, such as + # /mail/redirect or /web/image, etc. And it is not unsafe because the user does + # have access to these other companies. The risk of exposing foreign records + # (wrt to the context) is low because all normal RPCs will have a proper + # allowed_company_ids. + # Examples: + # - when printing a report for several records from several companies + # - when accessing to a record from the notification email template + # - when loading an binary image on a template + allowed_company_ids = self.user.company_ids.ids + return self['res.company'].browse(allowed_company_ids) + + @property def lang(self): """ return the current language code """ return self.context.get('lang') diff --git a/odoo/fields.py b/odoo/fields.py index 2f8e64459a1..bc5f5e7d44f 100644 --- a/odoo/fields.py +++ b/odoo/fields.py @@ -657,8 +657,7 @@ class Field(MetaField('DummyField', (object,), {})): # read property as superuser, as the current user may not have access context = records.env.context if 'force_company' not in context: - field_id = records.env['ir.model.fields']._get_id(self.model_name, self.name) - company = records.env['res.company']._company_default_get(self.model_name, field_id) + company = records.env.company_id context = dict(context, force_company=company.id) Property = records.env(user=SUPERUSER_ID, context=context)['ir.property'] values = Property.get_multi(self.name, self.model_name, records.ids) @@ -669,8 +668,7 @@ class Field(MetaField('DummyField', (object,), {})): # update property as superuser, as the current user may not have access context = records.env.context if 'force_company' not in context: - field_id = records.env['ir.model.fields']._get_id(self.model_name, self.name) - company = records.env['res.company']._company_default_get(self.model_name, field_id) + company = records.env.company_id context = dict(context, force_company=company.id) Property = records.env(user=SUPERUSER_ID, context=context)['ir.property'] values = { diff --git a/odoo/tools/misc.py b/odoo/tools/misc.py index 671fd09e148..3d34c608fd4 100644 --- a/odoo/tools/misc.py +++ b/odoo/tools/misc.py @@ -422,20 +422,6 @@ def scan_languages(): return sorted(result or [('en_US', u'English')], key=itemgetter(1)) -def get_user_companies(cr, user): - def _get_company_children(cr, ids): - if not ids: - return [] - cr.execute('SELECT id FROM res_company WHERE parent_id IN %s', (tuple(ids),)) - res = [x[0] for x in cr.fetchall()] - res.extend(_get_company_children(cr, res)) - return res - cr.execute('SELECT company_id FROM res_users WHERE id=%s', (user,)) - user_comp = cr.fetchone()[0] - if not user_comp: - return [] - return [user_comp] + _get_company_children(cr, [user_comp]) - def mod10r(number): """ Input number : account or invoice number |
