size
int64 0
304k
| ext
stringclasses 1
value | lang
stringclasses 1
value | branch
stringclasses 1
value | content
stringlengths 0
304k
| avg_line_length
float64 0
238
| max_line_length
int64 0
304k
|
|---|---|---|---|---|---|---|
376
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2018 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
relative_ids = fields.One2many(
string="Relatives",
comodel_name="hr.employee.relative",
inverse_name="employee_id",
)
| 26.857143
| 376
|
2,796
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from collections import defaultdict
from odoo import SUPERUSER_ID, api
def post_init_hook(cr, registry, employees=None):
"""Split current calendars by date ranges and assign new ones for
having proper initial data.
"""
env = api.Environment(cr, SUPERUSER_ID, {})
if not employees:
employees = env["hr.employee"].search([])
calendars = employees.mapped("resource_calendar_id")
calendar_obj = env["resource.calendar"]
line_obj = env["resource.calendar.attendance"]
groups = line_obj.read_group(
[("calendar_id", "in", calendars.ids)],
["calendar_id", "date_from", "date_to"],
["calendar_id", "date_from:day", "date_to:day"],
lazy=False,
)
calendar_mapping = defaultdict(list)
for group in groups:
calendar = calendar_obj.browse(group["calendar_id"][0])
lines = line_obj.search(group["__domain"])
if len(calendar.attendance_ids) == len(lines):
# Don't alter calendar, as it's the same
new_calendar = calendar
else:
name = calendar.name + " {}-{}".format(
lines[0].date_from,
lines[0].date_to,
)
attendances = []
for line in lines:
data = line.copy_data({"date_from": False, "date_to": False})[0]
data.pop("calendar_id")
attendances.append((0, 0, data))
new_calendar = calendar_obj.create(
{"name": name, "attendance_ids": attendances}
)
calendar_mapping[calendar].append(
(lines[0].date_from, lines[0].date_to, new_calendar),
)
for employee in employees.filtered("resource_calendar_id"):
calendar_lines = []
for data in calendar_mapping[employee.resource_calendar_id]:
calendar_lines.append(
(
0,
0,
{
"date_start": data[0],
"date_end": data[1],
"calendar_id": data[2].id,
},
)
)
# Extract employee's existing leaves so they are passed to the new
# automatic calendar.
leaves = employee.resource_calendar_id.leave_ids.filtered(
lambda x: x.resource_id == employee.resource_id
)
employee.calendar_ids = calendar_lines
employee.resource_calendar_id.active = False
# Now the automatic calendar has been created, so we link the
# leaves to that one so they count correctly.
leaves.write({"calendar_id": employee.resource_calendar_id.id})
| 39.380282
| 2,796
|
631
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Employee Calendar Planning",
"version": "15.0.1.1.8",
"category": "Human Resources",
"website": "https://github.com/OCA/hr",
"author": "Tecnativa,Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": ["hr"],
"data": [
"security/ir.model.access.csv",
"views/hr_employee_views.xml",
"views/resource_calendar_views.xml",
],
"post_init_hook": "post_init_hook",
"maintainers": ["victoralmau", "pedrobaeza"],
}
| 33.210526
| 631
|
17,694
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Pedro M. Baeza
# Copyright 2021-2023 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import exceptions, fields
from odoo.tests import common, new_test_user
from ..hooks import post_init_hook
class TestHrEmployeeCalendarPlanning(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(
context=dict(
cls.env.context,
mail_create_nolog=True,
mail_create_nosubscribe=True,
mail_notrack=True,
no_reset_password=True,
tracking_disable=True,
test_hr_employee_calendar_planning=True,
)
)
resource_calendar = cls.env["resource.calendar"]
cls.calendar1 = resource_calendar.create(
{"name": "Test calendar 1", "attendance_ids": []}
)
cls.calendar2 = resource_calendar.create(
{"name": "Test calendar 2", "attendance_ids": []}
)
for day in range(5): # From monday to friday
cls.calendar1.attendance_ids = [
(
0,
0,
{
"name": "Attendance",
"dayofweek": str(day),
"hour_from": "08",
"hour_to": "12",
},
),
(
0,
0,
{
"name": "Attendance",
"dayofweek": str(day),
"hour_from": "13",
"hour_to": "17",
},
),
]
cls.calendar2.attendance_ids = [
(
0,
0,
{
"name": "Attendance",
"dayofweek": str(day),
"hour_from": "07",
"hour_to": "14",
},
),
]
cls.employee = cls.env["hr.employee"].create({"name": "Test employee"})
cls.leave1 = cls.env["resource.calendar.leaves"].create(
{
"name": "Test leave",
"calendar_id": cls.calendar1.id,
"resource_id": cls.employee.resource_id.id,
"date_from": "2019-06-01",
"date_to": "2019-06-10",
}
)
cls.global_leave1 = cls.env["resource.calendar.leaves"].create(
{
"name": "Global Leave 1",
"date_from": "2019-03-01",
"date_to": "2019-03-02",
}
)
cls.global_leave2 = cls.env["resource.calendar.leaves"].create(
{
"name": "Global Leave 2",
"date_from": "2020-03-12",
"date_to": "2020-03-13",
}
)
cls.global_leave3 = cls.env["resource.calendar.leaves"].create(
{
"name": "Global Leave 3",
"date_from": "2020-03-09",
"date_to": "2020-03-10",
}
)
cls.calendar1.global_leave_ids = [
(6, 0, [cls.global_leave1.id, cls.global_leave2.id])
]
cls.calendar2.global_leave_ids = [(6, 0, [cls.global_leave3.id])]
# By default a calendar_ids is set, we remove it to better clarify the tests.
cls.employee.write({"calendar_ids": [(2, cls.employee.calendar_ids.id)]})
def test_calendar_planning(self):
self.employee.calendar_ids = [
(0, 0, {"date_end": "2019-12-31", "calendar_id": self.calendar1.id}),
(0, 0, {"date_start": "2020-01-01", "calendar_id": self.calendar2.id}),
]
self.assertTrue(self.employee.resource_calendar_id)
calendar = self.employee.resource_calendar_id
self.assertEqual(len(calendar.attendance_ids), 15)
self.assertEqual(
len(
calendar.attendance_ids.filtered(
lambda x: x.date_from == fields.Date.to_date("2020-01-01")
)
),
5,
)
self.assertEqual(
len(
calendar.attendance_ids.filtered(
lambda x: x.date_to == fields.Date.to_date("2019-12-31")
)
),
10,
)
# Change one line
calendar_line = self.employee.calendar_ids[0]
calendar_line.date_end = "2019-12-30"
calendar = self.employee.resource_calendar_id
self.assertEqual(
len(
calendar.attendance_ids.filtered(
lambda x: x.date_to == fields.Date.to_date("2019-12-30")
)
),
10,
)
calendar_line.unlink()
self.assertEqual(
len(
calendar.attendance_ids.filtered(
lambda x: x.date_to == fields.Date.to_date("2019-12-30")
)
),
0,
)
self.assertEqual(len(calendar.attendance_ids), 5)
self.calendar2.write(
{
"attendance_ids": [
(
0,
0,
{
"name": "Attendance",
"dayofweek": "6",
"hour_from": "08",
"hour_to": "12",
},
)
],
}
)
self.assertEqual(len(calendar.attendance_ids), 6)
# 2 week calendars
self.employee.calendar_ids = [
(0, 0, {"date_end": "2019-12-31", "calendar_id": self.calendar1.id})
]
self.calendar1.switch_calendar_type()
self.assertTrue(self.employee.resource_calendar_id.two_weeks_calendar)
# Calendar 1 has 20 lines + Calendar 2 has 6 lines that are duplicated
# in the odd and even week + even week label + odd week label
self.assertEqual(
len(self.employee.resource_calendar_id.attendance_ids), 20 + 6 * 2 + 2
)
def test_calendar_planning_two_weeks(self):
self.calendar1.switch_calendar_type()
self.employee.calendar_ids = [
(0, 0, {"date_end": "2019-12-31", "calendar_id": self.calendar1.id}),
(0, 0, {"date_start": "2020-01-01", "calendar_id": self.calendar2.id}),
]
self.assertEqual(
len(self.employee.resource_calendar_id.attendance_ids), 20 + 5 * 2 + 2
)
items = self.employee.resource_calendar_id.attendance_ids
items_with_sections = items.filtered(lambda x: x.display_type)
self.assertEqual(len(items_with_sections), 2)
items_date_to = items.filtered(
lambda x: x.date_to == fields.Date.to_date("2019-12-31")
)
self.assertEqual(len(items_date_to), 20)
self.assertEqual(len(items_date_to.filtered(lambda x: x.week_type == "0")), 10)
self.assertEqual(len(items_date_to.filtered(lambda x: x.week_type == "1")), 10)
items_date_from = items.filtered(
lambda x: x.date_from == fields.Date.to_date("2020-01-01")
)
self.assertEqual(len(items_date_from), 10)
self.assertEqual(len(items_date_from.filtered(lambda x: x.week_type == "0")), 5)
self.assertEqual(len(items_date_from.filtered(lambda x: x.week_type == "1")), 5)
items_without_sections = items - items_with_sections
self.assertEqual(
len(items_without_sections.filtered(lambda x: x.week_type == "0")), 10 + 5
)
self.assertEqual(
len(items_without_sections.filtered(lambda x: x.week_type == "1")), 10 + 5
)
self.calendar2.switch_calendar_type()
items = self.employee.resource_calendar_id.attendance_ids
items_with_sections = items.filtered(lambda x: x.display_type)
items_without_sections = items - items_with_sections
self.assertEqual(len(items), 20 + 20 + 2)
self.assertEqual(len(items_with_sections), 2)
items_date_to = items.filtered(
lambda x: x.date_to == fields.Date.to_date("2019-12-31")
)
self.assertEqual(len(items_date_to), 20)
items_date_from = items.filtered(
lambda x: x.date_from == fields.Date.to_date("2020-01-01")
)
self.assertEqual(len(items_date_from), 20)
items_week_0 = items_without_sections.filtered(lambda x: x.week_type == "0")
self.assertEqual(len(items_week_0), 10 + 10)
self.assertEqual(
len(
items_week_0.filtered(
lambda x: x.date_to == fields.Date.to_date("2019-12-31")
)
),
5 + 5,
)
self.assertEqual(
len(
items_week_0.filtered(
lambda x: x.date_from == fields.Date.to_date("2020-01-01")
)
),
5 + 5,
)
items_week_1 = items_without_sections.filtered(lambda x: x.week_type == "1")
self.assertEqual(len(items_week_1), 10 + 10)
self.assertEqual(
len(
items_week_1.filtered(
lambda x: x.date_to == fields.Date.to_date("2019-12-31")
)
),
5 + 5,
)
self.assertEqual(
len(
items_week_1.filtered(
lambda x: x.date_from == fields.Date.to_date("2020-01-01")
)
),
5 + 5,
)
def test_calendar_planning_two_weeks_multi(self):
self.calendar1.switch_calendar_type()
self.calendar2.switch_calendar_type()
self.employee.calendar_ids = [
(0, 0, {"date_end": "2019-12-31", "calendar_id": self.calendar1.id}),
(
0,
0,
{
"date_start": "2020-01-01",
"date_end": "2020-01-31",
"calendar_id": self.calendar2.id,
},
),
(
0,
0,
{
"date_start": "2020-02-01",
"date_end": "2020-02-02",
"calendar_id": self.calendar1.id,
},
),
(0, 0, {"date_start": "2020-01-03", "calendar_id": self.calendar2.id}),
]
items = self.employee.resource_calendar_id.attendance_ids
items_with_sections = items.filtered(lambda x: x.display_type)
items_without_sections = items - items_with_sections
self.assertEqual(len(items), (20 * 2) + (20 * 2) + 2)
self.assertEqual(len(items_with_sections), 2)
items_week_0 = items_without_sections.filtered(lambda x: x.week_type == "0")
self.assertEqual(
len(
items_week_0.filtered(
lambda x: x.date_to == fields.Date.to_date("2019-12-31")
)
),
10,
)
self.assertEqual(
len(
items_week_0.filtered(
lambda x: x.date_to == fields.Date.to_date("2020-01-31")
)
),
10,
)
self.assertEqual(
len(
items_week_0.filtered(
lambda x: x.date_to == fields.Date.to_date("2020-02-02")
)
),
10,
)
self.assertEqual(
len(
items_week_0.filtered(
lambda x: x.date_from == fields.Date.to_date("2020-01-03")
)
),
10,
)
self.assertEqual(len(items_week_0), 20 + 20)
items_week_1 = items_without_sections.filtered(lambda x: x.week_type == "1")
self.assertEqual(len(items_week_0), len(items_week_1))
def test_post_install_hook(self):
self.employee.resource_calendar_id = self.calendar1.id
post_init_hook(self.env.cr, self.env.registry, self.employee)
self.assertNotEqual(self.employee.resource_calendar_id, self.calendar1)
# Check that no change is done on original calendar
self.assertEqual(len(self.calendar1.attendance_ids), 10)
self.assertEqual(len(self.employee.calendar_ids), 1)
self.assertFalse(self.employee.calendar_ids.date_start)
self.assertFalse(self.employee.calendar_ids.date_end)
# Check that the employee leaves are transferred to the new calendar
# And that global leaves remain untouched
self.assertEqual(
self.calendar1.leave_ids, self.global_leave1 + self.global_leave2
)
self.assertTrue(
self.leave1.id in self.employee.resource_calendar_id.leave_ids.ids
)
# Test that global leaves are copied to the autogenerated calendar on post install hook
self.assertEqual(
{
global_leave.name
for global_leave in self.employee.resource_calendar_id.global_leave_ids
},
{"Global Leave 1", "Global Leave 2"},
)
def test_post_install_hook_several_calendaries(self):
self.calendar1.attendance_ids[0].date_from = "2019-01-01"
self.calendar1.attendance_ids[1].date_from = "2019-01-01"
self.employee.resource_calendar_id = self.calendar1.id
post_init_hook(self.env.cr, self.env.registry, self.employee)
self.assertNotEqual(self.employee.resource_calendar_id, self.calendar1)
# Check that no change is done on original calendar
self.assertEqual(len(self.calendar1.attendance_ids), 10)
self.assertEqual(len(self.employee.calendar_ids), 2)
self.assertEqual(
len(self.employee.calendar_ids[0].calendar_id.attendance_ids),
2,
)
self.assertEqual(
len(self.employee.calendar_ids[1].calendar_id.attendance_ids),
8,
)
def test_resource_calendar_constraint(self):
self.employee.calendar_ids = [
(0, 0, {"date_end": "2019-12-31", "calendar_id": self.calendar1.id})
]
with self.assertRaises(exceptions.ValidationError):
self.calendar1.write({"active": False})
self.employee.write({"calendar_ids": [(2, self.employee.calendar_ids.id)]})
self.calendar1.write({"active": False})
self.assertFalse(self.calendar1.active)
def test_resource_calendar_constraint_company_id(self):
main_company = self.env.ref("base.main_company")
self.calendar1.company_id = main_company
self.employee.company_id = main_company
self.employee.calendar_ids = [
(0, 0, {"date_end": "2019-12-31", "calendar_id": self.calendar1.id})
]
company2 = self.env["res.company"].create({"name": "Test company"})
with self.assertRaises(exceptions.ValidationError):
self.calendar1.company_id = company2
def test_employee_with_calendar_ids(self):
employee = self.env["hr.employee"].create(
{
"name": "Test employee",
"calendar_ids": [
(
0,
0,
{"date_start": "2020-01-01", "calendar_id": self.calendar2.id},
),
],
}
)
self.assertTrue(employee.resource_calendar_id.auto_generate)
def test_copy_global_leaves(self):
# test that global leaves are combined from calendar_ids
global_leave_ids_cal1 = self.calendar1.global_leave_ids.ids
# self.employee.calendar_ids.unlink()
self.employee.calendar_ids = [
(0, 0, {"date_end": "2020-03-03", "calendar_id": self.calendar1.id}),
(0, 0, {"date_start": "2020-03-03", "calendar_id": self.calendar2.id}),
]
self.assertEqual(
{
global_leave.name
for global_leave in self.employee.resource_calendar_id.global_leave_ids
},
{"Global Leave 1", "Global Leave 3"},
)
# test that global leaves on original calendar are not changed
self.assertEqual(global_leave_ids_cal1, self.calendar1.global_leave_ids.ids)
def test_employee_copy(self):
self.employee.calendar_ids = [
(0, 0, {"date_end": "2019-12-31", "calendar_id": self.calendar1.id}),
(0, 0, {"date_start": "2020-01-01", "calendar_id": self.calendar2.id}),
]
self.assertTrue(self.employee.resource_calendar_id)
self.assertTrue(self.employee.resource_calendar_id.auto_generate)
employee2 = self.employee.copy()
self.assertIn(self.calendar1, employee2.mapped("calendar_ids.calendar_id"))
self.assertIn(self.calendar2, employee2.mapped("calendar_ids.calendar_id"))
self.assertTrue(employee2.resource_calendar_id)
self.assertTrue(employee2.resource_calendar_id.auto_generate)
self.assertNotEqual(
self.employee.resource_calendar_id, employee2.resource_calendar_id
)
def test_user_action_create_employee(self):
user = new_test_user(self.env, login="test-user")
user.action_create_employee()
self.assertIn(
user.company_id.resource_calendar_id,
user.employee_id.mapped("calendar_ids.calendar_id"),
)
| 38.969163
| 17,692
|
2,539
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Pedro M. Baeza
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ResourceCalendar(models.Model):
_inherit = "resource.calendar"
active = fields.Boolean(default=True)
auto_generate = fields.Boolean()
employee_calendar_ids = fields.One2many("hr.employee.calendar", "calendar_id")
@api.constrains("active")
def _check_active(self):
for item in self:
total_items = self.env["hr.employee.calendar"].search_count(
[
("calendar_id", "=", item.id),
"|",
("date_end", "=", False),
("date_end", "<=", fields.Date.today()),
]
)
if total_items:
raise ValidationError(
_(
"%(item_name)s is used in %(total_items)s employee(s)."
"You should change them first.",
item_name=item.name,
total_items=total_items,
)
)
@api.constrains("company_id")
def _check_company_id(self):
for item in self.filtered("company_id"):
total_items = self.env["hr.employee.calendar"].search_count(
[
("calendar_id.company_id", "=", item.company_id.id),
("employee_id.company_id", "!=", item.company_id.id),
("employee_id.company_id", "!=", False),
]
)
if total_items:
raise ValidationError(
_(
"%(item_name)s is used in %(total_items)s employee(s)"
" related to another company.",
item_name=item.name,
total_items=total_items,
)
)
def write(self, vals):
res = super(ResourceCalendar, self).write(vals)
if "attendance_ids" in vals or "global_leave_ids" in vals:
for record in self.filtered(lambda x: not x.auto_generate):
calendars = self.env["hr.employee.calendar"].search(
[("calendar_id", "=", record.id)]
)
for employee in calendars.mapped("employee_id"):
employee._regenerate_calendar()
return res
| 38.439394
| 2,537
|
7,806
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Pedro M. Baeza
# Copyright 2022-2023 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools import config
SECTION_LINES = [
(
0,
0,
{
"name": "Even week",
"dayofweek": "0",
"sequence": "0",
"hour_from": 0,
"day_period": "morning",
"week_type": "0",
"hour_to": 0,
"display_type": "line_section",
},
),
(
0,
0,
{
"name": "Odd week",
"dayofweek": "0",
"sequence": "25",
"hour_from": 0,
"day_period": "morning",
"week_type": "1",
"hour_to": 0,
"display_type": "line_section",
},
),
]
class HrEmployee(models.Model):
_inherit = "hr.employee"
calendar_ids = fields.One2many(
comodel_name="hr.employee.calendar",
inverse_name="employee_id",
string="Calendar planning",
copy=True,
)
@api.model
def default_get(self, fields):
"""Set calendar_ids default value to cover all use cases."""
vals = super().default_get(fields)
if "calendar_ids" in fields and not vals.get("calendar_ids"):
vals["calendar_ids"] = [
(0, 0, {"calendar_id": self.env.company.resource_calendar_id.id}),
]
return vals
def _regenerate_calendar(self):
self.ensure_one()
vals_list = []
two_weeks = bool(
self.calendar_ids.mapped("calendar_id").filtered("two_weeks_calendar")
)
if self.resource_id.calendar_id.auto_generate:
self.resource_calendar_id.attendance_ids.unlink()
self.resource_calendar_id.two_weeks_calendar = two_weeks
seq = 0
for week in ["0", "1"] if two_weeks else ["0"]:
if two_weeks:
section_vals = SECTION_LINES[int(week)]
section_vals[2]["sequence"] = seq
vals_list.append(section_vals)
seq += 1
for line in self.calendar_ids:
if line.calendar_id.two_weeks_calendar:
attendances = line.calendar_id.attendance_ids.filtered(
lambda x: x.week_type == week
)
else:
attendances = line.calendar_id.attendance_ids
for attendance_line in attendances:
if attendance_line.display_type == "line_section":
continue
data = attendance_line.copy_data(
{
"calendar_id": self.resource_calendar_id.id,
"date_from": line.date_start,
"date_to": line.date_end,
"week_type": week if two_weeks else False,
"sequence": seq,
}
)[0]
seq += 1
vals_list.append((0, 0, data))
# Autogenerate
if not self.resource_id.calendar_id.auto_generate:
self.resource_id.calendar_id = (
self.env["resource.calendar"]
.create(
{
"active": False,
"company_id": self.company_id.id,
"auto_generate": True,
"name": _("Auto generated calendar for employee")
+ " %s" % self.name,
"attendance_ids": vals_list,
"two_weeks_calendar": two_weeks,
"tz": self.tz, # take employee timezone as default
}
)
.id
)
else:
self.resource_calendar_id.attendance_ids = vals_list
# Set the hours per day to the last (top date end) calendar line to apply
if self.calendar_ids:
self.resource_id.calendar_id.hours_per_day = self.calendar_ids[
0
].calendar_id.hours_per_day
# set global leaves
self.resource_id.calendar_id.global_leave_ids = [
(
6,
0,
self.copy_global_leaves(),
)
]
def copy_global_leaves(self):
self.ensure_one()
leave_ids = []
for calendar in self.calendar_ids:
global_leaves = calendar.calendar_id.global_leave_ids
if calendar.date_start:
global_leaves = global_leaves.filtered(
lambda x: x.date_from.date() >= calendar.date_start
)
if calendar.date_end:
global_leaves = global_leaves.filtered(
lambda x: x.date_to.date() <= calendar.date_end
)
leave_ids += global_leaves.ids
vals = [
leave.copy_data({})[0]
for leave in self.env["resource.calendar.leaves"].browse(leave_ids)
]
return self.env["resource.calendar.leaves"].create(vals).ids
def regenerate_calendar(self):
for item in self:
item._regenerate_calendar()
def copy(self, default=None):
self.ensure_one()
new = super().copy(default)
# Define a good main calendar for being able to regenerate it later
new.resource_id.calendar_id = fields.first(new.calendar_ids).calendar_id
new.filtered("calendar_ids").regenerate_calendar()
return new
@api.model_create_multi
def create(self, vals_list):
res = super().create(vals_list)
# Avoid creating an employee without calendars
if (
not self.env.context.get("skip_employee_calendars_required")
and not config["test_enable"]
and not self.env.context.get("install_mode")
and res.filtered(lambda x: not x.calendar_ids)
):
raise UserError(_("You can not create employees without any calendar."))
res.filtered("calendar_ids").regenerate_calendar()
return res
class HrEmployeeCalendar(models.Model):
_name = "hr.employee.calendar"
_description = "Employee Calendar"
_order = "date_end desc"
date_start = fields.Date(
string="Start Date",
)
date_end = fields.Date(
string="End Date",
)
employee_id = fields.Many2one(
comodel_name="hr.employee", string="Employee", required=True, ondelete="cascade"
)
company_id = fields.Many2one(related="employee_id.company_id")
calendar_id = fields.Many2one(
comodel_name="resource.calendar",
string="Working Time",
required=True,
check_company=True,
ondelete="restrict",
)
_sql_constraints = [
(
"date_consistency",
"CHECK(date_start <= date_end)",
"Date end should be higher than date start",
),
]
@api.model_create_multi
def create(self, vals):
record = super(HrEmployeeCalendar, self).create(vals)
record.employee_id._regenerate_calendar()
return record
def write(self, vals):
res = super(HrEmployeeCalendar, self).write(vals)
for employee in self.mapped("employee_id"):
employee._regenerate_calendar()
return res
def unlink(self):
employees = self.mapped("employee_id")
res = super(HrEmployeeCalendar, self).unlink()
for employee in employees:
employee._regenerate_calendar()
return res
| 34.378855
| 7,804
|
733
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Brainbean Apps (https://brainbeanapps.com)
# Copyright 2020 CorporateHub (https://corporatehub.eu)
# Copyright 2020 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "HR Employee Document",
"version": "15.0.1.0.0",
"category": "Human Resources",
"website": "https://github.com/OCA/hr",
"author": "CorporateHub, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"application": False,
"summary": "Documents attached to the employee profile",
"depends": ["hr"],
"data": [
"security/security.xml",
"views/hr_employee.xml",
"views/hr_employee_public.xml",
],
}
| 33.227273
| 731
|
3,361
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Brainbean Apps (https://brainbeanapps.com)
# Copyright 2021-2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import base64
from odoo.tests import common, new_test_user
from odoo.tests.common import users
class TestHrEmployeeDocument(common.TransactionCase):
def setUp(self):
super().setUp()
ctx = {
"mail_create_nolog": True,
"mail_create_nosubscribe": True,
"mail_notrack": True,
"no_reset_password": True,
}
self.user_1 = new_test_user(self.env, login="test-user-1", context=ctx)
self.user_2 = new_test_user(self.env, login="test-user-2", context=ctx)
new_test_user(
self.env, login="test-user-manager", groups="hr.group_hr_user", context=ctx
)
self.employee_1 = self.env["hr.employee"].create(
{"name": "Employee #1", "user_id": self.user_1.id}
)
self.employee_2 = self.env["hr.employee"].create(
{"name": "Employee #2", "user_id": self.user_2.id}
)
def _create_attachment(self, employee_id):
return (
self.env["ir.attachment"]
.sudo()
.create(
{
"res_model": employee_id._name,
"res_id": employee_id.id,
"datas": base64.b64encode(b"My attachment"),
"name": "doc.txt",
}
)
)
@users("test-user-1")
def test_employee_attachment(self):
employee = self.env.user.employee_id
self._create_attachment(employee)
self.assertEqual(employee.document_count, 1)
employee_public = self.env["hr.employee.public"].browse(employee.id)
self.assertEqual(employee_public.document_count, 1)
@users("test-user-2")
def test_employee_attachment_tree_view(self):
employee = self.env.user.employee_id
self.assertNotEqual(employee.action_get_attachment_tree_view(), None)
employee_public = self.env["hr.employee.public"].browse(employee.id)
self.assertNotEqual(employee_public.action_get_attachment_tree_view(), None)
@users("test-user-1")
def test_attachments_access_user_1(self):
# create attachments
attachment_1 = self._create_attachment(self.employee_1)
attachment_2 = self._create_attachment(self.employee_2)
records = self.env["ir.attachment"].search([])
self.assertIn(attachment_1, records)
self.assertNotIn(attachment_2, records)
@users("test-user-2")
def test_attachments_access_user_2(self):
# create attachments
attachment_1 = self._create_attachment(self.employee_1)
attachment_2 = self._create_attachment(self.employee_2)
records = self.env["ir.attachment"].search([])
self.assertNotIn(attachment_1, records)
self.assertIn(attachment_2, records)
@users("test-user-manager")
def test_attachments_access_user_manager(self):
# create attachments
attachment_1 = self._create_attachment(self.employee_1)
attachment_2 = self._create_attachment(self.employee_2)
records = self.env["ir.attachment"].search([])
self.assertIn(attachment_1, records)
self.assertIn(attachment_2, records)
| 39.05814
| 3,359
|
1,094
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class HrEmployeePublic(models.Model):
_inherit = "hr.employee.public"
is_logged = fields.Boolean(compute="_compute_is_logged", store=False)
def _compute_is_logged(self):
self.is_logged = False
for record in self:
if self.env.user == record.user_id:
record.is_logged = True
def action_get_attachment_tree_view(self):
action = self.env["ir.actions.act_window"]._for_xml_id("base.action_attachment")
action["context"] = {
"default_res_model": "hr.employee",
"default_res_id": self.env.user.employee_id.id,
}
action["domain"] = str(
[
("res_model", "=", "hr.employee"),
("res_id", "=", self.env.user.employee_id.id),
]
)
action["search_view_id"] = (
self.env.ref("hr_employee_document.ir_attachment_view_search").id,
)
return action
| 33.090909
| 1,092
|
1,299
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class HrEmployeeBase(models.AbstractModel):
_inherit = "hr.employee.base"
document_count = fields.Integer(
compute="_compute_document_count",
)
def _compute_document_count(self):
self.document_count = 0
attachment_groups = self.env["ir.attachment"].read_group(
[("res_model", "=", "hr.employee"), ("res_id", "in", self.ids)],
["res_id"],
["res_id"],
)
count_dict = {x["res_id"]: x["res_id_count"] for x in attachment_groups}
for record in self:
record.document_count = count_dict.get(record.id, 0)
def action_get_attachment_tree_view(self):
action = self.env["ir.actions.act_window"]._for_xml_id("base.action_attachment")
action["context"] = {
"default_res_model": self._name,
"default_res_id": self.ids[0],
}
action["domain"] = str(
[("res_model", "=", self._name), ("res_id", "in", self.ids)]
)
action["search_view_id"] = (
self.env.ref("hr_employee_document.ir_attachment_view_search").id,
)
return action
| 35.108108
| 1,299
|
592
|
py
|
PYTHON
|
15.0
|
# copyright 2017 Denis Leemann, Camptocamp SA
# Copyright (C) 2021 Open Source Integrators
# Copyright (C) 2021 Serpent Consulting Services
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Employee Birth Name",
"version": "15.0.1.0.1",
"category": "Human Resources",
"author": "Camptocamp SA,Odoo Community Association (OCA),"
"Open Source Integrators",
"website": "https://github.com/OCA/hr",
"license": "AGPL-3",
"depends": ["hr"],
"data": ["views/hr_employee_view.xml"],
"installable": True,
"auto_install": False,
}
| 32.888889
| 592
|
358
|
py
|
PYTHON
|
15.0
|
# copyright 2017 Denis Leemann, Camptocamp SA
# Copyright (C) 2021 Open Source Integrators
# Copyright (C) 2021 Serpent Consulting Services
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
birth_name = fields.Char(groups="hr.group_hr_user")
| 29.833333
| 358
|
594
|
py
|
PYTHON
|
15.0
|
# copyright 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>
# copyright 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "HR Emergency Contact",
"version": "15.0.1.0.0",
"category": "Generic Modules/Human Resources",
"author": "OpenSynergy Indonesia,Michael Telahun Makonnen,"
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"license": "AGPL-3",
"depends": [
"hr",
],
"data": [
"views/hr_employee_views.xml",
],
"installable": True,
}
| 29.7
| 594
|
514
|
py
|
PYTHON
|
15.0
|
# copyright 2011 Michael Telahun Makonnen <mmakonnen@gmail.com>
# copyright 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
emergency_contact_ids = fields.Many2many(
comodel_name="res.partner",
string="Emergency Contacts",
relation="rel_employee_emergency_contact",
domain=[
("is_company", "=", False),
],
)
| 27.052632
| 514
|
823
|
py
|
PYTHON
|
15.0
|
# Copyright 2011, 2013 Michael Telahun Makonnen <mmakonnen@gmail.com>
# Copyright 2016 OpenSynergy Indonesia
# Copyright 2018 Brainbean Apps (https://brainbeanapps.com)
# Copyright 2020 CorporateHub (https://corporatehub.eu)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Employee ID",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"category": "Generic Modules/Human Resources",
"author": "CorporateHub, "
"Michael Telahun Makonnen, "
"OpenSynergy Indonesia, "
"Camptocamp, "
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"depends": ["hr"],
"data": [
"data/hr_employee_sequence.xml",
"views/hr_employee_views.xml",
"views/res_config_settings_views.xml",
],
"installable": True,
}
| 34.291667
| 823
|
5,629
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Salton Massally <smassally@idtlabs.sl>
# Copyright 2016 OpenSynergy Indonesia
# Copyright 2018 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
class TestEmployeeID(common.TransactionCase):
def setUp(self):
super(TestEmployeeID, self).setUp()
self.employee_model = self.env["hr.employee"]
self.company = self.env.ref("base.main_company")
self.sequence = self.env.ref("hr_employee_id.seq_hr_employee_id")
def test_random_id_generation(self):
# test ID generation for random
employee = self.employee_model.create({"name": "Employee"})
self.assertAlmostEqual(len(employee.identification_id), 5)
def test_random_id_generation_changed_digits(self):
# test ID generation for random but with defaults changed
self.company.write({"employee_id_random_digits": 10})
employee = self.employee_model.create({"name": "Employee"})
self.assertAlmostEqual(len(employee.identification_id), 10)
def test_sequences_id_generation(self):
# test ID generation for a provided sequence
self.company.write(
{
"employee_id_gen_method": "sequence",
"employee_id_sequence": self.sequence.id,
}
)
employee = self.employee_model.create({"name": "Employee"})
self.assertTrue(len(employee.identification_id))
def test_no_sequences_id_generation(self):
# test ID generation for a provided sequence
self.company.write({"employee_id_gen_method": "sequence"})
employee = self.employee_model.create({"name": "Employee"})
self.assertEqual(employee.identification_id, False)
def test_custom_id(self):
# if we pass the ID no generation occurs.
# Let's set a sequence and check that is not used at all
self.company.write(
{
"employee_id_gen_method": "sequence",
"employee_id_sequence": self.sequence.id,
}
)
number = self.sequence.number_next
employee = self.employee_model.create(
{"name": "Employee", "identification_id": "THERE_YOU_GO"}
)
self.assertEqual(employee.identification_id, "THERE_YOU_GO")
self.assertEqual(self.sequence.number_next, number)
def test_configuration_default_values(self):
# test loading of default configuration values
self.company.write(
self.company.default_get(
[
"employee_id_gen_method",
"employee_id_random_digits",
"employee_id_sequence",
]
)
)
config_model = self.env["res.config.settings"]
config = config_model.create({})
self.assertTrue(config.company_id.id == self.company.id)
self.assertTrue(config.employee_id_gen_method == "random")
self.assertTrue(config.employee_id_random_digits == 5)
self.assertFalse(config.employee_id_sequence is False)
def test_configuration_set_default_values(self):
"""test loading of default values when the company fields are empty"""
company = self.env.company
company.employee_id_gen_method = False
company.employee_id_random_digits = False
config_model = self.env["res.config.settings"]
config = config_model.create({})
self.assertEqual(config.employee_id_gen_method, "random")
self.assertEqual(config.employee_id_random_digits, 5)
def test_multi_company_res_config(self):
"""Test different values for different companies."""
DIGITS2 = 12
METHOD2 = "sequence"
Settings = self.env["res.config.settings"]
company = self.env.company
fields = list(Settings.fields_get())
# Settings for first company
vals1 = self.company.default_get(
[
"employee_id_gen_method",
"employee_id_random_digits",
"employee_id_sequence",
]
)
vals1.update({"employee_id_random_digits": 6})
Settings.create(vals1).execute()
# Set company 2 as main company
company2 = self.env["res.company"].create({"name": "oobO"})
self.env.user.write(
{"company_ids": [(4, self.company.id)], "company_id": company2.id}
)
# Set company 2 settings and read them back
#
sequence2 = (
self.env["ir.sequence"]
.with_company(company2.id)
.create({"name": "EE ID2", "code": "hr.employee.id2"})
)
self.assertEqual(sequence2.company_id.id, company2.id)
vals2 = {
"employee_id_random_digits": DIGITS2,
"employee_id_gen_method": METHOD2,
"employee_id_sequence": sequence2.id,
}
Settings.create(vals2).execute()
res2 = Settings.default_get(fields)
# Change back to first company and read its settings
self.env.user.write({"company_id": company.id})
res1 = Settings.default_get(fields)
self.assertNotEqual(res1["employee_id_random_digits"], DIGITS2)
self.assertNotEqual(res1["employee_id_gen_method"], METHOD2)
self.assertNotEqual(res1["employee_id_sequence"], sequence2.id)
self.assertEqual(res2["employee_id_random_digits"], DIGITS2)
self.assertEqual(res2["employee_id_gen_method"], METHOD2)
self.assertEqual(res2["employee_id_sequence"], sequence2.id)
| 38.292517
| 5,629
|
875
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Salton Massally <smassally@idtlabs.sl>
# Copyright 2016 OpenSynergy Indonesia
# Copyright 2018 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
employee_id_gen_method = fields.Selection(
selection=[
("random", "Random"),
("sequence", "Sequence"),
],
string="Generation Method",
default="random",
)
employee_id_random_digits = fields.Integer(
string="# of Digits", default=5, help="Number of digits in employee identifier"
)
employee_id_sequence = fields.Many2one(
comodel_name="ir.sequence",
string="Identifier Sequence",
help="Pattern to be used for employee identifier generation",
)
| 32.407407
| 875
|
2,194
|
py
|
PYTHON
|
15.0
|
# Copyright 2011, 2013 Michael Telahun Makonnen <mmakonnen@gmail.com>
# Copyright 2016 OpenSynergy Indonesia
# Copyright 2018 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
import random
import string
from odoo import _, api, fields, models
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
class HrEmployee(models.Model):
"""Implement company wide unique identification number."""
_inherit = "hr.employee"
identification_id = fields.Char(string="Identification No", copy=False)
_sql_constraints = [
(
"identification_id_uniq",
"unique(identification_id)",
"The Employee Number must be unique across the company(s).",
),
]
@api.model
def _generate_identification_id(self):
"""Generate a random employee identification number"""
company = self.env.user.company_id
steps = 0
for _retry in range(50):
employee_id = False
if company.employee_id_gen_method == "sequence":
if not company.employee_id_sequence:
_logger.warning("No sequence configured for employee ID generation")
return employee_id
employee_id = company.employee_id_sequence.next_by_id()
elif company.employee_id_gen_method == "random":
employee_id_random_digits = company.employee_id_random_digits
rnd = random.SystemRandom()
employee_id = "".join(
rnd.choice(string.digits) for x in range(employee_id_random_digits)
)
if self.search_count([("identification_id", "=", employee_id)]):
steps += 1
continue
return employee_id
raise UserError(
_("Unable to generate unique Employee ID in %d steps.") % (steps,)
)
@api.model
def create(self, vals):
if not vals.get("identification_id"):
vals["identification_id"] = self._generate_identification_id()
return super(HrEmployee, self).create(vals)
| 33.753846
| 2,194
|
1,795
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Salton Massally <smassally@idtlabs.sl>
# Copyright 2016 OpenSynergy Indonesia
# Copyright 2018 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
employee_id_gen_method = fields.Selection(
related="company_id.employee_id_gen_method",
readonly=False,
default=lambda self: self._default_id_gen_method(),
)
employee_id_random_digits = fields.Integer(
related="company_id.employee_id_random_digits",
readonly=False,
default=lambda self: self._default_id_random_digits(),
)
employee_id_sequence = fields.Many2one(
"ir.sequence",
related="company_id.employee_id_sequence",
readonly=False,
default=lambda self: self._default_id_sequence(),
)
def _default_id_gen_method(self):
gen_method = self.env.user.company_id.employee_id_gen_method
if not gen_method:
gen_method = self.env["res.company"].default_get(
["employee_id_gen_method"]
)["employee_id_gen_method"]
return gen_method
def _default_id_random_digits(self):
digits = self.env.user.company_id.employee_id_random_digits
if not digits:
digits = self.env["res.company"].default_get(["employee_id_random_digits"])[
"employee_id_random_digits"
]
return digits
def _default_id_sequence(self):
sequence = self.env.user.company_id.employee_id_sequence
if not sequence:
sequence = self.env.ref("hr_employee_id.seq_hr_employee_id")
return sequence and sequence.id or False
| 36.632653
| 1,795
|
492
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "HR Holidays Settings",
"summary": "Enables Settings Form for HR Holidays.",
"version": "15.0.1.0.0",
"category": "Human Resources",
"website": "https://github.com/OCA/hr",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["hr_holidays"],
"data": ["views/res_config_settings.xml"],
"installable": True,
}
| 35.142857
| 492
|
709
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Brainbean Apps (https://brainbeanapps.com)
# Copyright 2020 CorporateHub (https://corporatehub.eu)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "HR Employee Service from Contracts",
"version": "15.0.1.0.0",
"category": "Human Resources",
"website": "https://github.com/OCA/hr",
"author": "CorporateHub, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"application": False,
"summary": (
"Employee service information & duration based on employee's contracts"
),
"depends": ["hr", "hr_contract", "hr_employee_service"],
"external_dependencies": {"python": ["dateutil"]},
}
| 37.315789
| 709
|
4,934
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.tests import common
class TestHrEmployeeService(common.TransactionCase):
def setUp(self):
super().setUp()
self.today = fields.Date.today()
self.now = fields.Datetime.now()
self.Employee = self.env["hr.employee"]
self.SudoEmployee = self.Employee.sudo()
self.Contract = self.env["hr.contract"]
self.SudoContract = self.Contract.sudo()
def test_1(self):
employee = self.SudoEmployee.create(
{
"name": "Employee #1",
"contract_ids": [
(
0,
0,
{
"name": "Employee #1 Contract #1",
"wage": 5000.0,
"state": "close",
"date_start": self.today - relativedelta(years=3),
"date_end": self.today - relativedelta(years=1),
},
)
],
}
)
self.assertEqual(
employee.service_start_date, self.today - relativedelta(years=3)
)
self.assertEqual(
employee.service_termination_date, self.today - relativedelta(years=1)
)
def test_2(self):
employee = self.SudoEmployee.create(
{
"name": "Employee #2",
"contract_ids": [
(
0,
0,
{
"name": "Employee #2 Contract #1",
"wage": 5000.0,
"state": "open",
"date_start": self.today - relativedelta(years=3),
},
)
],
}
)
self.assertEqual(
employee.service_start_date, self.today - relativedelta(years=3)
)
self.assertEqual(employee.service_termination_date, False)
def test_3(self):
employee = self.SudoEmployee.create(
{
"name": "Employee #3",
"contract_ids": [
(
0,
0,
{
"name": "Employee #3 Contract #1",
"wage": 5000.0,
"state": "close",
"date_start": self.today - relativedelta(years=5),
"date_end": self.today - relativedelta(years=1),
},
),
(
0,
0,
{
"name": "Employee #3 Contract #2",
"wage": 5000.0,
"state": "open",
"date_start": self.today - relativedelta(months=6),
},
),
],
}
)
self.assertEqual(
employee.service_start_date, self.today - relativedelta(years=5)
)
self.assertEqual(employee.service_termination_date, False)
def test_4(self):
employee = self.SudoEmployee.create(
{
"name": "Employee #4",
"contract_ids": [
(
0,
0,
{
"name": "Employee #4 Contract #1",
"wage": 5000.0,
"state": "close",
"date_start": self.today - relativedelta(years=5),
"date_end": self.today - relativedelta(years=1),
},
),
(
0,
0,
{
"name": "Employee #4 Contract #2",
"wage": 5000.0,
"state": "close",
"date_start": self.today - relativedelta(months=6),
},
),
],
}
)
self.assertEqual(
employee.service_start_date, self.today - relativedelta(years=5)
)
self.assertEqual(employee.service_termination_date, False)
def test_5(self):
employee = self.SudoEmployee.create({"name": "Employee #5"})
self.assertEqual(employee.service_start_date, False)
self.assertEqual(employee.service_termination_date, False)
| 33.794521
| 4,934
|
2,185
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
first_contract_id = fields.Many2one(
"hr.contract",
compute="_compute_first_contract_id",
store=True,
prefetch=False,
string="First Contract",
help="First contract of the employee",
)
last_contract_id = fields.Many2one(
"hr.contract",
compute="_compute_last_contract_id",
store=True,
prefetch=False,
string="Last Contract",
help="Last contract of the employee",
)
service_start_date = fields.Date(
string="Start Date",
readonly=True,
related="first_contract_id.date_start",
prefetch=False,
)
service_termination_date = fields.Date(
string="Termination Date",
readonly=True,
related="last_contract_id.date_end",
prefetch=False,
)
@api.depends("contract_ids", "contract_ids.state", "contract_ids.date_start")
def _compute_first_contract_id(self):
Contract = self.env["hr.contract"]
for employee in self:
employee.first_contract_id = Contract.search(
employee._get_contract_filter(), order="date_start asc", limit=1
)
@api.depends("contract_ids", "contract_ids.state", "contract_ids.date_end")
def _compute_last_contract_id(self):
Contract = self.env["hr.contract"]
for employee in self:
employee.last_contract_id = Contract.search(
employee._get_contract_filter(), order="date_end desc", limit=1
)
@api.onchange("service_hire_date")
def _onchange_service_hire_date(self): # pragma: no cover
# Do nothing
pass
def _get_contract_filter(self):
self.ensure_one()
return [
("employee_id", "=", self.id),
("state", "in", self._get_service_contract_states()),
]
@api.model
def _get_service_contract_states(self):
return ["open", "pending", "close"]
| 31.214286
| 2,185
|
475
|
py
|
PYTHON
|
15.0
|
# copyright 2013 Savoir-faire Linux (<http://www.savoirfairelinux.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Employee Phone Extension",
"version": "15.0.1.0.0",
"category": "Human Resources",
"author": "Savoir-faire Linux,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"license": "AGPL-3",
"depends": ["hr"],
"data": ["views/hr_employee_view.xml"],
"installable": True,
}
| 33.928571
| 475
|
427
|
py
|
PYTHON
|
15.0
|
# copyright 2013 Savoir-faire Linux (<http://www.savoirfairelinux.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class HrEmployee(models.Model):
"""Enhance the features of the employee using Number details."""
_inherit = "hr.employee"
internal_number = fields.Char(help="Internal phone number.")
short_number = fields.Char(help="Short phone number.")
| 32.846154
| 427
|
653
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2018 Brainbean Apps (https://brainbeanapps.com)
# Copyright 2020 CorporateHub (https://corporatehub.eu)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "HR Employee Service",
"version": "15.0.1.0.0",
"category": "Human Resources",
"website": "https://github.com/OCA/hr",
"author": "CorporateHub, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"application": False,
"summary": "Employee service information & duration",
"depends": ["hr"],
"external_dependencies": {"python": ["dateutil"]},
"data": ["views/hr_employee.xml"],
}
| 36.277778
| 653
|
4,497
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2018 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from datetime import date
from dateutil.relativedelta import relativedelta
from mock import patch
from odoo import fields
from odoo.tests import common
class TestHrEmployeeService(common.TransactionCase):
def setUp(self):
super().setUp()
self.today = fields.Date.today()
self.now = fields.Datetime.now()
self.Employee = self.env["hr.employee"]
self.SudoEmployee = self.Employee.sudo()
def test_1(self):
employee = self.SudoEmployee.create(
{
"name": "Employee #1",
"service_hire_date": (self.today - relativedelta(years=3)),
"service_start_date": (self.today - relativedelta(years=3)),
"departure_date": (self.today - relativedelta(years=1)),
}
)
self.assertEqual(employee.service_duration_years, 2)
self.assertEqual(employee.service_duration_months, 0)
self.assertEqual(employee.service_duration_days, 0)
def test_2(self):
employee = self.SudoEmployee.create(
{
"name": "Employee #2",
"service_hire_date": (self.today - relativedelta(years=3)),
"service_start_date": (self.today - relativedelta(years=3)),
}
)
self.assertEqual(employee.service_duration_years, 3)
self.assertEqual(employee.service_duration_months, 0)
self.assertEqual(employee.service_duration_days, 0)
def test_3(self):
mocked_today = date(2019, 8, 27)
employee = self.SudoEmployee.create(
{
"name": "Employee #3",
"service_hire_date": (mocked_today - relativedelta(months=6)),
"service_start_date": (mocked_today - relativedelta(months=6)),
}
)
with patch("odoo.fields.Date.today") as today:
today.return_value = mocked_today
self.assertEqual(employee.service_duration_years, 0)
self.assertEqual(employee.service_duration_months, 6)
self.assertEqual(employee.service_duration_days, 0)
def test_4(self):
employee = self.SudoEmployee.create(
{
"name": "Employee #4",
"service_hire_date": (self.today - relativedelta(months=6)),
}
)
self.assertEqual(employee.service_duration_years, 0)
self.assertEqual(employee.service_duration_months, 0)
self.assertEqual(employee.service_duration_days, 0)
def test_5(self):
employee = self.SudoEmployee.create(
{
"name": "Employee #5",
"service_hire_date": (self.today - relativedelta(days=1)),
"service_start_date": (self.today - relativedelta(days=1)),
}
)
self.assertEqual(employee.service_duration, 1)
self.assertEqual(employee.service_duration_days, 1)
def test_6(self):
employee = self.SudoEmployee.create(
{
"name": "Employee #6",
"service_hire_date": self.today,
"service_start_date": self.today,
}
)
employee.service_hire_date = None
employee.service_start_date = None
self.assertEqual(employee.service_duration_years, 0)
self.assertEqual(employee.service_duration_months, 0)
self.assertEqual(employee.service_duration_days, 0)
def test_7(self):
employee = self.SudoEmployee.create(
{
"name": "Employee #7",
"service_hire_date": (self.today - relativedelta(days=1)),
}
)
employee._onchange_service_hire_date()
self.assertEqual(employee.service_duration_years, 0)
self.assertEqual(employee.service_duration_months, 0)
self.assertEqual(employee.service_duration_days, 1)
def test_8(self):
employee = self.SudoEmployee.create(
{
"name": "Employee #8",
"service_hire_date": (self.today - relativedelta(days=1)),
"service_start_date": (self.today - relativedelta(days=1)),
"departure_date": (self.today - relativedelta(years=1)),
}
)
self.assertEqual(employee.service_duration, 0)
employee._get_date_start_work()
| 34.592308
| 4,497
|
3,810
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2018-2019 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import timedelta
from math import fabs
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
service_hire_date = fields.Date(
string="Hire Date",
groups="hr.group_hr_user",
tracking=True,
help=(
"Hire date is normally the date an employee completes new hire paperwork"
),
)
service_start_date = fields.Date(
string="Start Date",
groups="hr.group_hr_user",
tracking=True,
help=(
"Start date is the first day the employee actually works and"
" this date is used for accrual leave allocations calculation"
),
)
service_termination_date = fields.Date(
string="Termination Date",
related="departure_date",
help=(
"Termination date is the last day the employee actually works and"
" this date is used for accrual leave allocations calculation"
),
)
service_duration = fields.Integer(
groups="hr.group_hr_user",
readonly=True,
compute="_compute_service_duration",
help="Service duration in days",
)
service_duration_years = fields.Integer(
string="Service Duration (years)",
groups="hr.group_hr_user",
readonly=True,
compute="_compute_service_duration_display",
)
service_duration_months = fields.Integer(
string="Service Duration (months)",
groups="hr.group_hr_user",
readonly=True,
compute="_compute_service_duration_display",
)
service_duration_days = fields.Integer(
string="Service Duration (days)",
groups="hr.group_hr_user",
readonly=True,
compute="_compute_service_duration_display",
)
@api.depends("service_start_date", "service_termination_date")
def _compute_service_duration(self):
for record in self:
service_until = record.service_termination_date or fields.Date.today()
if record.service_start_date and service_until > record.service_start_date:
service_since = record.service_start_date
service_duration = fabs(
(service_until - service_since) / timedelta(days=1)
)
record.service_duration = int(service_duration)
else:
record.service_duration = 0
@api.depends("service_start_date", "service_termination_date")
def _compute_service_duration_display(self):
for record in self:
service_until = record.service_termination_date or fields.Date.today()
if record.service_start_date and service_until > record.service_start_date:
service_duration = relativedelta(
service_until, record.service_start_date
)
record.service_duration_years = service_duration.years
record.service_duration_months = service_duration.months
record.service_duration_days = service_duration.days
else:
record.service_duration_years = 0
record.service_duration_months = 0
record.service_duration_days = 0
@api.onchange("service_hire_date")
def _onchange_service_hire_date(self):
if not self.service_start_date:
self.service_start_date = self.service_hire_date
# NOTE: Support odoo/odoo@90731ad170c503cdfe89a9998fa1d1e2a5035c86
def _get_date_start_work(self):
return self.sudo().service_start_date or super()._get_date_start_work()
| 37.722772
| 3,810
|
481
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "HR department code",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"category": "Human Resources",
"author": "Ecosoft, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"depends": ["hr"],
"data": ["views/hr_department_views.xml"],
"installable": True,
"maintainer": ["Saran440"],
}
| 32.066667
| 481
|
1,193
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests.common import TransactionCase
class TestHrDepartmentCode(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.department_model = cls.env["hr.department"]
def create_department(self, name, code=False):
return self.department_model.create({"name": name, "code": code})
def test_name_get_department(self):
department1 = self.create_department("Department1")
self.assertEqual(department1.name, "Department1")
self.assertEqual(department1.name_get()[0][1], "Department1")
def test_name_search_department(self):
department2 = self.create_department("Department2", code="D2")
self.assertEqual(department2.name, "Department2")
self.assertEqual(department2.code, "D2")
self.assertEqual(department2.name_get()[0][1], "[D2] Department2")
check_method1 = department2.name_search(
name="D2", operator="ilike", args=[("id", "=", department2.id)]
)
self.assertEqual(check_method1[0][0], department2.id)
| 41.137931
| 1,193
|
867
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class Department(models.Model):
_inherit = "hr.department"
_order = "code, name"
code = fields.Char()
def name_get(self):
res = []
for dep in self:
name = dep.name
if dep.code:
name = ("[%(code)s] %(name)s") % {"code": dep.code, "name": name}
res.append((dep.id, name))
return res
@api.model
def name_search(self, name, args=None, operator="ilike", limit=100):
args = args or []
domain = []
if name:
domain = ["|", ("code", operator, name), ("name", operator, name)]
department = self.search(domain + args, limit=limit)
return department.name_get()
| 29.896552
| 867
|
2,653
|
py
|
PYTHON
|
15.0
|
import logging
from odoo import SUPERUSER_ID, api
_logger = logging.getLogger(__name__)
def post_init_hook(cr, registry, employees=None):
"""Migrate calendars from contracts to calendar_ids
to have consistent work schedule history"""
env = api.Environment(cr, SUPERUSER_ID, {})
if not employees:
employees = env["hr.employee"].with_context(active_test=False).search([])
for employee in employees.filtered("contract_ids"):
contract_calendar_lines = []
for contract in employee.contract_ids:
date_start = contract.date_start
date_end = contract.date_end
# filter calendar_ids to check for overlaps with contracts
# with the same work schedule
cal_ids = employee.calendar_ids.filtered(
lambda x: x.calendar_id == contract.resource_calendar_id
and (not x.date_start or not date_end or x.date_start < date_end)
and (not x.date_end or not date_start or x.date_end > date_start)
)
if cal_ids:
_logger.info(f"{contract} is overlapping with {cal_ids}")
for calendar in cal_ids:
if date_start and calendar.date_start != date_start:
_logger.info(
f"changing date_start of {calendar} "
f"from {calendar.date_start} to {date_start}"
)
calendar.date_start = date_start
if date_end and calendar.date_end != date_end:
_logger.info(
f"changing date_end of {calendar} "
f"from {calendar.date_end} to {date_end}"
)
calendar.date_end = date_end
else:
_logger.info(
f"adding new calendar_id for {contract.employee_id.name}: "
f"{contract.resource_calendar_id.name} from {date_start} to {date_end}"
)
contract_calendar_lines.append(
(
0,
0,
{
"date_start": date_start,
"date_end": date_end,
"calendar_id": contract.resource_calendar_id.id,
},
)
)
employee.calendar_ids = contract_calendar_lines
# set correct calendar in contract
employee.contract_id.resource_calendar_id = employee.resource_calendar_id
| 42.790323
| 2,653
|
505
|
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Hr Contract Employee Calendar Planning",
"version": "15.0.1.0.0",
"category": "Human Resources",
"website": "https://github.com/OCA/hr",
"author": "cibex,Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"auto_install": True,
"depends": ["hr_contract", "hr_employee_calendar_planning"],
"data": ["views/contract.xml"],
"post_init_hook": "post_init_hook",
}
| 36.071429
| 505
|
2,863
|
py
|
PYTHON
|
15.0
|
from datetime import datetime
from odoo.addons.hr_contract.tests.common import TestContractCommon
from ..hooks import post_init_hook
class TestHrContractEmployeeCalendarPlanning(TestContractCommon):
def setUp(self):
super().setUp()
calendar_ids = [
(
0,
0,
{
"date_start": False,
"date_end": datetime.strptime("2020-11-30", "%Y-%m-%d").date(),
"calendar_id": self.env["resource.calendar"].browse([2]).id,
},
),
(
0,
0,
{
"date_start": datetime.strptime("2020-12-01", "%Y-%m-%d").date(),
"date_end": False,
"calendar_id": self.env["resource.calendar"].browse([1]).id,
},
),
]
self.employee.calendar_ids = calendar_ids
def test_calendar_migration_from_contracts(self):
self.contract1 = self.env["hr.contract"].create(
{
"name": "contract1",
"employee_id": self.employee.id,
"wage": 1,
"state": "close",
"kanban_state": "normal",
"resource_calendar_id": self.env["resource.calendar"].browse([1]).id,
"date_start": datetime.strptime("2018-11-30", "%Y-%m-%d").date(),
"date_end": datetime.strptime("2019-11-30", "%Y-%m-%d").date(),
}
)
self.contract2 = self.env["hr.contract"].create(
{
"name": "contract2",
"employee_id": self.employee.id,
"wage": 1,
"state": "open",
"kanban_state": "normal",
"resource_calendar_id": self.env["resource.calendar"].browse([2]).id,
"date_start": datetime.strptime("2019-12-01", "%Y-%m-%d").date(),
"date_end": datetime.strptime("2020-11-30", "%Y-%m-%d").date(),
}
)
original_cal_ids = self.employee.calendar_ids.ids
start_dt = datetime(2019, 1, 1, 0, 0, 0)
end_dt = datetime(2019, 1, 2, 0, 0, 0)
self.assertEqual(
7.0,
self.employee.resource_calendar_id.get_work_hours_count(
start_dt=start_dt,
end_dt=end_dt,
),
)
# calendar migration from contracts
post_init_hook(self.env.cr, self.env.registry, self.employee)
self.assertEqual(
8.0,
self.employee.resource_calendar_id.get_work_hours_count(
start_dt=start_dt,
end_dt=end_dt,
),
)
self.assertTrue(
all(ids in self.employee.calendar_ids.ids for ids in original_cal_ids)
)
| 36.240506
| 2,863
|
1,071
|
py
|
PYTHON
|
15.0
|
from odoo import models
class HrContract(models.Model):
_inherit = "hr.contract"
def write(self, vals):
if (
vals.get("resource_calendar_id")
and self.employee_id
and vals.get("resource_calendar_id")
!= self.employee_id.resource_calendar_id.id
):
# in the write method of contracts, when writing the resource_calendar_id
# the employee resource_calendar_id is set to the same id
# this interferes with the logic of hr_employee_calendar_planning
# which assumes that calendar times are managed by resource.calendar.attendances
# in auto-generated calendars based on the employee's calendar_ids
# since the default calendar for new contracts is the employee calendar
# and we set the correct calendar for the existing contract in the post_init_hook
# we resolve this conflict by not allowing calendar changes in contracts
vals.pop("resource_calendar_id")
return super().write(vals)
| 46.565217
| 1,071
|
584
|
py
|
PYTHON
|
15.0
|
# Copyright 2014 Savoir-faire Linux. All Rights Reserved.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "HR Contract Multi Jobs",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"category": "Generic Modules/Human Resources",
"author": "Savoir-faire Linux, "
"Fekete Mihai (Forest and Biomass Services Romania), "
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"depends": ["hr_contract"],
"data": ["security/ir.model.access.csv", "views/hr_contract_view.xml"],
"installable": True,
}
| 34.352941
| 584
|
2,881
|
py
|
PYTHON
|
15.0
|
# Copyright 2014 Savoir-faire Linux. All Rights Reserved.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.exceptions import UserError
from odoo.tests.common import TransactionCase
class TestContractMultiJob(TransactionCase):
def setUp(self):
super(TestContractMultiJob, self).setUp()
self.employee_model = self.env["hr.employee"]
self.user_model = self.env["res.users"]
self.contract_model = self.env["hr.contract"]
self.job_model = self.env["hr.job"]
# Create an employee
self.employee_id = self.employee_model.create({"name": "Employee 1"})
# Create 2 jobs
self.job_id = self.job_model.create({"name": "Job 1"})
self.job_2_id = self.job_model.create({"name": "Job 2"})
# Create a contract
self.contract_id = self.contract_model.create(
{"employee_id": self.employee_id.id, "name": "Contract 1", "wage": 50000}
)
def test_no_main_jobs(self):
"""
Validate the _check_one_main_job method
when contract has no assigned job
and check job_id is False.
"""
self.contract_id.write({"contract_job_ids": []})
self.assertFalse(self.contract_id.job_id is False)
def test_one_main_jobs(self):
"""
Validate the _check_one_main_job method
when contract has one assigned job
and check is the job_id is set.
"""
self.contract_id.write(
{
"contract_job_ids": [
(0, 0, {"job_id": self.job_id.id, "is_main_job": True})
]
}
)
self.assertEqual(self.contract_id.job_id.id, self.job_id.id)
def test_two_contract_jobs_one_main_job(self):
"""
Validate the _check_one_main_job method
when contract has two assigned jobs
and check is the job_id is set as main job.
"""
self.contract_id.write(
{
"contract_job_ids": [
(0, 0, {"job_id": self.job_id.id, "is_main_job": True}),
(0, 0, {"job_id": self.job_2_id.id, "is_main_job": False}),
]
}
)
self.assertEqual(self.contract_id.job_id.id, self.job_id.id)
def test_two_contract_jobs_two_main_job(self):
"""
Validate the _check_one_main_job method
when contract has two assigned jobs
and raise error since both are set as main jobs.
"""
with self.assertRaises(UserError):
self.contract_id.write(
{
"contract_job_ids": [
(0, 0, {"job_id": self.job_id.id, "is_main_job": True}),
(0, 0, {"job_id": self.job_2_id.id, "is_main_job": True}),
]
}
)
| 34.710843
| 2,881
|
315
|
py
|
PYTHON
|
15.0
|
# Copyright 2014 Savoir-faire Linux. All Rights Reserved.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class HrJob(models.Model):
_inherit = "hr.job"
contract_job_ids = fields.One2many(
"hr.contract.job", "job_id", string="Contract Jobs"
)
| 26.25
| 315
|
877
|
py
|
PYTHON
|
15.0
|
# Copyright 2014 Savoir-faire Linux. All Rights Reserved.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class HrContractJob(models.Model):
"""
An instance of a job position for an employee's contract.
This model may look trivial for now, but the purpose is that other modules
add fields to it, e.g. a salary class or a wage scale. These are fields
that depend on both the contract and the job position.
"""
_name = "hr.contract.job"
_description = "Relational object between contract and job"
name = fields.Char(string="Job Name", related="job_id.name", index=True)
job_id = fields.Many2one("hr.job", required=True, ondelete="cascade")
contract_id = fields.Many2one("hr.contract", required=True, ondelete="cascade")
is_main_job = fields.Boolean(string="Main Job Position")
| 39.863636
| 877
|
1,703
|
py
|
PYTHON
|
15.0
|
# Copyright 2014 Savoir-faire Linux. All Rights Reserved.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class HrContract(models.Model):
_inherit = "hr.contract"
contract_job_ids = fields.One2many("hr.contract.job", "contract_id", string="Jobs")
# Modify the job_id field so that it points to the main job
job_id = fields.Many2one(
"hr.job", string="Job Title", compute="_compute_main_job_position", store=True
)
@api.depends("contract_job_ids.is_main_job")
def _compute_main_job_position(self):
"""
Get the main job position from the field contract_job_ids which
contains one and only one record with field is_main_job == True
"""
for contract in self:
main_job = contract.contract_job_ids.filtered("is_main_job").mapped(
"job_id"
)
if main_job and len(main_job) == 1:
contract.job_id = main_job
else:
contract.job_id = False
@api.constrains("contract_job_ids")
def _check_one_main_job(self):
# if the contract has no job assigned, a main job
# is not required. Otherwise, one main job assigned is
# required.
for contract in self.filtered("contract_job_ids"):
main_jobs = contract.contract_job_ids.filtered("is_main_job")
if len(main_jobs) != 1:
raise UserError(
_(
"You must assign one and only one job position "
"as main job position."
)
)
| 37.021739
| 1,703
|
644
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Partner Company Type",
"summary": "Adds a company type to partner that are companies",
"version": "15.0.1.0.1",
"license": "AGPL-3",
"author": "ACSONE SA/NV,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"depends": ["base", "contacts"],
"data": [
"security/res_partner_company_type.xml",
"views/res_partner_company_type.xml",
"views/res_partner.xml",
],
"demo": ["demo/res_partner_company_type.xml"],
"installable": True,
}
| 33.894737
| 644
|
699
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from psycopg2 import IntegrityError
from odoo import tools
from odoo.tests.common import TransactionCase
class TestResPartnerCompanyType(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestResPartnerCompanyType, cls).setUpClass()
cls.company_type = cls.env.ref(
"partner_company_type.res_partner_company_type_sa"
)
def test_00_duplicate(self):
# Test Duplicate Company type
with self.assertRaises(IntegrityError), tools.mute_logger("odoo.sql_db"):
self.company_type.create(dict(name=self.company_type.name))
| 31.772727
| 699
|
507
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResPartnerCompanyType(models.Model):
_name = "res.partner.company.type"
_description = "Partner Company Type"
name = fields.Char(string="Title", required=True, translate=True)
shortcut = fields.Char(string="Abbreviation", translate=True)
_sql_constraints = [
("name_uniq", "unique (name)", "Partner Company Type already exists!")
]
| 29.823529
| 507
|
318
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
partner_company_type_id = fields.Many2one(
comodel_name="res.partner.company.type", string="Legal Form"
)
| 26.5
| 318
|
622
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Contact nationality",
"summary": "Add nationality field to contacts",
"version": "15.0.1.0.0",
"category": "Customer Relationship Management",
"website": "https://github.com/OCA/partner-contact",
"author": "Grupo ESOC, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"auto_install": False,
"depends": ["partner_contact_personal_information_page"],
"data": ["views/res_partner.xml"],
}
| 36.588235
| 622
|
290
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
nationality_id = fields.Many2one("res.country", "Nationality")
| 29
| 290
|
717
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Patrick Wilson <patrickraymondwilson@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Partner Priority",
"summary": "Adds priority to partners.",
"author": "Patrick Wilson, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"category": "Customer Relationship Management",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"depends": ["contacts"],
"data": [
"views/res_partner.xml",
"views/partner_priority.xml",
"security/ir.model.access.csv",
"data/partner_priority_data.xml",
],
"development_status": "Beta",
"maintainers": ["patrickrwilson"],
}
| 34.142857
| 717
|
477
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Patrick Wilson <patrickraymondwilson@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class PartnerPriority(models.Model):
_name = "partner.priority"
_order = "sequence"
_description = "Partner Priority"
name = fields.Char(string="Priority", required=True)
description = fields.Text(required=True)
sequence = fields.Integer(
required=True,
default=0,
)
| 28.058824
| 477
|
281
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Patrick Wilson <patrickraymondwilson@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
priority_id = fields.Many2one("partner.priority")
| 28.1
| 281
|
371
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Quartile Limited
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Partner Company Default",
"version": "15.0.1.0.0",
"author": "Quartile Limited, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"depends": ["base"],
"license": "AGPL-3",
"installable": True,
}
| 33.727273
| 371
|
268
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Quartile Limited
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
company_id = fields.Many2one(default=lambda self: self.env.company)
| 26.8
| 268
|
893
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Jairo Llopis
# Copyright 2016 Tecnativa - Vicent Cubells
# Copyright 2017-2018 Tecnativa - Pedro M. Baeza
# Copyright 2019 Tecnativa - Victor M.M. Torres
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Deduplicate Contacts ACL",
"summary": "Contact deduplication with fine-grained permission control",
"version": "15.0.1.2.0",
"category": "Tools",
"website": "https://github.com/OCA/partner-contact",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["contacts"],
"data": [
"security/partner_deduplicate_acl_security.xml",
"security/ir.model.access.csv",
"wizards/partner_merge_view.xml",
"views/base_partner_merge_view.xml",
],
"images": ["images/perms.png"],
}
| 35.72
| 893
|
1,662
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import exceptions
from odoo.tests import common
class TestPartnerDeduplicateAcl(common.TransactionCase):
def setUp(self):
super().setUp()
self.partner_1 = self.env["res.partner"].create(
{
"name": "Partner 1",
"email": "partner1@example.org",
"is_company": True,
"parent_id": False,
}
)
self.partner_2 = self.partner_1.copy()
self.partner_2.write({"name": "Partner 1", "email": "partner2@example.org"})
self.user = self.env["res.users"].create(
{
"login": "test_crm_deduplicate_acl",
"name": "test_crm_deduplicate_acl",
"email": "partner_deduplicate_acl@example.org",
"groups_id": [
(4, self.env.ref("base.group_user").id),
(4, self.env.ref("base.group_partner_manager").id),
],
}
)
self.wizard = (
self.env["base.partner.merge.automatic.wizard"]
.with_user(self.user)
.create({"group_by_name": True})
)
def test_same_email_restriction(self):
self.wizard.action_start_manual_process()
with self.assertRaises(exceptions.UserError):
self.wizard.action_merge()
self.user.groups_id = [
(4, self.env.ref("partner_deduplicate_acl.group_unrestricted").id)
]
# Now there shouldn't be error
self.wizard.action_merge()
| 36.130435
| 1,662
|
759
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Jairo Llopis
# Copyright 2016 Tecnativa - Vicent Cubells
# Copyright 2017-2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
def _merge(self, partner_ids, dst_partner=None, extra_checks=True):
"""Pass extra_checks=False if we have the extra group for avoiding
the checks.
"""
if self.env.user.has_group("partner_deduplicate_acl.group_unrestricted"):
extra_checks = False
return super()._merge(
partner_ids, dst_partner=dst_partner, extra_checks=extra_checks
)
| 37.95
| 759
|
527
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Base Partner Company Group",
"summary": "Adds the possibility to add a company group to a company",
"version": "15.0.1.1.0",
"category": "Sales",
"author": "Camptocamp SA, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["base"],
"website": "https://github.com/OCA/partner-contact",
"data": [
"views/contact_view.xml",
],
"installable": True,
}
| 32.9375
| 527
|
816
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Ecosoft Co., Ltd (http://ecosoft.co.th/)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class TestBasePartnerCompanyGroup(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner_model = cls.env["res.partner"]
cls.company = cls.partner_model.create(
{"name": "Test Company", "company_type": "company"}
)
cls.contact = cls.partner_model.create(
{"name": "Test Contact", "type": "contact", "parent_id": cls.company.id}
)
def test_base_partner_company_group(self):
self.company.write({"company_group_id": self.company.id})
self.assertEqual(self.company.company_group_id, self.contact.company_group_id)
| 38.857143
| 816
|
629
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class Contact(models.Model):
_inherit = "res.partner"
company_group_id = fields.Many2one(
"res.partner",
"Company group",
domain=[("is_company", "=", True)],
recursive=True,
)
company_group_member_ids = fields.One2many(
comodel_name="res.partner",
inverse_name="company_group_id",
string="Company group members",
)
def _commercial_fields(self):
return super()._commercial_fields() + ["company_group_id"]
| 27.347826
| 629
|
939
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Antonio Espinosa <antonio.espinosa@tecnativa.com>
# Copyright 2015 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2017 David Vidal <david.vidal@tecnativa.com>
# Copyright 2018 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Employee quantity in partners",
"summary": "Know how many employees a partner has",
"version": "15.0.1.0.0",
"category": "Customer Relationship Management",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"website": "https://github.com/OCA/partner-contact",
"depends": ["contacts"],
"data": [
"security/ir.model.access.csv",
"views/res_partner_employee_quantity_range_view.xml",
"views/res_partner_view.xml",
],
"development_status": "Mature",
"maintainers": ["pedrobaeza"],
"installable": True,
}
| 37.56
| 939
|
823
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Antonio Espinosa <antonio.espinosa@tecnativa.com>
# Copyright 2015 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2018 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
employee_quantity = fields.Integer()
employee_quantity_range_id = fields.Many2one(
comodel_name="res.partner.employee_quantity_range",
string="Employee quantity range",
help="Range of this partner depending on the employee quantity.",
)
class ResPartnerEmployeeQuantityRange(models.Model):
_name = "res.partner.employee_quantity_range"
_description = "Partner employee quantity range"
name = fields.Char(required=True, translate=True)
| 34.291667
| 823
|
752
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Partner Company Group",
"summary": "Adds the possibility to add a company group to a company",
"version": "15.0.2.0.0",
"category": "Sales",
"author": "Camptocamp SA, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": [
"account_partner_company_group",
"crm_partner_company_group",
"sale_partner_company_group",
],
"website": "https://github.com/OCA/partner-contact",
"data": [
"views/opportunity_view.xml",
"views/contact_view.xml",
"views/sale_order_view.xml",
"views/account_move_views.xml",
],
"installable": True,
}
| 32.695652
| 752
|
757
|
py
|
PYTHON
|
15.0
|
# Copyright 2013-2020 Therp BV <http://therp.nl>.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Partner Relations",
"version": "15.0.1.0.0",
"author": "Therp BV,Camptocamp,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"complexity": "normal",
"category": "Customer Relationship Management",
"license": "AGPL-3",
"depends": ["contacts", "sales_team"],
"demo": ["data/demo.xml"],
"data": [
"security/ir.model.access.csv",
"views/res_partner_relation_all.xml",
"views/res_partner.xml",
"views/res_partner_relation_type.xml",
"views/menu.xml",
],
"auto_install": False,
"installable": True,
}
| 34.409091
| 757
|
14,300
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Therp BV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from datetime import date
from odoo.exceptions import ValidationError
from .test_partner_relation_common import TestPartnerRelationCommon
class TestPartnerRelation(TestPartnerRelationCommon):
def setUp(self):
super(TestPartnerRelation, self).setUp()
# Create a new relation type which will not have valid relations:
category_nobody = self.category_model.create({"name": "Nobody"})
(
self.type_nobody,
self.selection_nobody,
self.selection_nobody_inverse,
) = self._create_relation_type_selection(
{
"name": "has relation with nobody",
"name_inverse": "nobody has relation with",
"contact_type_left": "c",
"contact_type_right": "p",
"partner_category_left": category_nobody.id,
"partner_category_right": category_nobody.id,
}
)
def _get_empty_relation(self):
"""Get empty relation record for onchange tests."""
# Need English, because we will compare text
return self.relation_all_model.with_context(lang="en_US").new({})
def test_get_partner_types(self):
"""Partner types should contain at least 'c' and 'p'."""
partner_types = self.selection_model.get_partner_types()
type_codes = [ptype[0] for ptype in partner_types]
self.assertTrue("c" in type_codes)
self.assertTrue("p" in type_codes)
def test_create_with_active_id(self):
"""Test creation with this_partner_id from active_id."""
# Check wether we can create connection from company to person,
# taking the particular company from the active records:
relation = self.relation_all_model.with_context(
active_id=self.partner_02_company.id, active_ids=self.partner_02_company.ids
).create(
{
"other_partner_id": self.partner_01_person.id,
"type_selection_id": self.selection_company2person.id,
}
)
self.assertTrue(relation)
self.assertEqual(relation.this_partner_id, self.partner_02_company)
# Partner should have one relation now:
relation.invalidate_cache(None, relation.ids)
self.partner_01_person.flush()
self.assertEqual(self.partner_01_person.relation_count, 1)
# Test create without type_selection_id:
with self.assertRaises(ValidationError):
self.relation_all_model.create(
{
"this_partner_id": self.partner_02_company.id,
"other_partner_id": self.partner_01_person.id,
}
)
def test_display_name(self):
"""Test display name"""
relation = self._create_company2person_relation()
self.assertEqual(
relation.display_name,
"%s %s %s"
% (
relation.this_partner_id.name,
relation.type_selection_id.name,
relation.other_partner_id.name,
),
)
def test_regular_write(self):
"""Test write with valid data."""
relation = self._create_company2person_relation()
relation.write({"date_start": "2014-09-01"})
self.assertEqual(relation.date_start, date(2014, 9, 1))
def test_write_incompatible_dates(self):
"""Test write with date_end before date_start."""
relation = self._create_company2person_relation()
with self.assertRaises(ValidationError):
relation.write({"date_start": "2016-09-01", "date_end": "2016-08-01"})
def test_validate_overlapping_01(self):
"""Test create overlapping with no start / end dates."""
relation = self._create_company2person_relation()
with self.assertRaises(ValidationError):
# New relation with no start / end should give error
self.relation_all_model.create(
{
"this_partner_id": relation.this_partner_id.id,
"type_selection_id": relation.type_selection_id.id,
"other_partner_id": relation.other_partner_id.id,
}
)
def test_validate_overlapping_02(self):
"""Test create overlapping with start / end dates."""
relation = self.relation_all_model.create(
{
"this_partner_id": self.partner_02_company.id,
"type_selection_id": self.selection_company2person.id,
"other_partner_id": self.partner_01_person.id,
"date_start": "2015-09-01",
"date_end": "2016-08-31",
}
)
# New relation with overlapping start / end should give error
with self.assertRaises(ValidationError):
self.relation_all_model.create(
{
"this_partner_id": relation.this_partner_id.id,
"type_selection_id": relation.type_selection_id.id,
"other_partner_id": relation.other_partner_id.id,
"date_start": "2016-08-01",
"date_end": "2017-07-30",
}
)
def test_validate_overlapping_03(self):
"""Test create not overlapping."""
relation = self.relation_all_model.create(
{
"this_partner_id": self.partner_02_company.id,
"type_selection_id": self.selection_company2person.id,
"other_partner_id": self.partner_01_person.id,
"date_start": "2015-09-01",
"date_end": "2016-08-31",
}
)
relation_another_record = self.relation_all_model.create(
{
"this_partner_id": relation.this_partner_id.id,
"type_selection_id": relation.type_selection_id.id,
"other_partner_id": relation.other_partner_id.id,
"date_start": "2016-09-01",
"date_end": "2017-08-31",
}
)
self.assertTrue(relation_another_record)
def test_inverse_record(self):
"""Test creation of inverse record."""
relation = self._create_company2person_relation()
inverse_relation = self.relation_all_model.search(
[
("this_partner_id", "=", relation.other_partner_id.id),
("other_partner_id", "=", relation.this_partner_id.id),
]
)
self.assertEqual(len(inverse_relation), 1)
self.assertEqual(
inverse_relation.type_selection_id.name, self.selection_person2company.name
)
def test_inverse_creation(self):
"""Test creation of record through inverse selection."""
relation = self.relation_all_model.create(
{
"this_partner_id": self.partner_01_person.id,
"type_selection_id": self.selection_person2company.id,
"other_partner_id": self.partner_02_company.id,
}
)
# Check wether display name is what we should expect:
self.assertEqual(
relation.display_name,
"%s %s %s"
% (
self.partner_01_person.name,
self.selection_person2company.name,
self.partner_02_company.name,
),
)
def test_inverse_creation_type_id(self):
"""Test creation of record through inverse selection with type_id."""
relation = self.relation_all_model.create(
{
"this_partner_id": self.partner_01_person.id,
"type_id": self.selection_person2company.type_id.id,
"is_inverse": True,
"other_partner_id": self.partner_02_company.id,
}
)
# Check wether display name is what we should expect:
self.assertEqual(
relation.display_name,
"%s %s %s"
% (
self.partner_01_person.name,
self.selection_person2company.name,
self.partner_02_company.name,
),
)
def test_unlink(self):
"""Unlinking derived relation should unlink base relation."""
# Check wether underlying record is removed when record is removed:
relation = self._create_company2person_relation()
base_model = self.env[relation.res_model]
base_relation = base_model.browse([relation.res_id])
relation.unlink()
self.assertFalse(base_relation.exists())
# Check unlinking record sets with both derived relation records
self.assertTrue(self.relation_all_model.search([]).unlink())
def test_on_change_type_selection(self):
"""Test on_change_type_selection."""
# 1. Test call with empty relation
relation_empty = self._get_empty_relation()
result = relation_empty.onchange_type_selection_id()
self.assertTrue("domain" in result)
self.assertFalse("warning" in result)
self.assertTrue("this_partner_id" in result["domain"])
self.assertFalse(result["domain"]["this_partner_id"])
self.assertTrue("other_partner_id" in result["domain"])
self.assertFalse(result["domain"]["other_partner_id"])
# 2. Test call with company 2 person relation
relation = self._create_company2person_relation()
domain = relation.onchange_type_selection_id()["domain"]
self.assertTrue(("is_company", "=", False) in domain["other_partner_id"])
# 3. Test with relation needing categories,
# take active partner from active_id:
relation_ngo_volunteer = self.relation_all_model.with_context(
active_id=self.partner_03_ngo.id
).create(
{
"type_selection_id": self.selection_ngo2volunteer.id,
"other_partner_id": self.partner_04_volunteer.id,
}
)
domain = relation_ngo_volunteer.onchange_type_selection_id()["domain"]
self.assertTrue(
("category_id", "in", [self.category_01_ngo.id])
in domain["this_partner_id"]
)
self.assertTrue(
("category_id", "in", [self.category_02_volunteer.id])
in domain["other_partner_id"]
)
# 4. Test with invalid or impossible combinations
relation_nobody = self._get_empty_relation()
relation_nobody.type_selection_id = self.selection_nobody
warning = relation_nobody.onchange_type_selection_id()["warning"]
self.assertTrue("message" in warning)
self.assertTrue("No this partner available" in warning["message"])
relation_nobody.this_partner_id = self.partner_02_company
warning = relation_nobody.onchange_type_selection_id()["warning"]
self.assertTrue("message" in warning)
self.assertTrue("incompatible" in warning["message"])
# Allow left partner and check message for other partner:
self.type_nobody.write({"partner_category_left": False})
self.type_nobody.flush()
self.selection_nobody.invalidate_cache(ids=self.selection_nobody.ids)
warning = relation_nobody.onchange_type_selection_id()["warning"]
self.assertTrue("message" in warning)
self.assertTrue("No other partner available" in warning["message"])
def test_on_change_partner_id(self):
"""Test on_change_partner_id."""
# 1. Test call with empty relation
relation_empty = self._get_empty_relation()
result = relation_empty.onchange_partner_id()
self.assertTrue("domain" in result)
self.assertFalse("warning" in result)
self.assertTrue("type_selection_id" in result["domain"])
self.assertFalse(result["domain"]["type_selection_id"])
# 2. Test call with company 2 person relation
relation = self._create_company2person_relation()
domain = relation.onchange_partner_id()["domain"]
self.assertTrue(("contact_type_this", "=", "c") in domain["type_selection_id"])
# 3. Test with invalid or impossible combinations
relation_nobody = self._get_empty_relation()
relation_nobody.this_partner_id = self.partner_02_company
relation_nobody.type_selection_id = self.selection_nobody
warning = relation_nobody.onchange_partner_id()["warning"]
self.assertTrue("message" in warning)
self.assertTrue("incompatible" in warning["message"])
def test_write(self):
"""Test write. Special attention for changing type."""
relation_company2person = self._create_company2person_relation()
company_partner = relation_company2person.this_partner_id
# First get another worker:
partner_extra_person = self.partner_model.create(
{"name": "A new worker", "is_company": False, "ref": "NW01"}
)
relation_company2person.write({"other_partner_id": partner_extra_person.id})
self.assertEqual(
relation_company2person.other_partner_id.name, partner_extra_person.name
)
# We will also change to a type going from person to company:
(
type_worker2company,
selection_worker2company,
selection_company2worker,
) = self._create_relation_type_selection(
{
"name": "works for",
"name_inverse": "has worker",
"contact_type_left": "p",
"contact_type_right": "c",
}
)
relation_company2person.write(
{
"this_partner_id": partner_extra_person.id,
"type_selection_id": selection_worker2company.id,
"other_partner_id": company_partner.id,
}
)
self.assertEqual(
relation_company2person.this_partner_id.id, partner_extra_person.id
)
self.assertEqual(
relation_company2person.type_selection_id.id, selection_worker2company.id
)
self.assertEqual(
relation_company2person.other_partner_id.id, company_partner.id
)
| 42.942943
| 14,300
|
3,345
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Camptocamp SA
# Copyright 2016 Therp BV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields
from odoo.exceptions import ValidationError
from .test_partner_relation_common import TestPartnerRelationCommon
class TestPartnerSearch(TestPartnerRelationCommon):
def test_search_relation_type(self):
"""Test searching on relation type."""
relation = self._create_company2person_relation()
partners = self.partner_model.search(
[("search_relation_type_id", "=", relation.type_selection_id.id)]
)
self.assertTrue(self.partner_02_company in partners)
partners = self.partner_model.search(
[("search_relation_type_id", "!=", relation.type_selection_id.id)]
)
self.assertTrue(self.partner_01_person in partners)
partners = self.partner_model.search(
[("search_relation_type_id", "=", self.type_company2person.name)]
)
self.assertTrue(self.partner_01_person in partners)
self.assertTrue(self.partner_02_company in partners)
partners = self.partner_model.search(
[("search_relation_type_id", "=", "unknown relation")]
)
self.assertFalse(partners)
# Check error with invalid search operator:
with self.assertRaises(ValidationError):
partners = self.partner_model.search(
[("search_relation_type_id", "child_of", "some parent")]
)
def test_search_relation_partner(self):
"""Test searching on related partner."""
self._create_company2person_relation()
partners = self.partner_model.search(
[("search_relation_partner_id", "=", self.partner_02_company.id)]
)
self.assertTrue(self.partner_01_person in partners)
def test_search_relation_date(self):
"""Test searching on relations valid on a certain date."""
self._create_company2person_relation()
partners = self.partner_model.search(
[("search_relation_date", "=", fields.Date.today())]
)
self.assertTrue(self.partner_01_person in partners)
self.assertTrue(self.partner_02_company in partners)
def test_search_any_partner(self):
"""Test searching for partner left or right."""
self._create_company2person_relation()
both_relations = self.relation_all_model.search(
[("any_partner_id", "=", self.partner_02_company.id)]
)
self.assertEqual(len(both_relations), 2)
def test_search_partner_category(self):
"""Test searching for partners related to partners having category."""
relation_ngo_volunteer = self.relation_all_model.create(
{
"this_partner_id": self.partner_03_ngo.id,
"type_selection_id": self.selection_ngo2volunteer.id,
"other_partner_id": self.partner_04_volunteer.id,
}
)
self.assertTrue(relation_ngo_volunteer)
partners = self.partner_model.search(
[
(
"search_relation_partner_category_id",
"=",
self.category_02_volunteer.id,
)
]
)
self.assertTrue(self.partner_03_ngo in partners)
| 41.296296
| 3,345
|
17,586
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Therp BV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from datetime import date, datetime, timedelta
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.exceptions import ValidationError
from .test_partner_relation_common import TestPartnerRelationCommon
class TestPartnerRelation(TestPartnerRelationCommon):
post_install = True
def test_selection_name_search(self):
"""Test wether we can find type selection on reverse name."""
selection_types = self.selection_model.name_search(
name=self.selection_person2company.name
)
self.assertTrue(selection_types)
self.assertTrue(
(self.selection_person2company.id, self.selection_person2company.name)
in selection_types
)
def test_self_allowed(self):
"""Test creation of relation to same partner when type allows."""
type_allow = self.type_model.create(
{
"name": "allow",
"name_inverse": "allow_inverse",
"contact_type_left": "p",
"contact_type_right": "p",
"allow_self": True,
}
)
self.assertTrue(type_allow)
reflexive_relation = self.relation_model.create(
{
"type_id": type_allow.id,
"left_partner_id": self.partner_01_person.id,
"right_partner_id": self.partner_01_person.id,
}
)
self.assertTrue(reflexive_relation)
def test_self_disallowed(self):
"""Test creating relation to same partner when disallowed.
Attempt to create a relation of a partner to the same partner should
raise an error when the type of relation explicitly disallows this.
"""
type_disallow = self.type_model.create(
{
"name": "disallow",
"name_inverse": "disallow_inverse",
"contact_type_left": "p",
"contact_type_right": "p",
"allow_self": False,
}
)
self.assertTrue(type_disallow)
with self.assertRaises(ValidationError):
self.relation_model.create(
{
"type_id": type_disallow.id,
"left_partner_id": self.partner_01_person.id,
"right_partner_id": self.partner_01_person.id,
}
)
def test_self_disallowed_after_self_relation_created(self):
"""Test that allow_self can not be true if a reflexive relation already exists.
If at least one reflexive relation exists for the given type,
reflexivity can not be disallowed.
"""
type_allow = self.type_model.create(
{
"name": "allow",
"name_inverse": "allow_inverse",
"contact_type_left": "p",
"contact_type_right": "p",
"allow_self": True,
}
)
self.assertTrue(type_allow)
reflexive_relation = self.relation_model.create(
{
"type_id": type_allow.id,
"left_partner_id": self.partner_01_person.id,
"right_partner_id": self.partner_01_person.id,
}
)
self.assertTrue(reflexive_relation)
with self.assertRaises(ValidationError):
type_allow.allow_self = False
def test_self_disallowed_with_delete_invalid_relations(self):
"""Test handle_invalid_onchange delete with allow_self disabled.
When deactivating allow_self, if handle_invalid_onchange is set
to delete, then existing reflexive relations are deleted.
Non reflexive relations are not modified.
"""
type_allow = self.type_model.create(
{
"name": "allow",
"name_inverse": "allow_inverse",
"contact_type_left": "p",
"contact_type_right": "p",
"allow_self": True,
"handle_invalid_onchange": "delete",
}
)
reflexive_relation = self.relation_model.create(
{
"type_id": type_allow.id,
"left_partner_id": self.partner_01_person.id,
"right_partner_id": self.partner_01_person.id,
}
)
normal_relation = self.relation_model.create(
{
"type_id": type_allow.id,
"left_partner_id": self.partner_01_person.id,
"right_partner_id": self.partner_04_volunteer.id,
}
)
type_allow.allow_self = False
self.assertFalse(reflexive_relation.exists())
self.assertTrue(normal_relation.exists())
def test_self_disallowed_with_end_invalid_relations(self):
"""Test handle_invalid_onchange delete with allow_self disabled.
When deactivating allow_self, if handle_invalid_onchange is set
to end, then active reflexive relations are ended.
Non reflexive relations are not modified.
Reflexive relations with an end date prior to the current date
are not modified.
"""
type_allow = self.type_model.create(
{
"name": "allow",
"name_inverse": "allow_inverse",
"contact_type_left": "p",
"contact_type_right": "p",
"allow_self": True,
"handle_invalid_onchange": "end",
}
)
reflexive_relation = self.relation_model.create(
{
"type_id": type_allow.id,
"left_partner_id": self.partner_01_person.id,
"right_partner_id": self.partner_01_person.id,
"date_start": "2000-01-02",
}
)
past_reflexive_relation = self.relation_model.create(
{
"type_id": type_allow.id,
"left_partner_id": self.partner_01_person.id,
"right_partner_id": self.partner_01_person.id,
"date_end": "2000-01-01",
}
)
normal_relation = self.relation_model.create(
{
"type_id": type_allow.id,
"left_partner_id": self.partner_01_person.id,
"right_partner_id": self.partner_04_volunteer.id,
}
)
type_allow.allow_self = False
self.assertEqual(reflexive_relation.date_end, fields.Date.today())
self.assertEqual(past_reflexive_relation.date_end, date(2000, 1, 1))
self.assertFalse(normal_relation.date_end)
def test_self_disallowed_with_future_reflexive_relation(self):
"""Test future reflexive relations are deleted.
If handle_invalid_onchange is set to end, then deactivating
reflexivity will delete invalid relations in the future.
"""
type_allow = self.type_model.create(
{
"name": "allow",
"name_inverse": "allow_inverse",
"contact_type_left": "p",
"contact_type_right": "p",
"allow_self": True,
"handle_invalid_onchange": "end",
}
)
future_reflexive_relation = self.relation_model.create(
{
"type_id": type_allow.id,
"left_partner_id": self.partner_01_person.id,
"right_partner_id": self.partner_01_person.id,
"date_start": datetime.now() + timedelta(1),
}
)
type_allow.allow_self = False
self.assertFalse(future_reflexive_relation.exists())
def test_self_default(self):
"""Test default not to allow relation with same partner.
Attempt to create a relation of a partner to the same partner
raise an error when the type of relation does not explicitly allow
this.
"""
type_default = self.type_model.create(
{
"name": "default",
"name_inverse": "default_inverse",
"contact_type_left": "p",
"contact_type_right": "p",
}
)
self.assertTrue(type_default)
with self.assertRaises(ValidationError):
self.relation_model.create(
{
"type_id": type_default.id,
"left_partner_id": self.partner_01_person.id,
"right_partner_id": self.partner_01_person.id,
}
)
def test_self_mixed(self):
"""Test creation of relation with wrong types.
Trying to create a relation between partners with an inappropiate
type should raise an error.
"""
with self.assertRaises(ValidationError):
self.relation_model.create(
{
"type_id": self.type_company2person.id,
"left_partner_id": self.partner_01_person.id,
"right_partner_id": self.partner_02_company.id,
}
)
def test_symmetric(self):
"""Test creating symmetric relation."""
# Start out with non symmetric relation:
type_symmetric = self.type_model.create(
{
"name": "not yet symmetric",
"name_inverse": "the other side of not symmetric",
"is_symmetric": False,
"contact_type_left": False,
"contact_type_right": "p",
}
)
# not yet symmetric relation should result in two records in
# selection:
selection_symmetric = self.selection_model.search(
[("type_id", "=", type_symmetric.id)]
)
self.assertEqual(len(selection_symmetric), 2)
# Now change to symmetric and test name and inverse name:
type_symmetric.write({"name": "sym", "is_symmetric": True})
self.assertEqual(type_symmetric.is_symmetric, True)
self.assertEqual(type_symmetric.name_inverse, type_symmetric.name)
self.assertEqual(
type_symmetric.contact_type_right, type_symmetric.contact_type_left
)
# now update the database:
type_symmetric.write(
{
"name": type_symmetric.name,
"is_symmetric": type_symmetric.is_symmetric,
"name_inverse": type_symmetric.name_inverse,
"contact_type_right": type_symmetric.contact_type_right,
}
)
type_symmetric.flush()
# symmetric relation should result in only one record in
# selection:
selection_symmetric = self.selection_model.search(
[("type_id", "=", type_symmetric.id)]
)
self.assertEqual(len(selection_symmetric), 1)
relation = self.relation_all_model.create(
{
"type_selection_id": selection_symmetric.id,
"this_partner_id": self.partner_02_company.id,
"other_partner_id": self.partner_01_person.id,
}
)
partners = self.partner_model.search(
[("search_relation_type_id", "=", relation.type_selection_id.id)]
)
self.assertTrue(self.partner_01_person in partners)
self.assertTrue(self.partner_02_company in partners)
def test_category_domain(self):
"""Test check on category in relations."""
# Check on left side:
with self.assertRaises(ValidationError):
self.relation_model.create(
{
"type_id": self.type_ngo2volunteer.id,
"left_partner_id": self.partner_02_company.id,
"right_partner_id": self.partner_04_volunteer.id,
}
)
# Check on right side:
with self.assertRaises(ValidationError):
self.relation_model.create(
{
"type_id": self.type_ngo2volunteer.id,
"left_partner_id": self.partner_03_ngo.id,
"right_partner_id": self.partner_01_person.id,
}
)
def test_relation_type_change(self):
"""Test change in relation type conditions."""
# First create a relation type having no particular conditions.
(
type_school2student,
school2student,
school2student_inverse,
) = self._create_relation_type_selection(
{"name": "school has student", "name_inverse": "studies at school"}
)
# Second create relations based on those conditions.
partner_school = self.partner_model.create(
{"name": "Test School", "is_company": True, "ref": "TS"}
)
partner_bart = self.partner_model.create(
{"name": "Bart Simpson", "is_company": False, "ref": "BS"}
)
partner_lisa = self.partner_model.create(
{"name": "Lisa Simpson", "is_company": False, "ref": "LS"}
)
relation_school2bart = self.relation_all_model.create(
{
"this_partner_id": partner_school.id,
"type_selection_id": school2student.id,
"other_partner_id": partner_bart.id,
}
)
self.assertTrue(relation_school2bart)
relation_school2lisa = self.relation_all_model.create(
{
"this_partner_id": partner_school.id,
"type_selection_id": school2student.id,
"other_partner_id": partner_lisa.id,
}
)
self.assertTrue(relation_school2lisa)
relation_bart2lisa = self.relation_all_model.create(
{
"this_partner_id": partner_bart.id,
"type_selection_id": school2student.id,
"other_partner_id": partner_lisa.id,
}
)
self.assertTrue(relation_bart2lisa)
# Third creata a category and make it a condition for the
# relation type.
# - Test restriction
# - Test ignore
category_student = self.category_model.create({"name": "Student"})
with self.assertRaises(ValidationError):
type_school2student.write({"partner_category_right": category_student.id})
self.assertFalse(type_school2student.partner_category_right.id)
type_school2student.write(
{
"handle_invalid_onchange": "ignore",
"partner_category_right": category_student.id,
}
)
self.assertEqual(
type_school2student.partner_category_right.id, category_student.id
)
# Fourth make company type a condition for left partner
# - Test ending
# - Test deletion
partner_bart.write({"category_id": [(4, category_student.id)]})
partner_lisa.write({"category_id": [(4, category_student.id)]})
# Future student to be deleted by end action:
partner_homer = self.partner_model.create(
{
"name": "Homer Simpson",
"is_company": False,
"ref": "HS",
"category_id": [(4, category_student.id)],
}
)
relation_lisa2homer = self.relation_all_model.create(
{
"this_partner_id": partner_lisa.id,
"type_selection_id": school2student.id,
"other_partner_id": partner_homer.id,
"date_start": date.today() + relativedelta(months=+6),
}
)
self.assertTrue(relation_lisa2homer)
type_school2student.write(
{"handle_invalid_onchange": "end", "contact_type_left": "c"}
)
self.assertEqual(relation_bart2lisa.date_end, fields.Date.today())
self.assertFalse(relation_lisa2homer.exists())
type_school2student.write(
{
"handle_invalid_onchange": "delete",
"contact_type_left": "c",
"contact_type_right": "p",
}
)
self.assertFalse(relation_bart2lisa.exists())
def test_relation_type_unlink(self):
"""Test delete of relation type, including deleting relations."""
# First create a relation type having restrict particular conditions.
type_model = self.env["res.partner.relation.type"]
relation_model = self.env["res.partner.relation"]
partner_model = self.env["res.partner"]
type_school2student = type_model.create(
{
"name": "school has student",
"name_inverse": "studies at school",
"handle_invalid_onchange": "delete",
}
)
# Second create relation based on those conditions.
partner_school = partner_model.create(
{"name": "Test School", "is_company": True, "ref": "TS"}
)
partner_bart = partner_model.create(
{"name": "Bart Simpson", "is_company": False, "ref": "BS"}
)
relation_school2bart = relation_model.create(
{
"left_partner_id": partner_school.id,
"type_id": type_school2student.id,
"right_partner_id": partner_bart.id,
}
)
# Delete type. Relations with type should also cease to exist:
type_school2student.unlink()
self.assertFalse(relation_school2bart.exists())
| 38.4814
| 17,586
|
4,346
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Therp BV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
class TestPartnerRelationCommon(common.TransactionCase):
def setUp(self):
super(TestPartnerRelationCommon, self).setUp()
self.partner_model = self.env["res.partner"]
self.category_model = self.env["res.partner.category"]
self.type_model = self.env["res.partner.relation.type"]
self.selection_model = self.env["res.partner.relation.type.selection"]
self.relation_model = self.env["res.partner.relation"]
self.relation_all_model = self.env["res.partner.relation.all"]
self.partner_01_person = self.partner_model.create(
{"name": "Test User 1", "is_company": False, "ref": "PR01"}
)
self.partner_02_company = self.partner_model.create(
{"name": "Test Company", "is_company": True, "ref": "PR02"}
)
# Create partners with specific categories:
self.category_01_ngo = self.category_model.create({"name": "NGO"})
self.partner_03_ngo = self.partner_model.create(
{
"name": "Test NGO",
"is_company": True,
"ref": "PR03",
"category_id": [(4, self.category_01_ngo.id)],
}
)
self.category_02_volunteer = self.category_model.create({"name": "Volunteer"})
self.partner_04_volunteer = self.partner_model.create(
{
"name": "Test Volunteer",
"is_company": False,
"ref": "PR04",
"category_id": [(4, self.category_02_volunteer.id)],
}
)
# Create a new relation type withouth categories:
(
self.type_company2person,
self.selection_company2person,
self.selection_person2company,
) = self._create_relation_type_selection(
{
"name": "mixed",
"name_inverse": "mixed_inverse",
"contact_type_left": "c",
"contact_type_right": "p",
}
)
# Create a new relation type with categories:
(
self.type_ngo2volunteer,
self.selection_ngo2volunteer,
self.selection_volunteer2ngo,
) = self._create_relation_type_selection(
{
"name": "NGO has volunteer",
"name_inverse": "volunteer works for NGO",
"contact_type_left": "c",
"contact_type_right": "p",
"partner_category_left": self.category_01_ngo.id,
"partner_category_right": self.category_02_volunteer.id,
}
)
def _create_relation_type_selection(self, vals):
"""Create relation type and return this with selection types."""
assert "name" in vals, (
"Name missing in vals to create relation type. Vals: %s." % vals
)
assert "name" in vals, (
"Name_inverse missing in vals to create relation type. Vals: %s." % vals
)
new_type = self.type_model.create(vals)
self.assertTrue(new_type, msg="No relation type created with vals %s." % vals)
selection_types = self.selection_model.search([("type_id", "=", new_type.id)])
for st in selection_types:
if st.is_inverse:
inverse_type_selection = st
else:
type_selection = st
self.assertTrue(
inverse_type_selection,
msg="Failed to find inverse type selection based on"
" relation type created with vals %s." % vals,
)
self.assertTrue(
type_selection,
msg="Failed to find type selection based on"
" relation type created with vals %s." % vals,
)
return (new_type, type_selection, inverse_type_selection)
def _create_company2person_relation(self):
"""Utility function to get a relation from company 2 partner."""
return self.relation_all_model.create(
{
"type_selection_id": self.selection_company2person.id,
"this_partner_id": self.partner_02_company.id,
"other_partner_id": self.partner_01_person.id,
}
)
| 41
| 4,346
|
995
|
py
|
PYTHON
|
15.0
|
# © 2021 Tobias Zehntner
# © 2021 Niboo SRL (https://www.niboo.com/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import exceptions
from .test_partner_relation_common import TestPartnerRelationCommon
class TestPartnerRelationAction(TestPartnerRelationCommon):
def setUp(self):
super().setUp()
self.user = self.env["res.users"].create(
{
"login": "test_partner_action_user",
"name": "test_partner_action_user",
"groups_id": [
(4, self.env.ref("base.group_user").id),
],
}
)
def test_call_relation_action(self):
"""Test calling relations action. Should be possible with simple user rights"""
try:
self.partner_01_person.with_user(self.user).action_view_relations()
except exceptions.AccessError:
self.fail("action_view_relations() raised AccessError unexpectedly!")
| 34.241379
| 993
|
10,871
|
py
|
PYTHON
|
15.0
|
# Copyright 2013-2018 Therp BV <https://therp.nl>.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
"""Define the type of relations that can exist between partners."""
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
from odoo.osv.expression import AND, OR
HANDLE_INVALID_ONCHANGE = [
("restrict", _("Do not allow change that will result in invalid relations")),
("ignore", _("Allow existing relations that do not fit changed conditions")),
("end", _("End relations per today, if they do not fit changed conditions")),
("delete", _("Delete relations that do not fit changed conditions")),
]
class ResPartnerRelationType(models.Model):
"""Model that defines relation types that might exist between partners"""
_name = "res.partner.relation.type"
_description = "Partner Relation Type"
_order = "name"
name = fields.Char(required=True, translate=True)
name_inverse = fields.Char(string="Inverse name", required=True, translate=True)
contact_type_left = fields.Selection(
selection="get_partner_types", string="Left partner type"
)
contact_type_right = fields.Selection(
selection="get_partner_types", string="Right partner type"
)
partner_category_left = fields.Many2one(
comodel_name="res.partner.category", string="Left partner category"
)
partner_category_right = fields.Many2one(
comodel_name="res.partner.category", string="Right partner category"
)
allow_self = fields.Boolean(
string="Reflexive",
help="This relation can be set up with the same partner left and " "right",
default=False,
)
is_symmetric = fields.Boolean(
string="Symmetric",
help="This relation is the same from right to left as from left to" " right",
default=False,
)
handle_invalid_onchange = fields.Selection(
selection=HANDLE_INVALID_ONCHANGE,
string="Invalid relation handling",
required=True,
default="restrict",
help="When adding relations criteria like partner type and category"
" are checked.\n"
"However when you change the criteria, there might be relations"
" that do not fit the new criteria.\n"
"Specify how this situation should be handled.",
)
@api.model
def get_partner_types(self):
"""A partner can be an organisation or an individual."""
# pylint: disable=no-self-use
return [("c", _("Organisation")), ("p", _("Person"))]
@api.model
def _end_active_relations(self, relations):
"""End the relations that are active.
If a relation is current, that is, if it has a start date
in the past and end date in the future (or no end date),
the end date will be set to the current date.
If a relation has a end date in the past, then it is inactive and
will not be modified.
:param relations: a recordset of relations (not necessarily all active)
"""
today = fields.Date.today()
for relation in relations:
if relation.date_start and relation.date_start >= today:
relation.unlink()
elif not relation.date_end or relation.date_end > today:
relation.write({"date_end": today})
def check_existing(self, vals):
"""Check wether records exist that do not fit new criteria."""
relation_model = self.env["res.partner.relation"]
def get_type_condition(vals, side):
"""Add if needed check for contact type."""
fieldname1 = "contact_type_%s" % side
fieldname2 = "%s_partner_id.is_company" % side
contact_type = fieldname1 in vals and vals[fieldname1] or False
if contact_type == "c":
# Records that are not companies are invalid:
return [(fieldname2, "=", False)]
if contact_type == "p":
# Records that are companies are invalid:
return [(fieldname2, "=", True)]
return []
def get_category_condition(vals, side):
"""Add if needed check for partner category."""
fieldname1 = "partner_category_%s" % side
fieldname2 = "%s_partner_id.category_id" % side
category_id = fieldname1 in vals and vals[fieldname1] or False
if category_id:
# Records that do not have the specified category are invalid:
return [(fieldname2, "not in", [category_id])]
return []
for this in self:
handling = (
"handle_invalid_onchange" in vals
and vals["handle_invalid_onchange"]
or this.handle_invalid_onchange
)
if handling == "ignore":
continue
invalid_conditions = []
for side in ["left", "right"]:
invalid_conditions = OR(
[invalid_conditions, get_type_condition(vals, side)]
)
invalid_conditions = OR(
[invalid_conditions, get_category_condition(vals, side)]
)
if not invalid_conditions:
return
# only look at relations for this type
invalid_domain = AND([[("type_id", "=", this.id)], invalid_conditions])
invalid_relations = relation_model.with_context(active_test=False).search(
invalid_domain
)
if invalid_relations:
if handling == "restrict":
raise ValidationError(
_(
"There are already relations not satisfying the"
" conditions for partner type or category."
)
)
elif handling == "delete":
invalid_relations.unlink()
else:
self._end_active_relations(invalid_relations)
def _get_reflexive_relations(self):
"""Get all reflexive relations for this relation type.
:return: a recordset of res.partner.relation.
"""
self.env.cr.execute(
"""
SELECT id FROM res_partner_relation
WHERE left_partner_id = right_partner_id
AND type_id = %(relation_type_id)s
""",
{"relation_type_id": self.id},
)
reflexive_relation_ids = [r[0] for r in self.env.cr.fetchall()]
return self.env["res.partner.relation"].browse(reflexive_relation_ids)
def _check_no_existing_reflexive_relations(self):
"""Check that no reflexive relation exists for these relation types."""
for relation_type in self:
relations = relation_type._get_reflexive_relations()
if relations:
raise ValidationError(
_(
"Reflexivity could not be disabled for the relation "
"type {relation_type}. There are existing reflexive "
"relations defined for the following partners: "
"{partners}"
).format(
relation_type=relation_type.display_name,
partners=relations.mapped("left_partner_id.display_name"),
)
)
def _delete_existing_reflexive_relations(self):
"""Delete existing reflexive relations for these relation types."""
for relation_type in self:
relations = relation_type._get_reflexive_relations()
relations.unlink()
def _end_active_reflexive_relations(self):
"""End active reflexive relations for these relation types."""
for relation_type in self:
reflexive_relations = relation_type._get_reflexive_relations()
self._end_active_relations(reflexive_relations)
def _handle_deactivation_of_allow_self(self):
"""Handle the deactivation of reflexivity on these relations types."""
restrict_relation_types = self.filtered(
lambda t: t.handle_invalid_onchange == "restrict"
)
restrict_relation_types._check_no_existing_reflexive_relations()
delete_relation_types = self.filtered(
lambda t: t.handle_invalid_onchange == "delete"
)
delete_relation_types._delete_existing_reflexive_relations()
end_relation_types = self.filtered(lambda t: t.handle_invalid_onchange == "end")
end_relation_types._end_active_reflexive_relations()
def _update_right_vals(self, vals):
"""Make sure that on symmetric relations, right vals follow left vals.
@attention: All fields ending in `_right` will have their values
replaced by the values of the fields whose names end
in `_left`.
"""
vals["name_inverse"] = vals.get("name", self.name)
# For all left keys in model, take value for right either from
# left key in vals, or if not present, from right key in self:
left_keys = [key for key in self._fields if key.endswith("_left")]
for left_key in left_keys:
right_key = left_key.replace("_left", "_right")
vals[right_key] = vals.get(left_key, self[left_key])
if hasattr(vals[right_key], "id"):
vals[right_key] = vals[right_key].id
@api.model
def create(self, vals):
if vals.get("is_symmetric"):
self._update_right_vals(vals)
return super(ResPartnerRelationType, self).create(vals)
def write(self, vals):
"""Handle existing relations if conditions change."""
self.check_existing(vals)
for rec in self:
rec_vals = vals.copy()
if rec_vals.get("is_symmetric", rec.is_symmetric):
self._update_right_vals(rec_vals)
super(ResPartnerRelationType, rec).write(rec_vals)
allow_self_disabled = "allow_self" in vals and not vals["allow_self"]
if allow_self_disabled:
self._handle_deactivation_of_allow_self()
return True
def unlink(self):
"""Allow delete of relation type, even when connections exist.
Relations can be deleted if relation type allows it.
"""
relation_model = self.env["res.partner.relation"]
for rec in self:
if rec.handle_invalid_onchange == "delete":
# Automatically delete relations, so existing relations
# do not prevent unlink of relation type:
relations = relation_model.search([("type_id", "=", rec.id)])
relations.unlink()
return super(ResPartnerRelationType, self).unlink()
| 41.811538
| 10,871
|
17,816
|
py
|
PYTHON
|
15.0
|
# Copyright 2014-2018 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
# pylint: disable=method-required-super
import collections
import logging
from psycopg2.extensions import AsIs
from odoo import _, api, fields, models
from odoo.exceptions import MissingError, ValidationError
from odoo.tools import drop_view_if_exists
_logger = logging.getLogger(__name__)
# Register relations
RELATIONS_SQL = """\
SELECT
(rel.id * %%(padding)s) + %(key_offset)s AS id,
'res.partner.relation' AS res_model,
rel.id AS res_id,
rel.left_partner_id AS this_partner_id,
rel.right_partner_id AS other_partner_id,
rel.type_id,
rel.date_start,
rel.date_end,
%(is_inverse)s as is_inverse
%(extra_additional_columns)s
FROM res_partner_relation rel"""
# Register inverse relations
RELATIONS_SQL_INVERSE = """\
SELECT
(rel.id * %%(padding)s) + %(key_offset)s AS id,
'res.partner.relation',
rel.id,
rel.right_partner_id,
rel.left_partner_id,
rel.type_id,
rel.date_start,
rel.date_end,
%(is_inverse)s as is_inverse
%(extra_additional_columns)s
FROM res_partner_relation rel"""
class ResPartnerRelationAll(models.Model):
"""Model to show each relation from two sides."""
_auto = False
_log_access = False
_name = "res.partner.relation.all"
_description = "All (non-inverse + inverse) relations between partners"
_order = "this_partner_id, type_selection_id, date_end desc, date_start desc"
res_model = fields.Char(
string="Resource Model",
readonly=True,
required=True,
help="The database object this relation is based on.",
)
res_id = fields.Integer(
string="Resource ID",
readonly=True,
required=True,
help="The id of the object in the model this relation is based on.",
)
this_partner_id = fields.Many2one(
comodel_name="res.partner", string="One Partner", required=True
)
other_partner_id = fields.Many2one(comodel_name="res.partner", required=True)
type_id = fields.Many2one(
comodel_name="res.partner.relation.type",
string="Underlying Relation Type",
readonly=True,
required=True,
)
date_start = fields.Date("Starting date")
date_end = fields.Date("Ending date")
is_inverse = fields.Boolean(
string="Is reverse type?",
readonly=True,
help="Inverse relations are from right to left partner.",
)
type_selection_id = fields.Many2one(
comodel_name="res.partner.relation.type.selection",
string="Relation Type",
required=True,
)
active = fields.Boolean(
readonly=True,
help="Records with date_end in the past are inactive",
)
any_partner_id = fields.Many2many(
comodel_name="res.partner",
string="Partner",
compute=lambda self: self.update({"any_partner_id": None}),
search="_search_any_partner_id",
)
def register_specification(self, register, base_name, is_inverse, select_sql):
_last_key_offset = register["_lastkey"]
key_name = base_name + (is_inverse and "_inverse" or "")
assert key_name not in register
assert "%%(padding)s" in select_sql
assert "%(key_offset)s" in select_sql
assert "%(is_inverse)s" in select_sql
_last_key_offset += 1
register["_lastkey"] = _last_key_offset
register[key_name] = dict(
base_name=base_name,
is_inverse=is_inverse,
key_offset=_last_key_offset,
select_sql=select_sql
% {
"key_offset": _last_key_offset,
"is_inverse": is_inverse,
"extra_additional_columns": self._get_additional_relation_columns(),
},
)
def get_register(self):
register = collections.OrderedDict()
register["_lastkey"] = -1
self.register_specification(register, "relation", False, RELATIONS_SQL)
self.register_specification(register, "relation", True, RELATIONS_SQL_INVERSE)
return register
def get_select_specification(self, base_name, is_inverse):
register = self.get_register()
key_name = base_name + (is_inverse and "_inverse" or "")
return register[key_name]
def _get_statement(self):
"""Allow other modules to add to statement."""
register = self.get_register()
union_select = " UNION ".join(
[register[key]["select_sql"] for key in register if key != "_lastkey"]
)
return """\
CREATE OR REPLACE VIEW %%(table)s AS
WITH base_selection AS (%(union_select)s)
SELECT
bas.*,
CASE
WHEN NOT bas.is_inverse OR typ.is_symmetric
THEN bas.type_id * 2
ELSE (bas.type_id * 2) + 1
END as type_selection_id,
(bas.date_end IS NULL OR bas.date_end >= current_date) AS active
%%(additional_view_fields)s
FROM base_selection bas
JOIN res_partner_relation_type typ ON (bas.type_id = typ.id)
%%(additional_tables)s
""" % {
"union_select": union_select
}
def _get_padding(self):
"""Utility function to define padding in one place."""
return 100
def _get_additional_relation_columns(self):
"""Get additionnal columns from res_partner_relation.
This allows to add fields to the model res.partner.relation
and display these fields in the res.partner.relation.all list view.
:return: ', rel.column_a, rel.column_b_id'
"""
return ""
def _get_additional_view_fields(self):
"""Allow inherit models to add fields to view.
If fields are added, the resulting string must have each field
prepended by a comma, like so:
return ', typ.allow_self, typ.left_partner_category'
"""
return ""
def _get_additional_tables(self):
"""Allow inherit models to add tables (JOIN's) to view.
Example:
return 'JOIN type_extention ext ON (bas.type_id = ext.id)'
"""
return ""
def _auto_init(self):
cr = self._cr
drop_view_if_exists(cr, self._table)
cr.execute(
self._get_statement(),
{
"table": AsIs(self._table),
"padding": self._get_padding(),
"additional_view_fields": AsIs(self._get_additional_view_fields()),
"additional_tables": AsIs(self._get_additional_tables()),
},
)
return super(ResPartnerRelationAll, self)._auto_init()
@api.model
def _search_any_partner_id(self, operator, value):
"""Search relation with partner, no matter on which side."""
# pylint: disable=no-self-use
return [
"|",
("this_partner_id", operator, value),
("other_partner_id", operator, value),
]
def name_get(self):
return {
this.id: "%s %s %s"
% (
this.this_partner_id.name,
this.type_selection_id.display_name,
this.other_partner_id.name,
)
for this in self
}
@api.onchange("type_selection_id")
def onchange_type_selection_id(self):
"""Add domain on partners according to category and contact_type."""
def check_partner_domain(partner, partner_domain, side):
"""Check wether partner_domain results in empty selection
for partner, or wrong selection of partner already selected.
"""
warning = {}
if partner:
test_domain = [("id", "=", partner.id)] + partner_domain
else:
test_domain = partner_domain
partner_model = self.env["res.partner"]
partners_found = partner_model.search(test_domain, limit=1)
if not partners_found:
warning["title"] = _("Error!")
if partner:
warning["message"] = (
_("%s partner incompatible with relation type.") % side.title()
)
else:
warning["message"] = (
_("No %s partner available for relation type.") % side
)
return warning
this_partner_domain = []
other_partner_domain = []
if self.type_selection_id.contact_type_this:
this_partner_domain.append(
("is_company", "=", self.type_selection_id.contact_type_this == "c")
)
if self.type_selection_id.partner_category_this:
this_partner_domain.append(
("category_id", "in", self.type_selection_id.partner_category_this.ids)
)
if self.type_selection_id.contact_type_other:
other_partner_domain.append(
("is_company", "=", self.type_selection_id.contact_type_other == "c")
)
if self.type_selection_id.partner_category_other:
other_partner_domain.append(
("category_id", "in", self.type_selection_id.partner_category_other.ids)
)
result = {
"domain": {
"this_partner_id": this_partner_domain,
"other_partner_id": other_partner_domain,
}
}
# Check wether domain results in no choice or wrong choice of partners:
warning = {}
partner_model = self.env["res.partner"]
if this_partner_domain:
this_partner = False
if bool(self.this_partner_id.id):
this_partner = self.this_partner_id
else:
this_partner_id = (
"default_this_partner_id" in self.env.context
and self.env.context["default_this_partner_id"]
or "active_id" in self.env.context
and self.env.context["active_id"]
or False
)
if this_partner_id:
this_partner = partner_model.browse(this_partner_id)
warning = check_partner_domain(this_partner, this_partner_domain, _("this"))
if not warning and other_partner_domain:
warning = check_partner_domain(
self.other_partner_id, other_partner_domain, _("other")
)
if warning:
result["warning"] = warning
return result
@api.onchange("this_partner_id", "other_partner_id")
def onchange_partner_id(self):
"""Set domain on type_selection_id based on partner(s) selected."""
def check_type_selection_domain(type_selection_domain):
"""If type_selection_id already selected, check wether it
is compatible with the computed type_selection_domain. An empty
selection can practically only occur in a practically empty
database, and will not lead to problems. Therefore not tested.
"""
warning = {}
if not (type_selection_domain and self.type_selection_id):
return warning
test_domain = [
("id", "=", self.type_selection_id.id)
] + type_selection_domain
type_model = self.env["res.partner.relation.type.selection"]
types_found = type_model.search(test_domain, limit=1)
if not types_found:
warning["title"] = _("Error!")
warning["message"] = _(
"Relation type incompatible with selected partner(s)."
)
return warning
type_selection_domain = []
if self.this_partner_id:
type_selection_domain += [
"|",
("contact_type_this", "=", False),
("contact_type_this", "=", self.this_partner_id.get_partner_type()),
"|",
("partner_category_this", "=", False),
("partner_category_this", "in", self.this_partner_id.category_id.ids),
]
if self.other_partner_id:
type_selection_domain += [
"|",
("contact_type_other", "=", False),
("contact_type_other", "=", self.other_partner_id.get_partner_type()),
"|",
("partner_category_other", "=", False),
("partner_category_other", "in", self.other_partner_id.category_id.ids),
]
result = {"domain": {"type_selection_id": type_selection_domain}}
# Check wether domain results in no choice or wrong choice for
# type_selection_id:
warning = check_type_selection_domain(type_selection_domain)
if warning:
result["warning"] = warning
return result
@api.model
def _correct_vals(self, vals, type_selection):
"""Fill left and right partner from this and other partner."""
vals = vals.copy()
if "type_selection_id" in vals:
vals["type_id"] = type_selection.type_id.id
if type_selection.is_inverse:
if "this_partner_id" in vals:
vals["right_partner_id"] = vals["this_partner_id"]
if "other_partner_id" in vals:
vals["left_partner_id"] = vals["other_partner_id"]
else:
if "this_partner_id" in vals:
vals["left_partner_id"] = vals["this_partner_id"]
if "other_partner_id" in vals:
vals["right_partner_id"] = vals["other_partner_id"]
# Delete values not in underlying table:
for key in (
"this_partner_id",
"type_selection_id",
"other_partner_id",
"is_inverse",
):
if key in vals:
del vals[key]
return vals
def get_base_resource(self):
"""Get base resource from res_model and res_id."""
self.ensure_one()
base_model = self.env[self.res_model]
return base_model.browse([self.res_id])
def write_resource(self, base_resource, vals):
"""write handled by base resource."""
self.ensure_one()
# write for models other then res.partner.relation SHOULD
# be handled in inherited models:
relation_model = self.env["res.partner.relation"]
assert self.res_model == relation_model._name
base_resource.write(vals)
base_resource.flush()
@api.model
def _get_type_selection_from_vals(self, vals):
"""Get type_selection_id straight from vals or compute from type_id."""
type_selection_id = vals.get("type_selection_id", False)
if not type_selection_id:
type_id = vals.get("type_id", False)
if type_id:
is_inverse = vals.get("is_inverse")
type_selection_id = type_id * 2 + (is_inverse and 1 or 0)
return (
type_selection_id
and self.type_selection_id.browse(type_selection_id)
or False
)
def write(self, vals):
"""For model 'res.partner.relation' call write on underlying model."""
new_type_selection = self._get_type_selection_from_vals(vals)
for rec in self:
type_selection = new_type_selection or rec.type_selection_id
vals = rec._correct_vals(vals, type_selection)
base_resource = rec.get_base_resource()
rec.write_resource(base_resource, vals)
# Invalidate cache to make res.partner.relation.all reflect changes
# in underlying res.partner.relation:
self.invalidate_cache(None, self.ids)
return True
@api.model
def _compute_base_name(self, type_selection):
"""This will be overridden for each inherit model."""
return "relation"
@api.model
def _compute_id(self, base_resource, type_selection):
"""Compute id. Allow for enhancements in inherit model."""
base_name = self._compute_base_name(type_selection)
key_offset = self.get_select_specification(
base_name, type_selection.is_inverse
)["key_offset"]
return base_resource.id * self._get_padding() + key_offset
@api.model
def create_resource(self, vals, type_selection):
relation_model = self.env["res.partner.relation"]
return relation_model.create(vals)
@api.model
def create(self, vals):
"""Divert non-problematic creates to underlying table.
Create a res.partner.relation but return the converted id.
"""
type_selection = self._get_type_selection_from_vals(vals)
if not type_selection: # Should not happen
raise ValidationError(_("No relation type specified in vals: %s.") % vals)
vals = self._correct_vals(vals, type_selection)
base_resource = self.create_resource(vals, type_selection)
res_id = self._compute_id(base_resource, type_selection)
return self.browse(res_id)
def unlink_resource(self, base_resource):
"""Delegate unlink to underlying model."""
self.ensure_one()
# unlink for models other then res.partner.relation SHOULD
# be handled in inherited models:
relation_model = self.env["res.partner.relation"]
assert self.res_model == relation_model._name
base_resource.unlink()
def unlink(self):
"""For model 'res.partner.relation' call unlink on underlying model."""
for rec in self:
try:
base_resource = rec.get_base_resource()
except MissingError:
continue
rec.unlink_resource(base_resource)
return True
| 37.507368
| 17,816
|
4,908
|
py
|
PYTHON
|
15.0
|
# Copyright 2013-2017 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
"""
For the model defined here _auto is set to False to prevent creating a
database file. The model is based on a SQL view based on
res_partner_relation_type where each type is included in the
result set twice, so it appears that the connection type and the inverse
type are separate records..
The original function _auto_init is still called because this function
normally (if _auto == True) not only creates the db tables, but it also takes
care of registering all fields in ir_model_fields. This is needed to make
the field labels translatable.
"""
from psycopg2.extensions import AsIs
from odoo import api, fields, models
from odoo.tools import drop_view_if_exists
class ResPartnerRelationTypeSelection(models.Model):
"""Virtual relation types"""
_name = "res.partner.relation.type.selection"
_description = "All relation types"
_auto = False # Do not try to create table in _auto_init(..)
_foreign_keys = []
_log_access = False
_order = "name asc"
@api.model
def get_partner_types(self):
"""Partner types are defined by model res.partner.relation.type."""
# pylint: disable=no-self-use
rprt_model = self.env["res.partner.relation.type"]
return rprt_model.get_partner_types()
type_id = fields.Many2one(comodel_name="res.partner.relation.type")
name = fields.Char()
contact_type_this = fields.Selection(
selection="get_partner_types", string="Current record's partner type"
)
is_inverse = fields.Boolean(
string="Is reverse type?",
help="Inverse relations are from right to left partner.",
)
contact_type_other = fields.Selection(
selection="get_partner_types", string="Other record's partner type"
)
partner_category_this = fields.Many2one(
comodel_name="res.partner.category", string="Current record's category"
)
partner_category_other = fields.Many2one(
comodel_name="res.partner.category", string="Other record's category"
)
allow_self = fields.Boolean(string="Reflexive")
is_symmetric = fields.Boolean(string="Symmetric")
def _get_additional_view_fields(self):
"""Allow inherit models to add fields to view.
If fields are added, the resulting string must have each field
prepended by a comma, like so:
return ', typ.allow_self, typ.left_partner_category'
"""
return ""
def _get_additional_tables(self):
"""Allow inherit models to add tables (JOIN's) to view.
Example:
return 'JOIN type_extention ext ON (bas.type_id = ext.id)'
"""
return ""
def _auto_init(self):
cr = self._cr
drop_view_if_exists(cr, self._table)
cr.execute(
"""\
CREATE OR REPLACE VIEW %(table)s AS
WITH selection_type AS (
SELECT
id * 2 AS id,
id AS type_id,
name AS name,
False AS is_inverse,
contact_type_left AS contact_type_this,
contact_type_right AS contact_type_other,
partner_category_left AS partner_category_this,
partner_category_right AS partner_category_other
FROM %(underlying_table)s
UNION SELECT
(id * 2) + 1,
id,
name_inverse,
True,
contact_type_right,
contact_type_left,
partner_category_right,
partner_category_left
FROM %(underlying_table)s
WHERE not is_symmetric
)
SELECT
bas.*,
typ.allow_self,
typ.is_symmetric
%(additional_view_fields)s
FROM selection_type bas
JOIN res_partner_relation_type typ ON (bas.type_id = typ.id)
%(additional_tables)s
""",
{
"table": AsIs(self._table),
"underlying_table": AsIs("res_partner_relation_type"),
"additional_view_fields": AsIs(self._get_additional_view_fields()),
"additional_tables": AsIs(self._get_additional_tables()),
},
)
return super(ResPartnerRelationTypeSelection, self)._auto_init()
def name_get(self):
"""Get name or name_inverse from underlying model."""
return [
(
this.id,
this.is_inverse
and this.type_id.name_inverse
or this.type_id.display_name,
)
for this in self
]
@api.model
def name_search(self, name="", args=None, operator="ilike", limit=100):
"""Search for name or inverse name in underlying model."""
# pylint: disable=no-value-for-parameter
return self.search(
[
"|",
("type_id.name", operator, name),
("type_id.name_inverse", operator, name),
]
+ (args or []),
limit=limit,
).name_get()
| 33.387755
| 4,908
|
5,759
|
py
|
PYTHON
|
15.0
|
# Copyright 2013-2017 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
# pylint: disable=api-one-deprecated
"""Store relations (connections) between partners."""
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ResPartnerRelation(models.Model):
"""Model res.partner.relation is used to describe all links or relations
between partners in the database.
This model is actually only used to store the data. The model
res.partner.relation.all, based on a view that contains each record
two times, once for the normal relation, once for the inverse relation,
will be used to maintain the data.
"""
_name = "res.partner.relation"
_description = "Partner relation"
left_partner_id = fields.Many2one(
comodel_name="res.partner",
string="Source Partner",
required=True,
auto_join=True,
ondelete="cascade",
)
right_partner_id = fields.Many2one(
comodel_name="res.partner",
string="Destination Partner",
required=True,
auto_join=True,
ondelete="cascade",
)
type_id = fields.Many2one(
comodel_name="res.partner.relation.type",
string="Type",
required=True,
auto_join=True,
)
date_start = fields.Date("Starting date")
date_end = fields.Date("Ending date")
@api.model
def create(self, vals):
"""Override create to correct values, before being stored."""
context = self.env.context
if "left_partner_id" not in vals and context.get("active_id"):
vals["left_partner_id"] = context.get("active_id")
return super(ResPartnerRelation, self).create(vals)
@api.constrains("date_start", "date_end")
def _check_dates(self):
"""End date should not be before start date, if not filled
:raises ValidationError: When constraint is violated
"""
for record in self:
if (
record.date_start
and record.date_end
and record.date_start > record.date_end
):
raise ValidationError(
_("The starting date cannot be after the ending date.")
)
@api.constrains("left_partner_id", "type_id")
def _check_partner_left(self):
"""Check left partner for required company or person
:raises ValidationError: When constraint is violated
"""
self._check_partner("left")
@api.constrains("right_partner_id", "type_id")
def _check_partner_right(self):
"""Check right partner for required company or person
:raises ValidationError: When constraint is violated
"""
self._check_partner("right")
def _check_partner(self, side):
"""Check partner for required company or person, and for category
:param str side: left or right
:raises ValidationError: When constraint is violated
"""
for record in self:
assert side in ["left", "right"]
ptype = getattr(record.type_id, "contact_type_%s" % side)
partner = getattr(record, "%s_partner_id" % side)
if (ptype == "c" and not partner.is_company) or (
ptype == "p" and partner.is_company
):
raise ValidationError(
_("The %s partner is not applicable for this " "relation type.")
% side
)
category = getattr(record.type_id, "partner_category_%s" % side)
if category and category.id not in partner.category_id.ids:
raise ValidationError(
_(
"The {partner} partner does not have category {category}."
).format(partner=side, category=category.name)
)
@api.constrains("left_partner_id", "right_partner_id")
def _check_not_with_self(self):
"""Not allowed to link partner to same partner
:raises ValidationError: When constraint is violated
"""
for record in self:
if record.left_partner_id == record.right_partner_id:
if not (record.type_id and record.type_id.allow_self):
raise ValidationError(
_("Partners cannot have a relation with themselves.")
)
@api.constrains(
"left_partner_id", "type_id", "right_partner_id", "date_start", "date_end"
)
def _check_relation_uniqueness(self):
"""Forbid multiple active relations of the same type between the same
partners
:raises ValidationError: When constraint is violated
"""
# pylint: disable=no-member
# pylint: disable=no-value-for-parameter
for record in self:
domain = [
("type_id", "=", record.type_id.id),
("id", "!=", record.id),
("left_partner_id", "=", record.left_partner_id.id),
("right_partner_id", "=", record.right_partner_id.id),
]
if record.date_start:
domain += [
"|",
("date_end", "=", False),
("date_end", ">=", record.date_start),
]
if record.date_end:
domain += [
"|",
("date_start", "=", False),
("date_start", "<=", record.date_end),
]
if record.search(domain):
raise ValidationError(
_("There is already a similar relation with " "overlapping dates")
)
| 36.916667
| 5,759
|
7,701
|
py
|
PYTHON
|
15.0
|
# Copyright 2013-2017 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
"""Support connections between partners."""
import numbers
from odoo import _, api, exceptions, fields, models
from odoo.osv.expression import FALSE_LEAF, OR, is_leaf
class ResPartner(models.Model):
"""Extend partner with relations and allow to search for relations
in various ways.
"""
# pylint: disable=invalid-name
# pylint: disable=no-member
_inherit = "res.partner"
relation_count = fields.Integer(compute="_compute_relation_count")
relation_all_ids = fields.One2many(
comodel_name="res.partner.relation.all",
inverse_name="this_partner_id",
string="All relations with current partner",
auto_join=True,
search=False,
copy=False,
)
search_relation_type_id = fields.Many2one(
comodel_name="res.partner.relation.type.selection",
compute=lambda self: self.update({"search_relation_type_id": None}),
search="_search_relation_type_id",
string="Has relation of type",
)
search_relation_partner_id = fields.Many2one(
comodel_name="res.partner",
compute=lambda self: self.update({"search_relation_partner_id": None}),
search="_search_related_partner_id",
string="Has relation with",
)
search_relation_date = fields.Date(
compute=lambda self: self.update({"search_relation_date": None}),
search="_search_relation_date",
string="Relation valid",
)
search_relation_partner_category_id = fields.Many2one(
comodel_name="res.partner.category",
compute=lambda self: self.update({"search_relation_partner_category_id": None}),
search="_search_related_partner_category_id",
string="Has relation with a partner in category",
)
@api.depends("relation_all_ids")
def _compute_relation_count(self):
"""Count the number of relations this partner has for Smart Button
Don't count inactive relations.
"""
for rec in self:
rec.relation_count = len(rec.relation_all_ids.filtered("active"))
@api.model
def _search_relation_type_id(self, operator, value):
"""Search partners based on their type of relations."""
result = []
SUPPORTED_OPERATORS = (
"=",
"!=",
"like",
"not like",
"ilike",
"not ilike",
"in",
"not in",
)
if operator not in SUPPORTED_OPERATORS:
raise exceptions.ValidationError(
_('Unsupported search operator "%s"') % operator
)
type_selection_model = self.env["res.partner.relation.type.selection"]
relation_type_selection = []
if operator == "=" and isinstance(value, numbers.Integral):
relation_type_selection += type_selection_model.browse(value)
elif operator == "!=" and isinstance(value, numbers.Integral):
relation_type_selection = type_selection_model.search(
[("id", operator, value)]
)
else:
relation_type_selection = type_selection_model.search(
[
"|",
("type_id.name", operator, value),
("type_id.name_inverse", operator, value),
]
)
if not relation_type_selection:
result = [FALSE_LEAF]
for relation_type in relation_type_selection:
result = OR(
[
result,
[("relation_all_ids.type_selection_id.id", "=", relation_type.id)],
]
)
return result
@api.model
def _search_related_partner_id(self, operator, value):
"""Find partner based on relation with other partner."""
# pylint: disable=no-self-use
return [("relation_all_ids.other_partner_id", operator, value)]
@api.model
def _search_relation_date(self, operator, value):
"""Look only for relations valid at date of search."""
# pylint: disable=no-self-use
return [
"&",
"|",
("relation_all_ids.date_start", "=", False),
("relation_all_ids.date_start", "<=", value),
"|",
("relation_all_ids.date_end", "=", False),
("relation_all_ids.date_end", ">=", value),
]
@api.model
def _search_related_partner_category_id(self, operator, value):
"""Search for partner related to a partner with search category."""
# pylint: disable=no-self-use
return [("relation_all_ids.other_partner_id.category_id", operator, value)]
@api.model
def search(self, args, offset=0, limit=None, order=None, count=False):
"""Inject searching for current relation date if we search for
relation properties and no explicit date was given.
"""
# pylint: disable=arguments-differ
# pylint: disable=no-value-for-parameter
date_args = []
for arg in args:
if (
is_leaf(arg)
and isinstance(arg[0], str)
and arg[0].startswith("search_relation")
):
if arg[0] == "search_relation_date":
date_args = []
break
if not date_args:
date_args = [("search_relation_date", "=", fields.Date.today())]
# because of auto_join, we have to do the active test by hand
active_args = []
if self.env.context.get("active_test", True):
for arg in args:
if (
is_leaf(arg)
and isinstance(arg[0], str)
and arg[0].startswith("search_relation")
):
active_args = [("relation_all_ids.active", "=", True)]
break
return super(ResPartner, self).search(
args + date_args + active_args,
offset=offset,
limit=limit,
order=order,
count=count,
)
def get_partner_type(self):
"""Get partner type for relation.
:return: 'c' for company or 'p' for person
:rtype: str
"""
self.ensure_one()
return "c" if self.is_company else "p"
def action_view_relations(self):
for contact in self:
relation_model = self.env["res.partner.relation.all"]
relation_ids = relation_model.search(
[
"|",
("this_partner_id", "=", contact.id),
("other_partner_id", "=", contact.id),
]
)
action = self.env["ir.actions.act_window"]._for_xml_id(
"partner_multi_relation.action_res_partner_relation_all"
)
action["domain"] = [("id", "in", relation_ids.ids)]
context = action.get("context", "{}").strip()[1:-1]
elements = context.split(",") if context else []
to_add = [
"""'search_default_this_partner_id': {0},
'default_this_partner_id': {0},
'active_model': 'res.partner',
'active_id': {0},
'active_ids': [{0}],
'active_test': False""".format(
contact.id
)
]
context = "{" + ", ".join(elements + to_add) + "}"
action["context"] = context
return action
| 37.383495
| 7,701
|
1,018
|
py
|
PYTHON
|
15.0
|
# Copyright 2014-2016 Akretion (Alexis de Lattre
# <alexis.delattre@akretion.com>)
# Copyright 2014 Lorenzo Battistini <lorenzo.battistini@agilebg.com>
# Copyright 2016-2021 Tecnativa - Pedro M. Baeza
# Copyright 2017 ForgeFlow, S.L. <.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Base Location Geonames Import",
"version": "15.0.1.0.2",
"development_status": "Mature",
"category": "Partner Management",
"license": "AGPL-3",
"summary": "Import zip entries from Geonames",
"author": (
"Akretion,"
"Agile Business Group,"
"Tecnativa,"
"AdaptiveCity,"
"Odoo Community Association (OCA)"
),
"website": "https://github.com/OCA/partner-contact",
"depends": ["base_location"],
"data": [
"security/ir.model.access.csv",
"data/res_country_data.xml",
"views/res_country_view.xml",
"wizard/geonames_import_view.xml",
],
"installable": True,
}
| 32.83871
| 1,018
|
6,912
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2021 Tecnativa - Pedro M. Baeza
# Copyright 2020 Manuel Regidor <manuel.regidor@sygel.es>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.exceptions import UserError
from odoo.tests import common
class TestBaseLocationGeonamesImport(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.country = cls.env.ref("base.mc")
cls.city = cls.env["res.city"].create(
{"name": "Test city", "country_id": cls.country.id}
)
cls.wizard = cls.env["city.zip.geonames.import"].create(
{"country_ids": [(6, 0, [cls.country.id])]}
)
cls.wrong_country = cls.env["res.country"].create(
{"name": "Wrong country", "code": "ZZYYXX"}
)
cls.wrong_wizard = cls.env["city.zip.geonames.import"].create(
{"country_ids": [(6, 0, [cls.wrong_country.id])]}
)
cls.country_2 = cls.env.ref("base.li")
cls.country_3 = cls.env.ref("base.sm")
cls.wizard_2 = cls.env["city.zip.geonames.import"].create(
{"country_ids": [(6, 0, [cls.country_2.id, cls.country_3.id])]}
)
cls.country_4 = cls.env.ref("base.ad")
cls.wizard_3 = cls.env["city.zip.geonames.import"].create(
{"country_ids": [(4, cls.country_4.id)]}
)
def test_import_country(self):
max_import = 10
self.wizard.with_context(max_import=max_import).run_import()
# Look if there are imported states for the country
state_count = self.env["res.country.state"].search_count(
[("country_id", "=", self.country.id)]
)
self.assertTrue(state_count)
# Look if there are imported zips
zip_count = self.env["res.city.zip"].search_count(
[("city_id.country_id", "=", self.country.id)]
)
self.assertEqual(zip_count, max_import)
# Look if there are imported cities
city_count = self.env["res.city"].search_count(
[("country_id", "=", self.country.id)]
)
self.assertTrue(city_count)
# Reimport again to see that there's no duplicates
self.wizard.with_context(max_import=max_import).run_import()
state_count2 = self.env["res.country.state"].search_count(
[("country_id", "=", self.country.id)]
)
self.assertEqual(state_count, state_count2)
city_count2 = self.env["res.city"].search_count(
[("country_id", "=", self.country.id)]
)
self.assertEqual(city_count, city_count2)
zip_count = self.env["res.city.zip"].search_count(
[("city_id.country_id", "=", self.country.id)]
)
self.assertEqual(zip_count, max_import)
def test_delete_old_entries(self):
zip_entry = self.env["res.city.zip"].create(
{"name": "Brussels", "city_id": self.city.id}
)
self.wizard.run_import()
self.assertFalse(zip_entry.exists())
city_entry = self.env["res.city"].create(
{"name": "Test city", "country_id": self.country.id}
)
self.wizard.run_import()
self.assertFalse(city_entry.exists())
def test_import_title(self):
self.wizard.letter_case = "title"
self.wizard.with_context(max_import=1).run_import()
city_zip = self.env["res.city.zip"].search(
[("city_id.country_id", "=", self.country.id)], limit=1
)
self.assertEqual(city_zip.city_id.name, city_zip.city_id.name.title())
city = self.env["res.city"].search(
[("country_id", "=", self.country.id)], limit=1
)
self.assertEqual(city.name, city.name.title())
def test_import_upper(self):
self.wizard.letter_case = "upper"
self.wizard.with_context(max_import=1).run_import()
city_zip = self.env["res.city.zip"].search(
[("city_id.country_id", "=", self.country.id)], limit=1
)
self.assertEqual(city_zip.city_id.name, city_zip.city_id.name.upper())
city = self.env["res.city"].search(
[("country_id", "=", self.country.id)], limit=1
)
self.assertEqual(city.name, city.name.upper())
def test_download_error(self):
"""Check that we get an error when trying to download
with a wrong country code"""
with self.assertRaises(UserError):
self.wrong_wizard.run_import()
def test_import_duplicated_city_name(self):
country = self.env.ref("base.us")
self.wizard.country_ids = [(6, 0, country.ids)]
parsed_csv = [
[
"US",
"95602",
"Auburn",
" California",
"CA",
"Placer",
"61",
"38.9829",
"-121.0944",
"4",
],
[
"US",
"95603",
"Auburn",
" California",
"CA",
"Placer",
"61",
"38.9115",
"-121.08",
"4",
],
[
"US",
"30011",
"Auburn",
" Georgia",
"GA",
"Barrow",
"13",
"34.0191",
"-83.8261",
"4",
],
]
self.wizard._process_csv(parsed_csv, country)
cities = self.env["res.city"].search([("name", "=", "Auburn")])
self.assertEqual(len(cities), 2)
mapping = [
["California", "95602"],
["California", "95603"],
["Georgia", "30011"],
]
for state_name, zip_code in mapping:
zip_entry = self.env["res.city.zip"].search(
[("city_id.country_id", "=", country.id), ("name", "=", zip_code)]
)
state = self.env["res.country.state"].search(
[("country_id", "=", country.id), ("name", "=", state_name)]
)
self.assertEqual(
zip_entry.city_id.state_id,
state,
"Incorrect state for {} {}".format(state_name, zip_code),
)
def test_import_countries(self):
max_import = 1
self.wizard_2.with_context(max_import=max_import).run_import()
# Look if there are imported zips
zip_country_2_count = self.env["res.city.zip"].search_count(
[("city_id.country_id", "=", self.country_2.id)]
)
zip_country_3_count = self.env["res.city.zip"].search_count(
[("city_id.country_id", "=", self.country_3.id)]
)
self.assertEqual(zip_country_2_count, max_import)
self.assertEqual(zip_country_3_count, max_import)
| 36
| 6,912
|
10,580
|
py
|
PYTHON
|
15.0
|
# Copyright 2014-2016 Akretion (Alexis de Lattre
# <alexis.delattre@akretion.com>)
# Copyright 2014 Lorenzo Battistini <lorenzo.battistini@agilebg.com>
# Copyright 2017 ForgeFlow, S.L. <.com>
# Copyright 2018 Aitor Bouzas <aitor.bouzas@adaptivecity.com>
# Copyright 2016-2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import csv
import io
import logging
import os
import tempfile
import zipfile
import requests
from odoo import _, api, fields, models
from odoo.exceptions import UserError
logger = logging.getLogger(__name__)
class CityZipGeonamesImport(models.TransientModel):
_name = "city.zip.geonames.import"
_description = "Import City Zips from Geonames"
country_ids = fields.Many2many("res.country", string="Countries")
letter_case = fields.Selection(
[("unchanged", "Unchanged"), ("title", "Title Case"), ("upper", "Upper Case")],
default="unchanged",
help="Converts retreived city and state names to Title Case "
"(upper case on each first letter of a word) or Upper Case "
"(all letters upper case).",
)
@api.model
def transform_city_name(self, city, country):
"""Override it for transforming city name (if needed)
:param city: Original city name
:param country: Country record
:return: Transformed city name
"""
res = city
if self.letter_case == "title":
res = city.title()
elif self.letter_case == "upper":
res = city.upper()
return res
@api.model
def _domain_search_city_zip(self, row, city_id=False):
domain = [("name", "=", row[1])]
if city_id:
domain += [("city_id", "=", city_id)]
return domain
@api.model
def select_city(self, row, country, state_id):
# This has to be done by SQL for performance reasons avoiding
# left join with ir_translation on the translatable field "name"
self.env.cr.execute(
"SELECT id, name FROM res_city "
"WHERE name = %s AND country_id = %s AND state_id = %s LIMIT 1",
(self.transform_city_name(row[2], country), country.id, state_id),
)
row_city = self.env.cr.fetchone()
return (row_city[0], row_city[1]) if row_city else (False, False)
@api.model
def select_zip(self, row, country, state_id):
city_id, _ = self.select_city(row, country, state_id)
return self.env["res.city.zip"].search(
self._domain_search_city_zip(row, city_id)
)
@api.model
def prepare_state(self, row, country):
return {
"name": row[country.geonames_state_name_column or 3],
"code": row[country.geonames_state_code_column or 4],
"country_id": country.id,
}
@api.model
def prepare_city(self, row, country, state_id):
vals = {
"name": self.transform_city_name(row[2], country),
"state_id": state_id,
"country_id": country.id,
}
return vals
@api.model
def prepare_zip(self, row, city_id):
vals = {"name": row[1], "city_id": city_id}
return vals
@api.model
def get_and_parse_csv(self, country):
country_code = country.code
config_url = self.env["ir.config_parameter"].get_param(
"geonames.url", default="http://download.geonames.org/export/zip/%s.zip"
)
url = config_url % country_code
logger.info("Starting to download %s" % url)
res_request = requests.get(url)
if res_request.status_code != requests.codes.ok:
# pylint: disable=translation-positional-used - Don't want to re-translate
raise UserError(
_("Got an error %d when trying to download the file %s.")
% (res_request.status_code, url)
)
f_geonames = zipfile.ZipFile(io.BytesIO(res_request.content))
tempdir = tempfile.mkdtemp(prefix="odoo")
f_geonames.extract("%s.txt" % country_code, tempdir)
data_file = open(
os.path.join(tempdir, "%s.txt" % country_code), "r", encoding="utf-8"
)
data_file.seek(0)
reader = csv.reader(data_file, delimiter=" ")
parsed_csv = [row for i, row in enumerate(reader)]
data_file.close()
logger.info("The geonames zipfile has been decompressed")
return parsed_csv
def _create_states(self, parsed_csv, search_states, max_import, country):
states_map = {}
if search_states:
states_map = {
state.code: state
for state in self.env["res.country.state"].search(
[("country_id", "=", country.id)]
)
}
# States
state_vals_set = set()
state_dict = {}
for i, row in enumerate(parsed_csv):
if max_import and i == max_import:
break
state = None
if search_states:
code = row[country.geonames_state_code_column or 4]
state = states_map.get(code)
if not state:
state_vals = self.prepare_state(row, country)
state_vals_set.add(
(state_vals["name"], state_vals["code"], state_vals["country_id"])
)
else:
state_dict[state.code] = state.id
state_vals_list = [
{"name": name, "code": code, "country_id": country_id}
for name, code, country_id in state_vals_set
]
logger.info("Importing %d states", len(state_vals_list))
created_states = self.env["res.country.state"].create(state_vals_list)
for i, vals in enumerate(state_vals_list):
state_dict[vals["code"]] = created_states[i].id
return state_dict
def _create_cities(
self, parsed_csv, search_cities, max_import, state_dict, country
):
# Cities
city_vals_set = set()
city_dict = {}
for i, row in enumerate(parsed_csv):
if max_import and i == max_import:
break
state_id = state_dict[row[country.geonames_state_code_column or 4]]
city_id, city_name = (
self.select_city(row, country, state_id)
if search_cities
else (False, False)
)
if not city_id:
city_vals = self.prepare_city(row, country, state_id)
city_vals_set.add(
(city_vals["name"], city_vals["state_id"], city_vals["country_id"])
)
else:
city_dict[(city_name, state_id)] = city_id
ctx = dict(self.env.context)
ctx.pop("lang", None) # make sure no translation is added
city_vals_list = [
{"name": name, "state_id": state_id, "country_id": country_id}
for name, state_id, country_id in city_vals_set
]
logger.info("Importing %d cities", len(city_vals_list))
# pylint: disable=context-overridden - It's legit to replace it in this case
created_cities = self.env["res.city"].with_context(ctx).create(city_vals_list)
for i, vals in enumerate(city_vals_list):
city_dict[(vals["name"], vals["state_id"])] = created_cities[i].id
return city_dict
def run_import(self):
for country in self.country_ids:
parsed_csv = self.get_and_parse_csv(country)
self._process_csv(parsed_csv, country)
return True
def _action_remove_old_records(self, model_name, old_records, country):
model = self.env[model_name]
items = model.browse(list(old_records))
try:
logger.info("removing %s entries" % model._name)
items.unlink()
logger.info(
"%d entries deleted for country %s" % (len(old_records), country.name)
)
except Exception:
for item in items:
try:
item.unlink()
except Exception:
logger.info(_("%d could not be deleted %") % item.name)
def _process_csv(self, parsed_csv, country):
state_model = self.env["res.country.state"]
zip_model = self.env["res.city.zip"]
res_city_model = self.env["res.city"]
# Store current record list
old_zips = set(zip_model.search([("city_id.country_id", "=", country.id)]).ids)
search_zips = len(old_zips) > 0
old_cities = set(res_city_model.search([("country_id", "=", country.id)]).ids)
search_cities = len(old_cities) > 0
current_states = state_model.search([("country_id", "=", country.id)])
search_states = len(current_states) > 0
max_import = self.env.context.get("max_import", 0)
logger.info("Starting to create the cities and/or city zip entries")
# Pre-create states and cities
state_dict = self._create_states(parsed_csv, search_states, max_import, country)
city_dict = self._create_cities(
parsed_csv, search_cities, max_import, state_dict, country
)
# Zips
zip_vals_list = []
for i, row in enumerate(parsed_csv):
if max_import and i == max_import:
break
# Don't search if there aren't any records
zip_code = False
state_id = state_dict[row[country.geonames_state_code_column or 4]]
if search_zips:
zip_code = self.select_zip(row, country, state_id)
if not zip_code:
city_id = city_dict[
(self.transform_city_name(row[2], country), state_id)
]
zip_vals = self.prepare_zip(row, city_id)
if zip_vals not in zip_vals_list:
zip_vals_list.append(zip_vals)
else:
old_zips.discard(zip_code.id)
zip_model.create(zip_vals_list)
if not max_import:
if old_zips:
self._action_remove_old_records("res.city.zip", old_zips, country)
old_cities -= set(city_dict.values())
if old_cities:
self._action_remove_old_records("res.city", old_cities, country)
logger.info(
"The wizard to create cities and/or city zip entries from "
"geonames has been successfully completed."
)
return True
| 39.04059
| 10,580
|
335
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Franco Tampieri, Freelancer http://franco.tampieri.info
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResCountry(models.Model):
_inherit = "res.country"
geonames_state_name_column = fields.Integer()
geonames_state_code_column = fields.Integer()
| 27.916667
| 335
|
1,076
|
py
|
PYTHON
|
15.0
|
# Copyright 2004-2010 Tiny SPRL http://tiny.be
# Copyright 2010-2012 ChriCar Beteiligungs- und Beratungs- GmbH
# http://www.camptocamp.at
# Copyright 2015 Antiun Ingenieria, SL (Madrid, Spain)
# http://www.antiun.com
# Antonio Espinosa <antonioea@antiun.com>
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Partner Identification Numbers",
"category": "Customer Relationship Management",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"depends": ["contacts"],
"data": [
"security/ir.model.access.csv",
"views/res_partner_id_category_view.xml",
"views/res_partner_id_number_view.xml",
"views/res_partner_view.xml",
],
"author": "ChriCar Beteiligungs- und Beratungs- GmbH,"
"Tecnativa,"
"Camptocamp,"
"ACSONE SA/NV,"
"LasLabs,"
"Onestein,"
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"development_status": "Production/Stable",
}
| 35.866667
| 1,076
|
4,636
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from psycopg2._psycopg import IntegrityError
from odoo.exceptions import UserError, ValidationError
from odoo.tests import common
from odoo.tools import mute_logger
class TestPartnerIdentificationBase(common.TransactionCase):
def test_create_id_category(self):
partner_id_category = self.env["res.partner.id_category"].create(
{"code": "id_code", "name": "id_name"}
)
self.assertEqual(partner_id_category.name, "id_name")
self.assertEqual(partner_id_category.code, "id_code")
@mute_logger("odoo.sql_db")
def test_update_partner_with_no_category(self):
partner_1 = self.env.ref("base.res_partner_1")
self.assertEqual(len(partner_1.id_numbers), 0)
# create without required category
with self.assertRaises(IntegrityError):
partner_1.write({"id_numbers": [(0, 0, {"name": "1234"})]})
def test_update_partner_with_category(self):
partner_1 = self.env.ref("base.res_partner_1")
partner_id_category = self.env["res.partner.id_category"].create(
{"code": "new_code", "name": "new_name"}
)
# successful creation
partner_1.write(
{
"id_numbers": [
(0, 0, {"name": "1234", "category_id": partner_id_category.id})
]
}
)
self.assertEqual(len(partner_1.id_numbers), 1)
self.assertEqual(partner_1.id_numbers.name, "1234")
# delete
partner_1.write({"id_numbers": [(5, 0, 0)]})
self.assertEqual(len(partner_1.id_numbers), 0)
class TestPartnerCategoryValidation(common.TransactionCase):
def test_partner_id_number_validation(self):
partner_id_category = self.env["res.partner.id_category"].create(
{
"code": "id_code",
"name": "id_name",
"validation_code": """
if id_number.name != '1234':
failed = True
""",
}
)
partner_1 = self.env.ref("base.res_partner_1")
with self.assertRaises(ValidationError), self.cr.savepoint():
partner_1.write(
{
"id_numbers": [
(0, 0, {"name": "01234", "category_id": partner_id_category.id})
]
}
)
partner_1.write(
{
"id_numbers": [
(0, 0, {"name": "1234", "category_id": partner_id_category.id})
]
}
)
self.assertEqual(len(partner_1.id_numbers), 1)
self.assertEqual(partner_1.id_numbers.name, "1234")
partner_id_category2 = self.env["res.partner.id_category"].create(
{
"code": "id_code2",
"name": "id_name2",
"validation_code": """
if id_number.name != '1235':
failed = True
""",
}
)
# check that the constrains is also checked when we change the
# associated category
with self.assertRaises(ValidationError), self.cr.savepoint():
partner_1.id_numbers.write({"category_id": partner_id_category2.id})
def test_bad_validation_code(self):
partner_id_category = self.env["res.partner.id_category"].create(
{
"code": "id_code",
"name": "id_name",
"validation_code": """
if id_number.name != '1234' # missing :
failed = True
""",
}
)
partner_1 = self.env.ref("base.res_partner_1")
with self.assertRaises(UserError):
partner_1.write(
{
"id_numbers": [
(0, 0, {"name": "1234", "category_id": partner_id_category.id})
]
}
)
def test_bad_validation_code_override(self):
"""It should allow a bad validation code if context overrides."""
partner_id_category = self.env["res.partner.id_category"].create(
{
"code": "id_code",
"name": "id_name",
"validation_code": """
if id_number.name != '1234' # missing :
failed = True
""",
}
)
partner_1 = self.env.ref("base.res_partner_1").with_context(id_no_validate=True)
partner_1.write(
{
"id_numbers": [
(0, 0, {"name": "1234", "category_id": partner_id_category.id})
]
}
)
| 35.121212
| 4,636
|
1,258
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 LasLabs Inc.
# Copyright 2018 ACSONE
# Copyright 2018 Camptocamp
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from odoo import fields, models
def setup_test_model(env, model_cls):
"""Pass a test model class and initialize it.
Courtesy of SBidoul from https://github.com/OCA/mis-builder :)
"""
model_cls._build_model(env.registry, env.cr)
env.registry.setup_models(env.cr)
env.registry.init_models(
env.cr, [model_cls._name], dict(env.context, update_custom_fields=True)
)
def teardown_test_model(env, model_cls):
"""Pass a test model class and deinitialize it.
Courtesy of SBidoul from https://github.com/OCA/mis-builder :)
"""
if not getattr(model_cls, "_teardown_no_delete", False):
del env.registry.models[model_cls._name]
env.registry.setup_models(env.cr)
class ResPartner(models.Model):
_name = "res.partner"
_inherit = "res.partner"
_teardown_no_delete = True
social_security = fields.Char(
compute=lambda s: s._compute_identification("social_security", "SSN"),
inverse=lambda s: s._inverse_identification("social_security", "SSN"),
search=lambda s, *a: s._search_identification("SSN", *a),
)
| 31.45
| 1,258
|
3,521
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.exceptions import ValidationError
from odoo.tests import common
from .fake_models import ResPartner, setup_test_model, teardown_test_model
class TestResPartner(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
setup_test_model(cls.env, ResPartner)
bad_cat = cls.env["res.partner.id_category"].create(
{"code": "another_code", "name": "another_name"}
)
cls.env["res.partner.id_number"].create(
{
"name": "Bad ID",
"category_id": bad_cat.id,
"partner_id": cls.env.user.partner_id.id,
}
)
cls.partner_id_category = cls.env["res.partner.id_category"].create(
{"code": "id_code", "name": "id_name"}
)
cls.partner = cls.env.ref("base.main_partner")
cls.partner_id = cls.env["res.partner.id_number"].create(
{
"name": "Good ID",
"category_id": cls.partner_id_category.id,
"partner_id": cls.partner.id,
}
)
@classmethod
def tearDownClass(cls):
teardown_test_model(cls.env, ResPartner)
super().tearDownClass()
def test_compute_identification(self):
"""It should set the proper field to the proper ID name."""
self.partner._compute_identification("name", "id_code")
self.assertEqual(self.partner.name, self.partner_id.name)
def test_inverse_identification_saves(self):
"""It should set the ID name to the proper field value."""
self.partner._inverse_identification("name", "id_code")
self.assertEqual(self.partner_id.name, self.partner.name)
def test_inverse_identification_creates_new_category(self):
"""It should create a new category of the type if non-existent."""
self.partner._inverse_identification("name", "new_code_type")
category = self.env["res.partner.id_category"].search(
[("code", "=", "new_code_type")]
)
self.assertTrue(category)
def test_inverse_identification_creates_new_id(self):
"""It should create a new ID of the type if non-existent."""
category = self.env["res.partner.id_category"].create(
{"code": "new_code_type", "name": "new_code_type"}
)
self.partner._inverse_identification("name", "new_code_type")
identification = self.env["res.partner.id_number"].search(
[("category_id", "=", category.id), ("partner_id", "=", self.partner.id)]
)
self.assertEqual(identification.name, self.partner.name)
def test_inverse_identification_multi_exception(self):
"""It should not allow a write when multiple IDs of same type."""
self.env["res.partner.id_number"].create(
{
"name": "Another ID",
"category_id": self.partner_id_category.id,
"partner_id": self.partner.id,
}
)
with self.assertRaises(ValidationError):
self.partner._inverse_identification("name", "id_code")
def test_search_identification(self):
"""It should return the right record when searched by ID."""
self.partner.social_security = "Test"
partner = self.env["res.partner"].search([("social_security", "=", "Test")])
self.assertEqual(partner, self.partner)
| 40.471264
| 3,521
|
2,498
|
py
|
PYTHON
|
15.0
|
# Copyright 2004-2010 Tiny SPRL http://tiny.be
# Copyright 2010-2012 ChriCar Beteiligungs- und Beratungs- GmbH
# http://www.camptocamp.at
# Copyright 2015 Antiun Ingenieria, SL (Madrid, Spain)
# http://www.antiun.com
# Antonio Espinosa <antonioea@antiun.com>
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from random import randint
from odoo import _, fields, models
from odoo.exceptions import UserError, ValidationError
from odoo.tools.safe_eval import safe_eval
class ResPartnerIdCategory(models.Model):
_name = "res.partner.id_category"
_description = "Partner ID Category"
_order = "name"
def _get_default_color(self):
return randint(1, 11)
color = fields.Integer(string="Color Index", default=_get_default_color)
code = fields.Char(
required=True,
help="Abbreviation or acronym of this ID type. For example, "
"'driver_license'",
)
name = fields.Char(
string="ID name",
required=True,
translate=True,
help="Name of this ID type. For example, 'Driver License'",
)
active = fields.Boolean(default=True)
validation_code = fields.Text(
"Python validation code", help="Python code called to validate an id number."
)
def _validation_eval_context(self, id_number):
self.ensure_one()
return {"self": self, "id_number": id_number}
def validate_id_number(self, id_number):
"""Validate the given ID number
The method raises an odoo.exceptions.ValidationError if the eval of
python validation code fails
"""
self.ensure_one()
if self.env.context.get("id_no_validate") or not self.validation_code:
return
eval_context = self._validation_eval_context(id_number)
try:
safe_eval(self.validation_code, eval_context, mode="exec", nocopy=True)
except Exception as e:
raise UserError(
_(
"Error when evaluating the id_category "
"validation code: \n {name} \n({error})"
).format(name=self.name, error=e)
) from e
if eval_context.get("failed", False):
raise ValidationError(
_("{id_name} is not a valid {cat_name} identifier").format(
id_name=id_number.name, cat_name=self.name
)
)
| 35.685714
| 2,498
|
2,847
|
py
|
PYTHON
|
15.0
|
# Copyright 2004-2010 Tiny SPRL http://tiny.be
# Copyright 2010-2012 ChriCar Beteiligungs- und Beratungs- GmbH
# http://www.camptocamp.at
# Copyright 2015 Antiun Ingenieria, SL (Madrid, Spain)
# http://www.antiun.com
# Antonio Espinosa <antonioea@antiun.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class ResPartnerIdNumber(models.Model):
_name = "res.partner.id_number"
_description = "Partner ID Number"
_order = "name"
@api.constrains("name", "category_id")
def validate_id_number(self):
for record in self:
record.category_id.validate_id_number(record)
name = fields.Char(
string="ID Number",
required=True,
help="The ID itself. For example, Driver License number of this person",
)
category_id = fields.Many2one(
string="Category",
required=True,
comodel_name="res.partner.id_category",
help="ID type defined in configuration. For example, Driver License",
)
partner_id = fields.Many2one(
string="Partner", required=True, comodel_name="res.partner", ondelete="cascade"
)
partner_issued_id = fields.Many2one(
string="Issued by",
comodel_name="res.partner",
help="Another partner, who issued this ID. For example, Traffic "
"National Institution",
)
place_issuance = fields.Char(
string="Place of Issuance",
help="The place where the ID has been issued. For example the country "
"for passports and visa",
)
date_issued = fields.Date(
string="Issued on",
help="Issued date. For example, date when person approved his driving "
"exam, 21/10/2009",
)
valid_from = fields.Date(
string="Valid from", help="Validation period stating date."
)
valid_until = fields.Date(
string="Valid until",
help="Expiration date. For example, date when person needs to renew "
"his driver license, 21/10/2019",
)
comment = fields.Text(string="Notes")
status = fields.Selection(
[
("draft", "New"),
("open", "Running"),
("pending", "To Renew"),
("close", "Expired"),
]
)
active = fields.Boolean(default=True)
@api.model
def default_get(self, fields):
res = super(ResPartnerIdNumber, self).default_get(fields)
# It seems to be a bug in native odoo that the field partner_id
# is not in the fields list by default. A workaround is required
# to force this.
if "default_partner_id" in self._context and "partner_id" not in fields:
fields.append("partner_id")
res["partner_id"] = self._context.get("default_partner_id")
return res
| 35.148148
| 2,847
|
6,226
|
py
|
PYTHON
|
15.0
|
# Copyright 2004-2010 Tiny SPRL http://tiny.be
# Copyright 2010-2012 ChriCar Beteiligungs- und Beratungs- GmbH
# http://www.camptocamp.at
# Copyright 2015 Antiun Ingenieria, SL (Madrid, Spain)
# http://www.antiun.com
# Antonio Espinosa <antonioea@antiun.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ResPartner(models.Model):
_inherit = "res.partner"
id_numbers = fields.One2many(
comodel_name="res.partner.id_number",
inverse_name="partner_id",
string="Identification Numbers",
)
@api.depends("id_numbers")
def _compute_identification(self, field_name, category_code):
"""Compute a field that indicates a certain ID type.
Use this on a field that represents a certain ID type. It will compute
the desired field as that ID(s).
This ID can be worked with as if it were a Char field, but it will
be relating back to a ``res.partner.id_number`` instead.
Example:
.. code-block:: python
social_security = fields.Char(
compute=lambda s: s._compute_identification(
'social_security', 'SSN',
),
inverse=lambda s: s._inverse_identification(
'social_security', 'SSN',
),
search=lambda s, *a: s._search_identification(
'SSN', *a
),
)
Args:
field_name (str): Name of field to set.
category_code (str): Category code of the Identification type.
"""
for record in self:
id_numbers = record.id_numbers.filtered(
lambda r: r.category_id.code == category_code
)
if not id_numbers:
# As this is used as a compute method
# we need to assign something
record[field_name] = False
continue
value = id_numbers[0].name
record[field_name] = value
def _inverse_identification(self, field_name, category_code):
"""Inverse for an identification field.
This method will create a new record, or modify the existing one
in order to allow for the associated field to work like a Char.
If a category does not exist of the correct code, it will be created
using `category_code` as both the `name` and `code` values.
If the value of the target field is unset, the associated ID will
be deactivated in order to preserve history.
Example:
.. code-block:: python
social_security = fields.Char(
compute=lambda s: s._compute_identification(
'social_security', 'SSN',
),
inverse=lambda s: s._inverse_identification(
'social_security', 'SSN',
),
search=lambda s, *a: s._search_identification(
'SSN', *a
),
)
Args:
field_name (str): Name of field to set.
category_code (str): Category code of the Identification type.
"""
for record in self:
id_number = record.id_numbers.filtered(
lambda r: r.category_id.code == category_code
)
record_len = len(id_number)
# Record for category is not existent.
if record_len == 0:
name = record[field_name]
if not name:
# No value to set
continue
category = self.env["res.partner.id_category"].search(
[("code", "=", category_code)]
)
if not category:
category = self.env["res.partner.id_category"].create(
{"code": category_code, "name": category_code}
)
self.env["res.partner.id_number"].create(
{"partner_id": record.id, "category_id": category.id, "name": name}
)
# There was an identification record singleton found.
elif record_len == 1:
value = record[field_name]
if value:
id_number.name = value
else:
id_number.active = False
# Guard against writing wrong records.
else:
raise ValidationError(
_(
"This {record_name} has multiple IDs of this "
"type ({category_code}), so a write via the "
"{field_name} field is not possible. "
"In order to fix this, please use the IDs tab."
).format(
record_name=record._name,
category_code=category_code,
field_name=field_name,
)
)
@api.model
def _search_identification(self, category_code, operator, value):
"""Search method for an identification field.
Example:
.. code-block:: python
social_security = fields.Char(
compute=lambda s: s._compute_identification(
'social_security', 'SSN',
),
inverse=lambda s: s._inverse_identification(
'social_security', 'SSN',
),
search=lambda s, *a: s._search_identification(
'SSN', *a
),
)
Args:
category_code (str): Category code of the Identification type.
operator (str): Operator of domain.
value (str): Value to search for.
Returns:
list: Domain to search with.
"""
id_numbers = self.env["res.partner.id_number"].search(
[("name", operator, value), ("category_id.code", "=", category_code)]
)
return [("id_numbers.id", "in", id_numbers.ids)]
| 36.623529
| 6,226
|
693
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - David Vidal
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Portal Partner Block Data Edit",
"version": "15.0.1.0.0",
"category": "Customer Relationship Management",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"license": "AGPL-3",
"depends": ["portal"],
"data": [
"views/res_partner_views.xml",
"views/portal_template.xml",
],
"assets": {
"web.assets_tests": [
"portal_partner_data_no_edit/static/src/js/portal_partner_data_no_edit_tour.js",
],
},
"installable": True,
}
| 33
| 693
|
763
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - David Vidal
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import common, tagged
@tagged("-at_install", "post_install")
class PortalHttpCase(common.HttpCase):
def setUp(self):
super().setUp()
self.partner = self.env.ref("base.partner_demo_portal")
def test_portal_partner_default(self):
"""The default standard behavior"""
self.start_tour(
"/my", "portal_partner_data_no_edit_default_tour", login="portal"
)
def test_portal_partner_blocked(self):
"""There's no form fields anymore"""
self.partner.block_portal_data_edit = True
self.start_tour("/my", "portal_partner_data_no_edit_block_tour", login="portal")
| 36.333333
| 763
|
2,570
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - David Vidal
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from lxml import html
from markupsafe import Markup
from odoo import models
class IrUiView(models.Model):
_inherit = "ir.ui.view"
def _render(self, values=None, engine="ir.qweb", minimal_qcontext=False):
"""Disable inputs converting them into paragraphs and clear form
buttons. This way, we don't need to go input by input and we can
support any view extension without further patching"""
res = super()._render(
values=values, engine=engine, minimal_qcontext=minimal_qcontext
)
if not self.env.context.get("block_portal_data_edit"):
return res
fragments = html.fromstring(res.encode("utf-8"))
for fragment in fragments:
# The result is a page that looks the same way as the original form
# but with the input fields shadowed and not editable as they're
# just `<p>` paragraphs in `form-control` classes disguise.
for _input in fragment.iterfind(".//form[@action='/my/account']//input"):
if _input.type in ["text", "tel", "email"]:
attrs = _input.attrib
text = attrs.pop("value", "")
# We don't want this attribute in the `<p>`
del attrs["type"]
attrs["readonly"] = "1"
p_readonly = _input.makeelement("p", attrib=attrs)
p_readonly.text = text
_input.addprevious(p_readonly)
_input.getparent().remove(_input)
for _select in fragment.iterfind(".//form[@action='/my/account']//select"):
# Maybe there's a prettier way to extract the selected value
option = [
x
for x in _select.getchildren()
if x.attrib.get("value", "") == _select.value
]
text = option and option[0].text or ""
attrs = _select.attrib
attrs["readonly"] = "1"
p_readonly = _select.makeelement("p", attrib=attrs)
p_readonly.text = text
_select.addprevious(p_readonly)
_select.getparent().remove(_select)
for _button in fragment.iterfind(".//form[@action='/my/account']//button"):
_button.getparent().remove(_button)
return Markup("".join(html.tostring(f).decode() for f in fragments))
| 48.490566
| 2,570
|
389
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - David Vidal
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
block_portal_data_edit = fields.Boolean(
string="Block Customer Info Edit",
help="Block portal info editing for the portal " "user linked to this partner",
)
| 32.416667
| 389
|
883
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - David Vidal
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.http import request, route
from odoo.addons.portal.controllers.portal import CustomerPortal
class PortalBlockEdit(CustomerPortal):
def _prepare_portal_layout_values(self):
"""So we can change the edit link text in the view"""
values = super()._prepare_portal_layout_values()
values["block_portal_data_edit"] = request.env.user.block_portal_data_edit
return values
@route()
def account(self, redirect=None, **post):
"""Inject a context that we later we catch in the template `render`"""
if request.env.user.block_portal_data_edit:
context = dict(request.env.context, block_portal_data_edit=True)
request.env.context = context
return super().account(redirect, **post)
| 42.047619
| 883
|
550
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 - Iván Todorovich
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Secondary phone number on partners",
"summary": "Adds a secondary phone number on partners",
"license": "AGPL-3",
"version": "15.0.1.0.0",
"author": "Iván Todorovich, Odoo Community Association (OCA)",
"maintainers": ["ivantodorovich"],
"category": "Customer Relationship Management",
"depends": ["base"],
"website": "https://github.com/OCA/partner-contact",
"data": ["views/res_partner.xml"],
}
| 36.533333
| 548
|
884
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 - Iván Todorovich
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests.common import Form, TransactionCase
class TestPartnerPhoneSecondary(TransactionCase):
def test_01_phone_validation_compatibility(self):
# This is here only to get code coverage.
with Form(self.env["res.partner"]) as form:
form.name = "French Partner"
form.country_id = self.env.ref("base.fr")
form.phone = "766666666"
form.phone2 = "766666666"
# It's not the purpose of this module to test phone_validation,
# nor how it formats phone numbers. Also it's not directly depended
# by this module. We do know for sure, though, that the same number
# is going to be formatted in the exact same way.
self.assertEqual(form.phone, form.phone2)
| 46.473684
| 883
|
526
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 - Iván Todorovich
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
phone2 = fields.Char("Phone (Secondary)")
@api.onchange("phone2", "country_id", "company_id")
def _onchange_phone2_validation(self):
# Compatibility with phone_validation
if hasattr(self, "phone_format"):
if self.phone2:
self.phone2 = self.phone_format(self.phone2)
| 30.882353
| 525
|
441
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - David Vidal
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Track partner pricelist changes",
"version": "15.0.1.0.0",
"category": "Partner Management",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"license": "AGPL-3",
"depends": ["product"],
"data": [],
"installable": True,
}
| 33.923077
| 441
|
790
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
# When we change the country or the state of the partner, Odoo tries to match
# a proper pricelist for the country, which will be the first it finds with
# a country group containing such country. The user could be unaware of this
# change (that could be right or not) and the partner would be left with a
# wrong pricelist. So we enable traceability to at least be able to log those
# changes and give the users the chance to amend them. We could also want to log
# manual changes overtime.
property_product_pricelist = fields.Many2one(tracking=True)
| 49.375
| 790
|
526
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Camptocamp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Partner Contact Role",
"summary": """Add roles to partners.""",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "Camptocamp,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"depends": [
"contacts",
],
"data": [
"security/ir.model.access.csv",
"views/res_partner_role.xml",
"views/res_partner.xml",
],
}
| 27.684211
| 526
|
423
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Camptocamp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
role_ids = fields.Many2many(
string="Roles",
comodel_name="res.partner.role",
)
class ResPartnerRole(models.Model):
_name = "res.partner.role"
_description = "Partner Role"
name = fields.Char()
| 20.142857
| 423
|
896
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Antonio Espinosa <antonio.espinosa@tecnativa.com>
# Copyright 2016 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2017 David Vidal <david.vidal@tecnativa.com>
# Copyright 2021 Gustavo Salgado <gustavo2840@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "NUTS Regions",
"category": "Localisation/Europe",
"version": "15.0.1.0.0",
"depends": ["contacts"],
"data": [
"views/res_country_view.xml",
"views/res_partner_nuts_view.xml",
"views/res_partner_view.xml",
"wizard/nuts_import_view.xml",
"security/ir.model.access.csv",
],
"images": ["images/new_fields.png"],
"author": "Tecnativa, " "Agile Business Group, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"license": "AGPL-3",
"installable": True,
}
| 37.333333
| 896
|
5,595
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 David Vidal <david.vidal@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.exceptions import UserError
from odoo.tests import common
class TestBaseLocationNuts(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestBaseLocationNuts, cls).setUpClass()
cls.importer = cls.env["nuts.import"].create({})
cls.importer.run_import() # loads nuts
cls.country_1 = cls.env["res.country"].search([("code", "=", "ES")])
cls.country_2 = cls.env["res.country"].search([("code", "=", "PT")])
cls.nuts_model = cls.env["res.partner.nuts"]
cls.nuts1_2 = cls.nuts_model.search([("code", "=", "PT")])
cls.nuts2_1 = cls.nuts_model.search([("code", "=", "ES2")])
cls.nuts3_1 = cls.nuts_model.search([("code", "=", "ES24")])
cls.nuts4_1 = cls.nuts_model.search([("code", "=", "ES243")])
cls.nuts4_2 = cls.nuts_model.search([("code", "=", "ES300")])
cls.partner = cls.env["res.partner"].create(
{"name": "Test partner", "country_id": cls.country_1.id}
)
cls.state_1 = cls.env["res.country.state"].create(
{"name": "Zaragoza Test", "code": "ZT", "country_id": cls.country_1.id}
)
cls.nuts4_1.state_id = cls.state_1
cls.state_2 = cls.env["res.country.state"].create(
{"name": "Madrid Test", "code": "MT", "country_id": cls.country_1.id}
)
cls.nuts4_2.state_id = cls.state_2
cls.country_1.state_level = 4
def test_onchange_nuts_country(self):
self.partner.nuts1_id = self.nuts1_2
self.partner._onchange_nuts1_id()
self.assertEqual(self.partner.country_id, self.nuts1_2.country_id)
def test_onchange_nuts(self):
self.partner.country_id = self.country_2
self.partner._onchange_country_id_base_location_nuts()
self.assertEqual(self.partner.nuts1_id.country_id, self.partner.country_id)
self.partner.nuts4_id = self.nuts4_1
self.partner._onchange_nuts4_id()
self.assertEqual(self.partner.country_id, self.country_1)
self.assertEqual(self.partner.nuts3_id, self.nuts3_1)
self.partner._onchange_nuts3_id()
self.assertEqual(self.partner.nuts2_id, self.nuts2_1)
self.partner._onchange_nuts2_id()
self.assertEqual(self.partner.nuts1_id.country_id, self.country_1)
self.partner.country_id = self.country_2
self.partner._onchange_country_id_base_location_nuts()
self.assertEqual(self.partner.country_id, self.nuts1_2.country_id)
self.assertFalse(self.partner.nuts2_id)
self.assertFalse(self.partner.nuts3_id)
self.assertFalse(self.partner.nuts4_id)
def test_onchange_states(self):
self.partner.state_id = self.state_2
self.partner.onchange_state_id_base_location_nuts()
self.assertEqual(self.state_2, self.partner.nuts4_id.state_id)
self.partner.state_id = self.state_1
self.partner.onchange_state_id_base_location_nuts()
self.assertEqual(self.state_1, self.partner.nuts4_id.state_id)
self.partner._onchange_nuts4_id()
self.assertEqual(self.partner.nuts3_id, self.nuts3_1)
self.partner._onchange_nuts3_id()
self.assertEqual(self.partner.nuts2_id, self.nuts2_1)
self.partner._onchange_nuts2_id()
self.assertEqual(self.partner.nuts1_id.country_id, self.country_1)
def test_download_exceptions(self):
"""Tests download exceptions"""
with self.assertRaises(UserError):
self.importer._download_nuts(url_base="htttt://test.com")
with self.assertRaises(UserError):
self.importer._download_nuts(url_base="http://ec.europa.eu/_404")
def create_new_parent(self, orig_parent):
new_parent = self.nuts_model.create(
{
"level": orig_parent.level,
"code": "NEW" + orig_parent.code,
"name": "New parent",
"country_id": orig_parent.country_id.id,
"not_updatable": False,
}
)
return new_parent
def test_no_update(self):
# Update a NUTS field
orig_name = self.nuts4_2.name
new_name = 2 * orig_name
self.assertNotEqual(orig_name, new_name)
# Update hierarchy creating a new parent
orig_parent = self.nuts4_2.parent_id
new_parent = self.create_new_parent(orig_parent)
self.assertNotEqual(orig_parent, new_parent)
# If the flag is False (default), updates will be overwritten
# and the new parent deleted
self.assertFalse(self.nuts4_2.not_updatable)
self.assertFalse(new_parent.not_updatable)
self.nuts4_2.name = new_name
self.nuts4_2.parent_id = new_parent
self.importer.run_import()
self.assertEqual(self.nuts4_2.name, orig_name)
self.assertEqual(self.nuts4_2.parent_id, orig_parent)
self.assertFalse(new_parent.exists())
# New parent has been deleted by the import
new_parent = self.create_new_parent(orig_parent)
# If the flag is True, creation and updates will not be overwritten
self.nuts4_2.not_updatable = True
new_parent.not_updatable = True
self.nuts4_2.name = new_name
self.nuts4_2.parent_id = new_parent
self.importer.run_import()
self.assertEqual(self.nuts4_2.name, new_name)
self.assertEqual(self.nuts4_2.parent_id, new_parent)
self.assertTrue(new_parent.exists())
| 44.76
| 5,595
|
7,919
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Antonio Espinosa <antonio.espinosa@tecnativa.com>
# Copyright 2016 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2017 David Vidal <jairo.llopis@tecnativa.com>
# Copyright 2021 Andrii Skrypka <andrijskrypa@ukr.net>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import logging
import re
from collections import OrderedDict
import requests
from lxml import etree
from odoo import _, api, fields, models
from odoo.exceptions import UserError
logger = logging.getLogger(__name__)
# Default server values
URL_BASE = "http://ec.europa.eu"
URL_PATH = "/eurostat/ramon/nomenclatures/index.cfm"
URL_PARAMS = {
"TargetUrl": "ACT_OTH_CLS_DLD",
"StrNom": "NUTS_2013",
"StrFormat": "XML",
"StrLanguageCode": "EN",
"StrLayoutCode": "HIERARCHIC",
}
class NutsImport(models.TransientModel):
_name = "nuts.import"
_description = "Import NUTS items from European RAMON service"
_parents = [False, False, False, False]
_countries = {
"BE": False,
"BG": False,
"CZ": False,
"DK": False,
"DE": False,
"EE": False,
"IE": False,
"GR": False, # EL
"ES": False,
"FR": False,
"HR": False,
"IT": False,
"CY": False,
"LV": False,
"LT": False,
"LU": False,
"HU": False,
"MT": False,
"NL": False,
"AT": False,
"PL": False,
"PT": False,
"RO": False,
"SI": False,
"SK": False,
"FI": False,
"SE": False,
"GB": False, # UK
}
_map = OrderedDict(
[
(
"level",
{"xpath": "", "attrib": "idLevel", "type": "integer", "required": True},
),
(
"code",
{
"xpath": './Label/LabelText[@language="ALL"]',
"type": "string",
"required": True,
},
),
(
"name",
{
"xpath": './Label/LabelText[@language="EN"]',
"type": "string",
"required": True,
},
),
]
)
current_country_id = fields.Many2one("res.country")
def _check_node(self, node):
if node.get("id") and node.get("idLevel"):
return True
return False
def _mapping(self, node):
item = {}
for k, v in self._map.items():
field_xpath = v.get("xpath", "")
field_attrib = v.get("attrib", False)
field_type = v.get("type", "string")
field_required = v.get("required", False)
value = ""
if field_xpath:
n = node.find(field_xpath)
else:
n = node
if n is not None:
if field_attrib:
value = n.get(field_attrib, "")
else:
value = n.text
if field_type == "integer":
try:
value = int(value)
except (ValueError, TypeError):
logger.warning(
"Value {} for field {} replaced by 0".format(value, k)
)
value = 0
else:
logger.debug("xpath = '%s', not found" % field_xpath)
if field_required and not value:
raise UserError(_("Value not found for mandatory field %s") % k)
item[k] = value
return item
def _download_nuts(self, url_base=None, url_path=None, url_params=None):
if not url_base:
url_base = URL_BASE
if not url_path:
url_path = URL_PATH
if not url_params:
url_params = URL_PARAMS
url = url_base + url_path + "?"
url += "&".join([k + "=" + v for k, v in url_params.items()])
logger.info("Starting to download %s" % url)
try:
res_request = requests.get(url)
except Exception as e:
raise UserError(
_("Got an error when trying to download the file: %s.") % str(e)
) from e
if res_request.status_code != requests.codes.ok:
raise UserError(
_(
"Got an error %(status_code)s when trying to download the file %(url)s."
)
% {"status_code": res_request.status_code, "url": url}
)
logger.info("Download successfully %d bytes" % len(res_request.content))
# Workaround XML: Remove all characters before <?xml
pattern = re.compile(rb"^.*<\?xml", re.DOTALL)
content_fixed = re.sub(pattern, b"<?xml", res_request.content)
if not re.match(rb"<\?xml", content_fixed):
raise UserError(_("Downloaded file is not a valid XML file"))
return content_fixed
@api.model
def _load_countries(self):
for k in self._countries:
self._countries[k] = self.env["res.country"].search([("code", "=", k)])
# Workaround to translate some country codes:
# EL => GR (Greece)
# UK => GB (United Kingdom)
self._countries["EL"] = self._countries["GR"]
self._countries["UK"] = self._countries["GB"]
@api.model
def state_mapping(self, data, node):
# Method to inherit and add state_id relation depending on country
level = data.get("level", 0)
code = data.get("code", "")
if level == 1:
self.current_country_id = self._countries[code]
return {"country_id": self.current_country_id.id}
@api.model
def create_or_update_nuts(self, node):
if not self._check_node(node):
return False
nuts_model = self.env["res.partner.nuts"]
data = self._mapping(node)
data.update(self.state_mapping(data, node))
level = data.get("level", 0)
if 2 <= level <= 5:
data["parent_id"] = self._parents[level - 2]
nuts = nuts_model.search(
[("level", "=", data["level"]), ("code", "=", data["code"])]
)
if nuts:
nuts.filtered(lambda n: not n.not_updatable).write(data)
else:
nuts = nuts_model.create(data)
if 1 <= level <= 4:
self._parents[level - 1] = nuts.id
return nuts
def run_import(self):
nuts_model = self.env["res.partner.nuts"].with_context(
defer_parent_store_computation=True
)
self._load_countries()
# All current NUTS (for available countries),
# delete if not found above
nuts_to_delete = nuts_model.search(
[
("country_id", "in", [x.id for x in self._countries.values()]),
("not_updatable", "=", False),
]
)
# Download NUTS in english, create or update
logger.info("Importing NUTS 2013 English...")
xmlcontent = self._download_nuts()
dom = etree.fromstring(xmlcontent)
for node in dom.iter("Item"):
logger.debug(
"Reading level=%s, id=%s",
node.get("idLevel", "N/A"),
node.get("id", "N/A"),
)
nuts = self.create_or_update_nuts(node)
if nuts and nuts in nuts_to_delete:
nuts_to_delete -= nuts
# Delete obsolete NUTS
if nuts_to_delete:
logger.info("%d NUTS entries deleted" % len(nuts_to_delete))
nuts_to_delete.unlink()
logger.info(
"The wizard to create NUTS entries from RAMON "
"has been successfully completed."
)
return {
"type": "ir.actions.client",
"tag": "reload",
}
| 33.413502
| 7,919
|
369
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Antonio Espinosa <antonio.espinosa@tecnativa.com>
# Copyright 2016 Jairo Llopis <jairo.llopis@tecnativa.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ResCountry(models.Model):
_inherit = "res.country"
state_level = fields.Integer(help="Level for the state NUTS category.")
| 33.545455
| 369
|
1,014
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Antonio Espinosa <antonio.espinosa@tecnativa.com>
# Copyright 2016 Jairo Llopis <jairo.llopis@tecnativa.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ResPartnerNuts(models.Model):
_name = "res.partner.nuts"
_order = "parent_path"
_parent_order = "name"
_parent_store = True
_description = "NUTS Item"
# NUTS fields
level = fields.Integer(required=True)
code = fields.Char(required=True)
name = fields.Char(required=True, translate=True)
country_id = fields.Many2one(comodel_name="res.country", required=True)
state_id = fields.Many2one(comodel_name="res.country.state")
not_updatable = fields.Boolean()
# Parent hierarchy
parent_id = fields.Many2one(comodel_name="res.partner.nuts", ondelete="restrict")
parent_path = fields.Char(index=True)
child_ids = fields.One2many(
comodel_name="res.partner.nuts", inverse_name="parent_id", string="Children"
)
| 37.555556
| 1,014
|
4,535
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Antonio Espinosa <antonio.espinosa@tecnativa.com>
# Copyright 2016 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2021 Andrii Skrypka <andrijskrypa@ukr.net>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
from odoo.osv.expression import AND, OR
class ResPartner(models.Model):
_inherit = "res.partner"
nuts1_id = fields.Many2one(
comodel_name="res.partner.nuts",
domain="[('level', '=', 1), ('id', 'in', allowed_nut_ids)]",
string="NUTS L1",
)
nuts2_id = fields.Many2one(
comodel_name="res.partner.nuts",
domain="[('level', '=', 2), ('id', 'in', allowed_nut_ids)]",
string="NUTS L2",
)
nuts3_id = fields.Many2one(
comodel_name="res.partner.nuts",
domain="[('level', '=', 3), ('id', 'in', allowed_nut_ids)]",
string="NUTS L3",
)
nuts4_id = fields.Many2one(
comodel_name="res.partner.nuts",
domain="[('level', '=', 4), ('id', 'in', allowed_nut_ids)]",
string="NUTS L4",
)
allowed_nut_ids = fields.Many2many(
"res.partner.nuts",
string="Allowed nuts",
compute="_compute_allowed_nuts",
)
@api.depends("country_id", "nuts1_id", "nuts2_id", "nuts3_id")
def _compute_allowed_nuts(self):
Nuts = self.env["res.partner.nuts"]
for partner in self:
domain = []
for level in range(1, 4):
nuts = partner["nuts%d_id" % level]
if nuts:
domain = OR(
[
domain,
[("parent_id", "=", nuts.id), ("level", "=", level + 1)],
]
)
if partner.country_id:
domain = AND([[("country_id", "=", partner.country_id.id)], domain])
partner.allowed_nut_ids = Nuts.search(domain)
def _onchange_nuts(self, level):
field = self["nuts%d_id" % level]
country_id = field.country_id
state_id = field.state_id
if country_id and self.country_id != country_id:
self.country_id = country_id
if state_id and self.state_id != state_id:
self.state_id = state_id
if level > 1:
parent_id = field.parent_id
if parent_id:
nuts_parent_level = "nuts%d_id" % (level - 1)
parent_field = self[nuts_parent_level]
if parent_field != parent_id:
self[nuts_parent_level] = parent_id
@api.onchange("nuts4_id")
def _onchange_nuts4_id(self):
return self._onchange_nuts(4)
@api.onchange("nuts3_id")
def _onchange_nuts3_id(self):
return self._onchange_nuts(3)
@api.onchange("nuts2_id")
def _onchange_nuts2_id(self):
return self._onchange_nuts(2)
@api.onchange("nuts1_id")
def _onchange_nuts1_id(self):
return self._onchange_nuts(1)
@api.onchange("country_id")
def _onchange_country_id_base_location_nuts(self):
"""Sensible values and domains for related fields."""
fields = ["state_id", "nuts1_id", "nuts2_id", "nuts3_id", "nuts4_id"]
for field in fields:
if self.country_id and self[field].country_id != self.country_id:
self[field] = False
fields.remove("state_id")
if self.country_id:
nuts1 = self.env["res.partner.nuts"].search(
[("level", "=", 1), ("country_id", "=", self.country_id.id)], limit=1
)
if self.nuts1_id.id != nuts1.id:
self.nuts1_id = nuts1.id
@api.onchange("state_id")
def onchange_state_id_base_location_nuts(self):
if self.state_id:
self.country_id = self.state_id.country_id
if self.country_id.state_level:
nuts_state = self.env["res.partner.nuts"].search(
[
("level", "=", self.country_id.state_level),
("state_id", "=", self.state_id.id),
],
limit=1,
)
if nuts_state:
field = "nuts%d_id" % self.country_id.state_level
self[field] = nuts_state
@api.model
def _address_fields(self):
fields = super()._address_fields()
if fields:
fields += ["nuts1_id", "nuts2_id", "nuts3_id", "nuts4_id"]
return fields
| 36.28
| 4,535
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.