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.

75 lines
2.5 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 ABF OSIELL <http://osiell.com>
  3. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
  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. def _get_enabled_roles(self):
  43. return self.role_line_ids.filtered(
  44. lambda rec: rec.is_enabled and
  45. (not rec.company_id or rec.company_id == rec.user_id.company_id))
  46. @api.multi
  47. def set_groups_from_roles(self):
  48. """Set (replace) the groups following the roles defined on users.
  49. If no role is defined on the user, its groups are let untouched.
  50. """
  51. for user in self:
  52. if not user.role_line_ids:
  53. continue
  54. group_ids = []
  55. for role_line in user._get_enabled_roles():
  56. role = role_line.role_id
  57. group_ids.append(role.group_id.id)
  58. group_ids.extend(role.implied_ids.ids)
  59. group_ids = list(set(group_ids)) # Remove duplicates IDs
  60. vals = {
  61. 'groups_id': [(6, 0, group_ids)],
  62. }
  63. super(ResUsers, user).write(vals)
  64. return True