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.

72 lines
2.4 KiB

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