Browse Source

[IMP] base_user_role: black, isort

14.0
sebalix 5 years ago
committed by Jesús Alan Ramos Rodríguez
parent
commit
0e1b4653f7
  1. 32
      base_user_role/__manifest__.py
  2. 82
      base_user_role/models/role.py
  3. 56
      base_user_role/models/user.py
  4. 210
      base_user_role/tests/test_user_role.py

32
base_user_role/__manifest__.py

@ -3,22 +3,20 @@
{ {
'name': 'User roles',
'version': '13.0.1.0.0',
'category': 'Tools',
'author': 'ABF OSIELL, Odoo Community Association (OCA)',
'license': 'LGPL-3',
'maintainers': ['sebalix', 'jcdrubay', 'novawish'],
'website': 'https://github.com/OCA/server-backend',
'depends': [
'base',
"name": "User roles",
"version": "13.0.1.0.0",
"category": "Tools",
"author": "ABF OSIELL, Odoo Community Association (OCA)",
"license": "LGPL-3",
"maintainers": ["sebalix", "jcdrubay", "novawish"],
"website": "https://github.com/OCA/server-backend",
"depends": ["base"],
"data": [
"security/ir.model.access.csv",
"data/ir_cron.xml",
"data/ir_module_category.xml",
"views/role.xml",
"views/user.xml",
], ],
'data': [
'security/ir.model.access.csv',
'data/ir_cron.xml',
'data/ir_module_category.xml',
'views/role.xml',
'views/user.xml',
],
'installable': True,
"installable": True,
} }

82
base_user_role/models/role.py

@ -3,39 +3,41 @@
import datetime import datetime
import logging import logging
from odoo import _, api, fields, models
from odoo import SUPERUSER_ID
from odoo import SUPERUSER_ID, _, api, fields, models
from odoo.exceptions import ValidationError from odoo.exceptions import ValidationError
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
class ResUsersRole(models.Model): class ResUsersRole(models.Model):
_name = 'res.users.role'
_inherits = {'res.groups': 'group_id'}
_name = "res.users.role"
_inherits = {"res.groups": "group_id"}
_description = "User role" _description = "User role"
group_id = fields.Many2one( group_id = fields.Many2one(
comodel_name='res.groups', required=True, ondelete='cascade',
readonly=True, string="Associated group")
comodel_name="res.groups",
required=True,
ondelete="cascade",
readonly=True,
string="Associated group",
)
line_ids = fields.One2many( line_ids = fields.One2many(
comodel_name='res.users.role.line',
inverse_name='role_id', string="Role lines")
comodel_name="res.users.role.line", inverse_name="role_id", string="Role lines"
)
user_ids = fields.One2many( user_ids = fields.One2many(
comodel_name='res.users', string="Users list",
compute='_compute_user_ids')
comodel_name="res.users", string="Users list", compute="_compute_user_ids"
)
group_category_id = fields.Many2one( group_category_id = fields.Many2one(
related='group_id.category_id',
default=lambda cls: cls.env.ref(
'base_user_role.ir_module_category_role').id,
related="group_id.category_id",
default=lambda cls: cls.env.ref("base_user_role.ir_module_category_role").id,
string="Associated category", string="Associated category",
help="Associated group's category")
help="Associated group's category",
)
@api.depends('line_ids.user_id')
@api.depends("line_ids.user_id")
def _compute_user_ids(self): def _compute_user_ids(self):
for role in self: for role in self:
role.user_ids = role.line_ids.mapped('user_id')
role.user_ids = role.line_ids.mapped("user_id")
@api.model @api.model
def create(self, vals): def create(self, vals):
@ -49,14 +51,14 @@ class ResUsersRole(models.Model):
return res return res
def unlink(self): def unlink(self):
users = self.mapped('user_ids')
users = self.mapped("user_ids")
res = super(ResUsersRole, self).unlink() res = super(ResUsersRole, self).unlink()
users.set_groups_from_roles(force=True) users.set_groups_from_roles(force=True)
return res return res
def update_users(self): def update_users(self):
"""Update all the users concerned by the roles identified by `ids`.""" """Update all the users concerned by the roles identified by `ids`."""
users = self.mapped('user_ids')
users = self.mapped("user_ids")
users.set_groups_from_roles() users.set_groups_from_roles()
return True return True
@ -67,33 +69,41 @@ class ResUsersRole(models.Model):
class ResUsersRoleLine(models.Model): class ResUsersRoleLine(models.Model):
_name = 'res.users.role.line'
_description = 'Users associated to a role'
_name = "res.users.role.line"
_description = "Users associated to a role"
role_id = fields.Many2one( role_id = fields.Many2one(
comodel_name='res.users.role', required=True, string="Role",
ondelete='cascade')
comodel_name="res.users.role", required=True, string="Role", ondelete="cascade"
)
user_id = fields.Many2one( user_id = fields.Many2one(
comodel_name='res.users', required=True, string="User",
domain=[('id', '!=', SUPERUSER_ID)], ondelete='cascade')
comodel_name="res.users",
required=True,
string="User",
domain=[("id", "!=", SUPERUSER_ID)],
ondelete="cascade",
)
date_from = fields.Date("From") date_from = fields.Date("From")
date_to = fields.Date("To") date_to = fields.Date("To")
is_enabled = fields.Boolean("Enabled", compute='_compute_is_enabled')
is_enabled = fields.Boolean("Enabled", compute="_compute_is_enabled")
company_id = fields.Many2one( company_id = fields.Many2one(
'res.company', 'Company',
default=lambda self: self.env.user.company_id)
"res.company", "Company", default=lambda self: self.env.user.company_id
)
@api.constrains('user_id', 'company_id')
@api.constrains("user_id", "company_id")
def _check_company(self): def _check_company(self):
for record in self: for record in self:
if (record.company_id and
record.company_id != record.user_id.company_id and
record.company_id not in record.user_id.company_ids):
if (
record.company_id
and record.company_id != record.user_id.company_id
and record.company_id not in record.user_id.company_ids
):
raise ValidationError( raise ValidationError(
_('User "{}" does not have access to the company "{}"')
.format(record.user_id.name, record.company_id.name))
_('User "{}" does not have access to the company "{}"').format(
record.user_id.name, record.company_id.name
)
)
@api.depends('date_from', 'date_to')
@api.depends("date_from", "date_to")
def _compute_is_enabled(self): def _compute_is_enabled(self):
today = datetime.date.today() today = datetime.date.today()
for role_line in self: for role_line in self:
@ -108,7 +118,7 @@ class ResUsersRoleLine(models.Model):
role_line.is_enabled = False role_line.is_enabled = False
def unlink(self): def unlink(self):
users = self.mapped('user_id')
users = self.mapped("user_id")
res = super(ResUsersRoleLine, self).unlink() res = super(ResUsersRoleLine, self).unlink()
users.set_groups_from_roles(force=True) users.set_groups_from_roles(force=True)
return res return res

56
base_user_role/models/user.py

@ -4,37 +4,38 @@ from odoo import api, fields, models
class ResUsers(models.Model): class ResUsers(models.Model):
_inherit = 'res.users'
_inherit = "res.users"
role_line_ids = fields.One2many( role_line_ids = fields.One2many(
comodel_name='res.users.role.line',
inverse_name='user_id',
comodel_name="res.users.role.line",
inverse_name="user_id",
string="Role lines", string="Role lines",
default=lambda self: self._default_role_lines()
default=lambda self: self._default_role_lines(),
) )
role_ids = fields.One2many( role_ids = fields.One2many(
comodel_name='res.users.role', string="Roles",
compute='_compute_role_ids')
comodel_name="res.users.role", string="Roles", compute="_compute_role_ids"
)
@api.model @api.model
def _default_role_lines(self): def _default_role_lines(self):
default_user = self.env.ref(
'base.default_user', raise_if_not_found=False)
default_user = self.env.ref("base.default_user", raise_if_not_found=False)
default_values = [] default_values = []
if default_user: if default_user:
for role_line in default_user.role_line_ids: for role_line in default_user.role_line_ids:
default_values.append({
'role_id': role_line.role_id.id,
'date_from': role_line.date_from,
'date_to': role_line.date_to,
'is_enabled': role_line.is_enabled,
})
default_values.append(
{
"role_id": role_line.role_id.id,
"date_from": role_line.date_from,
"date_to": role_line.date_to,
"is_enabled": role_line.is_enabled,
}
)
return default_values return default_values
@api.depends('role_line_ids.role_id')
@api.depends("role_line_ids.role_id")
def _compute_role_ids(self): def _compute_role_ids(self):
for user in self: for user in self:
user.role_ids = user.role_line_ids.mapped('role_id')
user.role_ids = user.role_line_ids.mapped("role_id")
@api.model @api.model
def create(self, vals): def create(self, vals):
@ -49,8 +50,9 @@ class ResUsers(models.Model):
def _get_enabled_roles(self): def _get_enabled_roles(self):
return self.role_line_ids.filtered( return self.role_line_ids.filtered(
lambda rec: rec.is_enabled and
(not rec.company_id or rec.company_id == rec.user_id.company_id))
lambda rec: rec.is_enabled
and (not rec.company_id or rec.company_id == rec.user_id.company_id)
)
def set_groups_from_roles(self, force=False): def set_groups_from_roles(self, force=False):
"""Set (replace) the groups following the roles defined on users. """Set (replace) the groups following the roles defined on users.
@ -60,10 +62,14 @@ class ResUsers(models.Model):
role_groups = {} role_groups = {}
# We obtain all the groups associated to each role first, so that # We obtain all the groups associated to each role first, so that
# it is faster to compare later with each user's groups. # it is faster to compare later with each user's groups.
for role in self.mapped('role_line_ids.role_id'):
role_groups[role] = list(set(
role.group_id.ids + role.implied_ids.ids +
role.trans_implied_ids.ids))
for role in self.mapped("role_line_ids.role_id"):
role_groups[role] = list(
set(
role.group_id.ids
+ role.implied_ids.ids
+ role.trans_implied_ids.ids
)
)
for user in self: for user in self:
if not user.role_line_ids and not force: if not user.role_line_ids and not force:
continue continue
@ -71,15 +77,13 @@ class ResUsers(models.Model):
for role_line in user._get_enabled_roles(): for role_line in user._get_enabled_roles():
role = role_line.role_id role = role_line.role_id
group_ids += role_groups[role] group_ids += role_groups[role]
group_ids = list(set(group_ids)) # Remove duplicates IDs
group_ids = list(set(group_ids)) # Remove duplicates IDs
groups_to_add = list(set(group_ids) - set(user.groups_id.ids)) groups_to_add = list(set(group_ids) - set(user.groups_id.ids))
groups_to_remove = list(set(user.groups_id.ids) - set(group_ids)) groups_to_remove = list(set(user.groups_id.ids) - set(group_ids))
to_add = [(4, gr) for gr in groups_to_add] to_add = [(4, gr) for gr in groups_to_add]
to_remove = [(3, gr) for gr in groups_to_remove] to_remove = [(3, gr) for gr in groups_to_remove]
groups = to_remove + to_add groups = to_remove + to_add
if groups: if groups:
vals = {
'groups_id': groups,
}
vals = {"groups_id": groups}
super(ResUsers, user).write(vals) super(ResUsers, user).write(vals)
return True return True

210
base_user_role/tests/test_user_role.py

@ -7,61 +7,62 @@ from odoo.tests.common import TransactionCase
class TestUserRole(TransactionCase): class TestUserRole(TransactionCase):
def setUp(self): def setUp(self):
super(TestUserRole, self).setUp() super(TestUserRole, self).setUp()
self.user_model = self.env['res.users']
self.role_model = self.env['res.users.role']
self.user_model = self.env["res.users"]
self.role_model = self.env["res.users.role"]
self.default_user = self.env.ref('base.default_user')
self.default_user = self.env.ref("base.default_user")
self.user_id = self.user_model.create( self.user_id = self.user_model.create(
{'name': "USER TEST (ROLES)", 'login': 'user_test_roles'})
{"name": "USER TEST (ROLES)", "login": "user_test_roles"}
)
# ROLE_1 # ROLE_1
self.group_user_id = self.env.ref('base.group_user')
self.group_no_one_id = self.env.ref('base.group_no_one')
self.group_user_id = self.env.ref("base.group_user")
self.group_no_one_id = self.env.ref("base.group_no_one")
vals = { vals = {
'name': "ROLE_1",
'implied_ids': [
(6, 0, [self.group_user_id.id, self.group_no_one_id.id])],
"name": "ROLE_1",
"implied_ids": [(6, 0, [self.group_user_id.id, self.group_no_one_id.id])],
} }
self.role1_id = self.role_model.create(vals) self.role1_id = self.role_model.create(vals)
# ROLE_2 # ROLE_2
# Must have group_user in order to have sufficient groups. Check: # Must have group_user in order to have sufficient groups. Check:
# github.com/odoo/odoo/commit/c3717f3018ce0571aa41f70da4262cc946d883b4 # github.com/odoo/odoo/commit/c3717f3018ce0571aa41f70da4262cc946d883b4
self.group_multi_currency_id = self.env.ref(
'base.group_multi_currency')
self.group_settings_id = self.env.ref('base.group_system')
self.group_multi_currency_id = self.env.ref("base.group_multi_currency")
self.group_settings_id = self.env.ref("base.group_system")
vals = { vals = {
'name': "ROLE_2",
'implied_ids': [
(6, 0, [self.group_user_id.id,
"name": "ROLE_2",
"implied_ids": [
(
6,
0,
[
self.group_user_id.id,
self.group_multi_currency_id.id, self.group_multi_currency_id.id,
self.group_settings_id.id])],
self.group_settings_id.id,
],
)
],
} }
self.role2_id = self.role_model.create(vals) self.role2_id = self.role_model.create(vals)
self.company1 = self.env.ref('base.main_company')
self.company2 = self.env['res.company'].create({'name': 'company2'})
self.company1 = self.env.ref("base.main_company")
self.company2 = self.env["res.company"].create({"name": "company2"})
self.user_id.write( self.user_id.write(
{'company_ids': [
(4, self.company1.id, 0), (4, self.company2.id, 0)]})
{"company_ids": [(4, self.company1.id, 0), (4, self.company2.id, 0)]}
)
def test_role_1(self): def test_role_1(self):
self.user_id.write(
{'role_line_ids': [(0, 0, {'role_id': self.role1_id.id})]})
user_group_ids = sorted(set(
[group.id for group in self.user_id.groups_id]))
self.user_id.write({"role_line_ids": [(0, 0, {"role_id": self.role1_id.id})]})
user_group_ids = sorted({group.id for group in self.user_id.groups_id})
role_group_ids = self.role1_id.trans_implied_ids.ids role_group_ids = self.role1_id.trans_implied_ids.ids
role_group_ids.append(self.role1_id.group_id.id) role_group_ids.append(self.role1_id.group_id.id)
role_group_ids = sorted(set(role_group_ids)) role_group_ids = sorted(set(role_group_ids))
self.assertEqual(user_group_ids, role_group_ids) self.assertEqual(user_group_ids, role_group_ids)
def test_role_2(self): def test_role_2(self):
self.user_id.write(
{'role_line_ids': [(0, 0, {'role_id': self.role2_id.id})]})
user_group_ids = sorted(set(
[group.id for group in self.user_id.groups_id]))
self.user_id.write({"role_line_ids": [(0, 0, {"role_id": self.role2_id.id})]})
user_group_ids = sorted({group.id for group in self.user_id.groups_id})
role_group_ids = self.role2_id.trans_implied_ids.ids role_group_ids = self.role2_id.trans_implied_ids.ids
role_group_ids.append(self.role2_id.group_id.id) role_group_ids.append(self.role2_id.group_id.id)
role_group_ids = sorted(set(role_group_ids)) role_group_ids = sorted(set(role_group_ids))
@ -69,12 +70,14 @@ class TestUserRole(TransactionCase):
def test_role_1_2(self): def test_role_1_2(self):
self.user_id.write( self.user_id.write(
{'role_line_ids': [
(0, 0, {'role_id': self.role1_id.id}),
(0, 0, {'role_id': self.role2_id.id}),
]})
user_group_ids = sorted(set(
[group.id for group in self.user_id.groups_id]))
{
"role_line_ids": [
(0, 0, {"role_id": self.role1_id.id}),
(0, 0, {"role_id": self.role2_id.id}),
]
}
)
user_group_ids = sorted({group.id for group in self.user_id.groups_id})
role1_group_ids = self.role1_id.trans_implied_ids.ids role1_group_ids = self.role1_id.trans_implied_ids.ids
role1_group_ids.append(self.role1_id.group_id.id) role1_group_ids.append(self.role1_id.group_id.id)
role2_group_ids = self.role2_id.trans_implied_ids.ids role2_group_ids = self.role2_id.trans_implied_ids.ids
@ -88,15 +91,16 @@ class TestUserRole(TransactionCase):
yesterday = today - datetime.timedelta(days=1) yesterday = today - datetime.timedelta(days=1)
yesterday_str = fields.Date.to_string(yesterday) yesterday_str = fields.Date.to_string(yesterday)
self.user_id.write( self.user_id.write(
{'role_line_ids': [
# Role 1 should be enabled
(0, 0, {'role_id': self.role1_id.id, 'date_from': today_str}),
# Role 2 should be disabled
(0, 0,
{'role_id': self.role2_id.id, 'date_to': yesterday_str}),
]})
user_group_ids = sorted(set(
[group.id for group in self.user_id.groups_id]))
{
"role_line_ids": [
# Role 1 should be enabled
(0, 0, {"role_id": self.role1_id.id, "date_from": today_str}),
# Role 2 should be disabled
(0, 0, {"role_id": self.role2_id.id, "date_to": yesterday_str}),
]
}
)
user_group_ids = sorted({group.id for group in self.user_id.groups_id})
role1_group_ids = self.role1_id.trans_implied_ids.ids role1_group_ids = self.role1_id.trans_implied_ids.ids
role1_group_ids.append(self.role1_id.group_id.id) role1_group_ids.append(self.role1_id.group_id.id)
role_group_ids = sorted(set(role1_group_ids)) role_group_ids = sorted(set(role1_group_ids))
@ -110,19 +114,20 @@ class TestUserRole(TransactionCase):
# Configure the user with role1 and role2 # Configure the user with role1 and role2
self.user_id.write( self.user_id.write(
{'role_line_ids': [
(0, 0, {'role_id': self.role1_id.id}),
(0, 0, {'role_id': self.role2_id.id}),
]})
{
"role_line_ids": [
(0, 0, {"role_id": self.role1_id.id}),
(0, 0, {"role_id": self.role2_id.id}),
]
}
)
# Remove role2 # Remove role2
self.role2_id.unlink() self.role2_id.unlink()
user_group_ids = sorted(set([
group.id for group in self.user_id.groups_id]))
user_group_ids = sorted({group.id for group in self.user_id.groups_id})
self.assertEqual(user_group_ids, role1_group_ids) self.assertEqual(user_group_ids, role1_group_ids)
# Remove role1 # Remove role1
self.role1_id.unlink() self.role1_id.unlink()
user_group_ids = sorted(set([
group.id for group in self.user_id.groups_id]))
user_group_ids = sorted({group.id for group in self.user_id.groups_id})
self.assertEqual(user_group_ids, []) self.assertEqual(user_group_ids, [])
def test_role_line_unlink(self): def test_role_line_unlink(self):
@ -133,57 +138,71 @@ class TestUserRole(TransactionCase):
# Configure the user with role1 and role2 # Configure the user with role1 and role2
self.user_id.write( self.user_id.write(
{'role_line_ids': [
(0, 0, {'role_id': self.role1_id.id}),
(0, 0, {'role_id': self.role2_id.id}),
]})
{
"role_line_ids": [
(0, 0, {"role_id": self.role1_id.id}),
(0, 0, {"role_id": self.role2_id.id}),
]
}
)
# Remove role2 from the user # Remove role2 from the user
self.user_id.role_line_ids.filtered( self.user_id.role_line_ids.filtered(
lambda l: l.role_id.id == self.role2_id.id).unlink()
user_group_ids = sorted(set([
group.id for group in self.user_id.groups_id]))
lambda l: l.role_id.id == self.role2_id.id
).unlink()
user_group_ids = sorted({group.id for group in self.user_id.groups_id})
self.assertEqual(user_group_ids, role1_group_ids) self.assertEqual(user_group_ids, role1_group_ids)
# Remove role1 from the user # Remove role1 from the user
self.user_id.role_line_ids.filtered( self.user_id.role_line_ids.filtered(
lambda l: l.role_id.id == self.role1_id.id).unlink()
user_group_ids = sorted(set([
group.id for group in self.user_id.groups_id]))
lambda l: l.role_id.id == self.role1_id.id
).unlink()
user_group_ids = sorted({group.id for group in self.user_id.groups_id})
self.assertEqual(user_group_ids, []) self.assertEqual(user_group_ids, [])
def test_default_user_roles(self): def test_default_user_roles(self):
self.default_user.write({
'role_line_ids': [
(0, 0, {
'role_id': self.role1_id.id,
}),
(0, 0, {
'role_id': self.role2_id.id,
})
]
})
user = self.user_model.create({
'name': "USER TEST (DEFAULT ROLES)",
'login': 'user_test_default_roles'
})
self.default_user.write(
{
"role_line_ids": [
(0, 0, {"role_id": self.role1_id.id}),
(0, 0, {"role_id": self.role2_id.id}),
]
}
)
user = self.user_model.create(
{"name": "USER TEST (DEFAULT ROLES)", "login": "user_test_default_roles"}
)
roles = self.role_model.browse([self.role1_id.id, self.role2_id.id]) roles = self.role_model.browse([self.role1_id.id, self.role2_id.id])
self.assertEqual(user.role_ids, roles) self.assertEqual(user.role_ids, roles)
def test_user_role_different_company(self): def test_user_role_different_company(self):
self.user_id.write({'company_id': self.company1.id})
self.user_id.write({'role_line_ids': [(0, 0, {
'role_id': self.role2_id.id,
'company_id': self.company2.id})]})
self.user_id.write({"company_id": self.company1.id})
self.user_id.write(
{
"role_line_ids": [
(
0,
0,
{"role_id": self.role2_id.id, "company_id": self.company2.id},
)
]
}
)
# Check that user does not have any groups # Check that user does not have any groups
self.assertEquals(
self.user_id.groups_id, self.env['res.groups'].browse())
self.assertEquals(self.user_id.groups_id, self.env["res.groups"].browse())
def test_user_role_same_company(self): def test_user_role_same_company(self):
self.user_id.write({'company_id': self.company1.id})
self.user_id.write({'role_line_ids': [(0, 0, {
'role_id': self.role1_id.id,
'company_id': self.company1.id})]})
user_group_ids = sorted(set(
[group.id for group in self.user_id.groups_id]))
self.user_id.write({"company_id": self.company1.id})
self.user_id.write(
{
"role_line_ids": [
(
0,
0,
{"role_id": self.role1_id.id, "company_id": self.company1.id},
)
]
}
)
user_group_ids = sorted({group.id for group in self.user_id.groups_id})
role_group_ids = self.role1_id.trans_implied_ids.ids role_group_ids = self.role1_id.trans_implied_ids.ids
role_group_ids.append(self.role1_id.group_id.id) role_group_ids.append(self.role1_id.group_id.id)
role_group_ids = sorted(set(role_group_ids)) role_group_ids = sorted(set(role_group_ids))
@ -191,12 +210,15 @@ class TestUserRole(TransactionCase):
self.assertEqual(user_group_ids, role_group_ids) self.assertEqual(user_group_ids, role_group_ids)
def test_user_role_no_company(self): def test_user_role_no_company(self):
self.user_id.write({'company_id': self.company1.id})
self.user_id.write({'role_line_ids': [(0, 0, {
'role_id': self.role2_id.id,
'company_id': False})]})
user_group_ids = sorted(set(
[group.id for group in self.user_id.groups_id]))
self.user_id.write({"company_id": self.company1.id})
self.user_id.write(
{
"role_line_ids": [
(0, 0, {"role_id": self.role2_id.id, "company_id": False})
]
}
)
user_group_ids = sorted({group.id for group in self.user_id.groups_id})
role_group_ids = self.role2_id.trans_implied_ids.ids role_group_ids = self.role2_id.trans_implied_ids.ids
role_group_ids.append(self.role2_id.group_id.id) role_group_ids.append(self.role2_id.group_id.id)
role_group_ids = sorted(set(role_group_ids)) role_group_ids = sorted(set(role_group_ids))

Loading…
Cancel
Save