diff --git a/odoo/addons/base/models/res_company.py b/odoo/addons/base/models/res_company.py index af480ebf0d2..a3f72fc9deb 100644 --- a/odoo/addons/base/models/res_company.py +++ b/odoo/addons/base/models/res_company.py @@ -372,13 +372,25 @@ class Company(models.Model): return main_company - @ormcache('tuple(self.env.companies.ids)', 'self.id') + @ormcache('tuple(self.env.companies.ids)', 'self.id', 'self.env.uid') def __accessible_branches(self): # Get branches of this company that the current user can use self.ensure_one() - children = self.search([('id', 'child_of', self.id)]) + + accessible_branch_ids = [] accessible = self.env.companies - return (children & accessible).ids + current = self.sudo() + while current: + accessible_branch_ids.extend((current & accessible).ids) + current = current.child_ids + + if not accessible_branch_ids and self.env.uid == SUPERUSER_ID: + # Accessible companies will always be the same for super user when called in a cron. + # Because of that, the intersection between them and self might be empty. The super user anyway always has + # access to all companies (as it bypasses the record rules), so we return the current company in this case. + return self.ids + + return accessible_branch_ids def _accessible_branches(self): return self.browse(self.__accessible_branches())