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.

74 lines
2.5 KiB

  1. # Copyright 2014 ABF OSIELL <http://osiell.com>
  2. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  3. from odoo import api, fields, models
  4. class ResUsers(models.Model):
  5. _inherit = 'res.users'
  6. role_line_ids = fields.One2many(
  7. comodel_name='res.users.role.line',
  8. inverse_name='user_id',
  9. string="Role lines",
  10. default=lambda self: self._default_role_lines()
  11. )
  12. role_ids = fields.One2many(
  13. comodel_name='res.users.role', string="Roles",
  14. compute='_compute_role_ids')
  15. @api.model
  16. def _default_role_lines(self):
  17. default_user = self.env.ref(
  18. 'base.default_user', raise_if_not_found=False)
  19. default_values = []
  20. if default_user:
  21. for role_line in default_user.role_line_ids:
  22. default_values.append({
  23. 'role_id': role_line.role_id.id,
  24. 'date_from': role_line.date_from,
  25. 'date_to': role_line.date_to,
  26. 'is_enabled': role_line.is_enabled,
  27. })
  28. return default_values
  29. @api.multi
  30. @api.depends('role_line_ids.role_id')
  31. def _compute_role_ids(self):
  32. for user in self:
  33. user.role_ids = user.role_line_ids.mapped('role_id')
  34. @api.model
  35. def create(self, vals):
  36. new_record = super(ResUsers, self).create(vals)
  37. new_record.set_groups_from_roles()
  38. return new_record
  39. @api.multi
  40. def write(self, vals):
  41. res = super(ResUsers, self).write(vals)
  42. self.sudo().set_groups_from_roles()
  43. return res
  44. @api.multi
  45. def set_groups_from_roles(self, force=False):
  46. """Set (replace) the groups following the roles defined on users.
  47. If no role is defined on the user, its groups are let untouched unless
  48. the `force` parameter is `True`.
  49. """
  50. for user in self:
  51. if not user.role_line_ids and not force:
  52. continue
  53. group_ids = []
  54. role_lines = user.role_line_ids.filtered(
  55. lambda rec: rec.is_enabled)
  56. for role_line in role_lines:
  57. role = role_line.role_id
  58. if role:
  59. group_ids.append(role.group_id.id)
  60. group_ids.extend(role.implied_ids.ids)
  61. group_ids = list(set(group_ids)) # Remove duplicates IDs
  62. vals = {
  63. 'groups_id': [(6, 0, group_ids)],
  64. }
  65. super(ResUsers, user).write(vals)
  66. return True