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. 2
      base_user_role/readme/CONFIGURE.rst
  5. 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 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
_logger = logging.getLogger(__name__)
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"
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(
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(
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(
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",
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):
for role in self:
role.user_ids = role.line_ids.mapped('user_id')
role.user_ids = role.line_ids.mapped("user_id")
@api.model
def create(self, vals):
@ -49,14 +51,14 @@ class ResUsersRole(models.Model):
return res
def unlink(self):
users = self.mapped('user_ids')
users = self.mapped("user_ids")
res = super(ResUsersRole, self).unlink()
users.set_groups_from_roles(force=True)
return res
def update_users(self):
"""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()
return True
@ -67,33 +69,41 @@ class ResUsersRole(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(
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(
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_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(
'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):
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(
_('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):
today = datetime.date.today()
for role_line in self:
@ -108,7 +118,7 @@ class ResUsersRoleLine(models.Model):
role_line.is_enabled = False
def unlink(self):
users = self.mapped('user_id')
users = self.mapped("user_id")
res = super(ResUsersRoleLine, self).unlink()
users.set_groups_from_roles(force=True)
return res

56
base_user_role/models/user.py

@ -4,37 +4,38 @@ from odoo import api, fields, models
class ResUsers(models.Model):
_inherit = 'res.users'
_inherit = "res.users"
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",
default=lambda self: self._default_role_lines()
default=lambda self: self._default_role_lines(),
)
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
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 = []
if default_user:
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
@api.depends('role_line_ids.role_id')
@api.depends("role_line_ids.role_id")
def _compute_role_ids(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
def create(self, vals):
@ -49,8 +50,9 @@ class ResUsers(models.Model):
def _get_enabled_roles(self):
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):
"""Set (replace) the groups following the roles defined on users.
@ -60,10 +62,14 @@ class ResUsers(models.Model):
role_groups = {}
# We obtain all the groups associated to each role first, so that
# 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:
if not user.role_line_ids and not force:
continue
@ -71,15 +77,13 @@ class ResUsers(models.Model):
for role_line in user._get_enabled_roles():
role = role_line.role_id
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_remove = list(set(user.groups_id.ids) - set(group_ids))
to_add = [(4, gr) for gr in groups_to_add]
to_remove = [(3, gr) for gr in groups_to_remove]
groups = to_remove + to_add
if groups:
vals = {
'groups_id': groups,
}
vals = {"groups_id": groups}
super(ResUsers, user).write(vals)
return True

2
base_user_role/readme/CONFIGURE.rst

@ -21,4 +21,4 @@ Add users (with dates or not):
.. figure:: /OCA/server-backend/12.0/base_user_role/static/description/role_users.png
:width: 80 %
:align: center
:align: center

210
base_user_role/tests/test_user_role.py

@ -7,61 +7,62 @@ from odoo.tests.common import TransactionCase
class TestUserRole(TransactionCase):
def setUp(self):
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(
{'name': "USER TEST (ROLES)", 'login': 'user_test_roles'})
{"name": "USER TEST (ROLES)", "login": "user_test_roles"}
)
# 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 = {
'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)
# ROLE_2
# Must have group_user in order to have sufficient groups. Check:
# 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 = {
'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_settings_id.id])],
self.group_settings_id.id,
],
)
],
}
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(
{'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):
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.append(self.role1_id.group_id.id)
role_group_ids = sorted(set(role_group_ids))
self.assertEqual(user_group_ids, role_group_ids)
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.append(self.role2_id.group_id.id)
role_group_ids = sorted(set(role_group_ids))
@ -69,12 +70,14 @@ class TestUserRole(TransactionCase):
def test_role_1_2(self):
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.append(self.role1_id.group_id.id)
role2_group_ids = self.role2_id.trans_implied_ids.ids
@ -88,15 +91,16 @@ class TestUserRole(TransactionCase):
yesterday = today - datetime.timedelta(days=1)
yesterday_str = fields.Date.to_string(yesterday)
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.append(self.role1_id.group_id.id)
role_group_ids = sorted(set(role1_group_ids))
@ -110,19 +114,20 @@ class TestUserRole(TransactionCase):
# Configure the user with role1 and role2
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
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)
# Remove role1
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, [])
def test_role_line_unlink(self):
@ -133,57 +138,71 @@ class TestUserRole(TransactionCase):
# Configure the user with role1 and role2
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
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)
# Remove role1 from the user
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, [])
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])
self.assertEqual(user.role_ids, roles)
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
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):
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.append(self.role1_id.group_id.id)
role_group_ids = sorted(set(role_group_ids))
@ -191,12 +210,15 @@ class TestUserRole(TransactionCase):
self.assertEqual(user_group_ids, role_group_ids)
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.append(self.role2_id.group_id.id)
role_group_ids = sorted(set(role_group_ids))

Loading…
Cancel
Save