You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.2 KiB

  1. # Copyright (C) 2021 Open Source Integrators
  2. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  3. from odoo import _, api, fields, models
  4. from odoo.exceptions import ValidationError
  5. class ResUsersRoleLine(models.Model):
  6. _inherit = "res.users.role.line"
  7. company_id = fields.Many2one(
  8. "res.company",
  9. "Company",
  10. help="If set, this role only applies when this is the main company selected."
  11. " Otherwise it applies to all companies.",
  12. )
  13. active_role = fields.Boolean(string="Active Role", default=True)
  14. @api.constrains("user_id", "company_id")
  15. def _check_company(self):
  16. for record in self:
  17. if (
  18. record.company_id
  19. and record.company_id != record.user_id.company_id
  20. and record.company_id not in record.user_id.company_ids
  21. ):
  22. raise ValidationError(
  23. _('User "{}" does not have access to the company "{}"').format(
  24. record.user_id.name, record.company_id.name
  25. )
  26. )
  27. _sql_constraints = [
  28. (
  29. "user_role_uniq",
  30. "unique (user_id,role_id,company_id)",
  31. "Roles can be assigned to a user only once at a time",
  32. )
  33. ]
  34. class ResUsers(models.Model):
  35. _inherit = "res.users"
  36. def _get_enabled_roles(self):
  37. res = super()._get_enabled_roles()
  38. return res.filtered("active_role")
  39. @api.model
  40. def _set_session_active_roles(self, cids):
  41. """
  42. Based on the selected companies (cids),
  43. calculate the roles to enable.
  44. A role should be enabled only when it applies to all selected companies.
  45. """
  46. for role_line in self.env.user.role_line_ids:
  47. if not role_line.company_id:
  48. role_line.active_role = True
  49. elif role_line.company_id.id in cids:
  50. is_on_companies = self.env.user.role_line_ids.filtered(
  51. lambda x: x.role_id == role_line.role_id and x.company_id.id in cids
  52. )
  53. role_line.active_role = len(is_on_companies) == len(cids)
  54. else:
  55. role_line.active_role = False