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
|
|---|---|---|---|---|---|---|
544
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Eficent Business and IT Consulting Services, S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
group_use_partner_industry_for_person = fields.Boolean(
string="Use industry for individuals",
help="Set if you want to be able to use industries for individuals also.",
implied_group="partner_industry_secondary.group_use_partner_industry_for_person",
)
| 38.857143
| 544
|
1,029
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta
# Copyright 2016 Tecnativa S.L. - Vicent Cubells
# Copyright 2018 Eficent Business and IT Consulting Services, S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import _, api, exceptions, fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
industry_id = fields.Many2one(string="Main Industry")
secondary_industry_ids = fields.Many2many(
comodel_name="res.partner.industry",
string="Secondary Industries",
domain="[('id', '!=', industry_id)]",
)
@api.constrains("industry_id", "secondary_industry_ids")
def _check_industries(self):
for partner in self:
if partner.industry_id in partner.secondary_industry_ids:
raise exceptions.ValidationError(
_(
"The main industry must be different "
"from the secondary industries."
)
)
| 35.482759
| 1,029
|
464
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
{
"name": "Partner pricelist search",
"version": "15.0.1.0.0",
"author": "Tecnativa,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"category": "Partner Management",
"depends": ["product"],
"data": ["views/product_pricelist_views.xml"],
"installable": True,
"license": "AGPL-3",
}
| 33.142857
| 464
|
3,067
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Dauden
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo.tests import common
class TestPartnerPricelistSearch(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.pricelist_1 = cls.env["product.pricelist"].create(
{"name": "Test pricelist 1"}
)
cls.pricelist_2 = cls.env["product.pricelist"].create(
{"name": "Test pricelist 2"}
)
cls.customer_1 = cls.env["res.partner"].create(
{"name": "Test customer 1", "property_product_pricelist": cls.pricelist_1}
)
cls.customer_2 = cls.env["res.partner"].create(
{"name": "Test customer 2", "property_product_pricelist": cls.pricelist_2}
)
cls.partner_obj = cls.env["res.partner"]
def test_partner_pricelist_search_equal(self):
"""Test search '='"""
partners = self.partner_obj.search(
[("property_product_pricelist", "=", self.pricelist_1.id)]
)
self.assertEqual(partners, self.customer_1)
def test_partner_pricelist_search_in(self):
"""Test search 'in'"""
partners = self.partner_obj.search(
[
(
"property_product_pricelist",
"in",
(self.pricelist_1 | self.pricelist_2).ids,
)
]
)
self.assertIn(self.customer_1, partners)
self.assertIn(self.customer_2, partners)
def test_partner_pricelist_search_not_equal(self):
"""Test search 'not equal'"""
partners = self.partner_obj.search(
[("property_product_pricelist", "!=", self.pricelist_1.id)]
)
self.assertNotIn(self.customer_1, partners)
self.assertIn(self.customer_2, partners)
def test_partner_pricelist_search_not_in(self):
"""Test search 'not in'"""
partners = self.partner_obj.search(
[
(
"property_product_pricelist",
"not in",
(self.pricelist_1 | self.pricelist_2).ids,
)
]
)
self.assertNotIn(self.customer_1, partners)
self.assertNotIn(self.customer_2, partners)
def test_partner_pricelist_search_ilike(self):
"""Test search 'ilike'"""
partners = self.partner_obj.search(
[("property_product_pricelist", "ilike", "Test pricelist 1")]
)
self.assertIn(self.customer_1, partners)
self.assertNotIn(self.customer_2, partners)
def test_show_pricelist_partners(self):
res = self.pricelist_1.show_pricelist_partners()
self.assertEqual(self.partner_obj.search(res["domain"]), self.customer_1)
res = (self.pricelist_1 | self.pricelist_2).show_pricelist_partners()
self.assertEqual(
self.partner_obj.search(res["domain"]), (self.customer_1 | self.customer_2)
)
| 36.927711
| 3,065
|
450
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import models
class Pricelist(models.Model):
_inherit = "product.pricelist"
def show_pricelist_partners(self):
xmlid = "base.action_partner_form"
action = self.env["ir.actions.act_window"]._for_xml_id(xmlid)
action["domain"] = [("property_product_pricelist", "in", self.ids)]
return action
| 32.142857
| 450
|
1,242
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
property_product_pricelist = fields.Many2one(
search="_search_property_product_pricelist"
)
@api.model
def search(self, args, offset=0, limit=None, order=None, count=False):
# Substitute pricelist tuple
partner_domain = [
(1, "=", 1)
if (isinstance(x, (list, tuple)) and x[0] == "property_product_pricelist")
else x
for x in args
]
return super(
ResPartner, self.with_context(search_partner_domain=partner_domain)
).search(
args,
offset=offset,
limit=limit,
order=order,
count=count,
)
@api.model
def _search_property_product_pricelist(self, operator, value):
domain = self.env.context.get("search_partner_domain", [])
partners = self.with_context(prefetch_fields=False).search(domain)
key = "property_product_pricelist"
return [("id", "in", partners.filtered_domain([(key, operator, value)]).ids)]
| 32.684211
| 1,242
|
450
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
def pre_init_hook(cr):
"""Prepopulate stored related fields for faster installation"""
logger = logging.getLogger(__name__)
logger.info("Prepopulating stored related fields")
cr.execute(
"""
ALTER TABLE crm_lead
ADD COLUMN IF NOT EXISTS company_group_id integer;
"""
)
| 29.866667
| 448
|
544
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "CRM Partner Company Group",
"summary": "Adds the possibility to add a company group to a company",
"version": "15.0.1.0.0",
"category": "Sales",
"author": "Camptocamp SA, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["base_partner_company_group", "crm"],
"website": "https://github.com/OCA/partner-contact",
"data": ["views/opportunity_view.xml"],
"installable": True,
}
| 38.857143
| 544
|
295
|
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 CrmLead(models.Model):
_inherit = "crm.lead"
company_group_id = fields.Many2one(
related="partner_id.company_group_id", store=True
)
| 24.583333
| 295
|
452
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
def pre_init_hook(cr):
"""Prepopulate stored related fields for faster installation"""
logger = logging.getLogger(__name__)
logger.info("Prepopulating stored related fields")
cr.execute(
"""
ALTER TABLE sale_order
ADD COLUMN IF NOT EXISTS company_group_id integer;
"""
)
| 30
| 450
|
545
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Sale Partner Company Group",
"summary": "Adds the possibility to add a company group to a company",
"version": "15.0.1.0.1",
"category": "Sales",
"author": "Camptocamp SA, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["base_partner_company_group", "sale"],
"website": "https://github.com/OCA/partner-contact",
"data": ["views/sale_order_view.xml"],
"installable": True,
}
| 38.928571
| 545
|
4,447
|
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.addons.base_partner_company_group.tests.test_base_partner_company_group import (
TestBasePartnerCompanyGroup,
)
class TestSalePartnerCompanyGroup(TestBasePartnerCompanyGroup):
@classmethod
def setUpClass(cls):
super().setUpClass()
currency = cls.env.ref("base.USD")
cls.pricelist1 = cls.env["product.pricelist"].create(
{"name": "Pricelist 01", "currency_id": currency.id}
)
cls.pricelist2 = cls.env["product.pricelist"].create(
{"name": "Pricelist 02", "currency_id": currency.id}
)
cls.company_group1 = cls.env["res.partner"].create(
{
"name": "Company Group 01",
"is_company": True,
"property_product_pricelist": cls.pricelist1.id,
}
)
cls.company_group2 = cls.env["res.partner"].create(
{
"name": "Company Group 02",
"is_company": True,
"property_product_pricelist": cls.pricelist2.id,
}
)
cls.partner1 = cls.env["res.partner"].create(
{
"name": "Partner 01",
"is_company": True,
"property_product_pricelist": cls.pricelist1.id,
"company_group_id": cls.company_group1.id,
}
)
cls.partner2 = cls.env["res.partner"].create(
{
"name": "Partner 02",
"is_company": True,
"property_product_pricelist": cls.pricelist1.id,
"company_group_id": cls.company_group1.id,
}
)
def test_01_change_pricelist_partner(self):
self.partner1.property_product_pricelist = self.pricelist2
res = self.partner1._onchange_property_product_pricelist()
self.assertEqual(
{
"warning": {
"title": "Warning",
"message": "The company group Company Group 01 has the pricelist "
"Pricelist 01 (USD), that is different than the "
"pricelist set on this contact",
}
},
res,
)
self.partner1.property_product_pricelist = self.pricelist1
res = self.partner1._onchange_property_product_pricelist()
self.assertEqual({}, res)
def test_02_change_company_group_partner(self):
self.partner1.company_group_id = self.company_group2
res = self.partner1._onchange_company_group_id()
self.assertEqual(
{
"warning": {
"title": "Warning",
"message": "The company group Company Group 02 has the pricelist "
"Pricelist 02 (USD), that is different than the "
"pricelist set on this contact",
}
},
res,
)
self.partner1.company_group_id = self.company_group1
res = self.partner1._onchange_company_group_id()
self.assertEqual({}, res)
def test_03_change_pricelist_company_group(self):
self.company_group1.property_product_pricelist = self.pricelist2
res = self.company_group1._onchange_property_product_pricelist()
self.assertEqual(
{
"warning": {
"title": "Warning",
"message": "This contact has members of a company group with "
"different pricelists, the members are:\n"
"\t- Partner 01\n\t- Partner 02\n",
}
},
res,
)
self.partner1.property_product_pricelist = self.pricelist2
res = self.company_group1._onchange_property_product_pricelist()
self.assertEqual(
{
"warning": {
"title": "Warning",
"message": "This contact has members of a company group with "
"different pricelists, the members are:\n"
"\t- Partner 02\n",
}
},
res,
)
self.partner2.property_product_pricelist = self.pricelist2
res = self.company_group1._onchange_property_product_pricelist()
self.assertEqual({}, res)
| 38.336207
| 4,447
|
299
|
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 SaleOrder(models.Model):
_inherit = "sale.order"
company_group_id = fields.Many2one(
related="partner_id.company_group_id", store=True
)
| 24.916667
| 299
|
2,115
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, api, models
class Contact(models.Model):
_inherit = "res.partner"
@api.onchange("company_group_id")
def _onchange_company_group_id(self):
res = {}
if (
self.company_group_id
and self.company_group_id.property_product_pricelist
!= self.property_product_pricelist
):
res["warning"] = {
"title": _("Warning"),
"message": _(
f"The company group {self.company_group_id.display_name} has the pricelist "
f"{self.company_group_id.property_product_pricelist.display_name}, "
"that is different than the pricelist set on this contact"
),
}
return res
@api.onchange("property_product_pricelist")
def _onchange_property_product_pricelist(self):
res = self._onchange_company_group_id()
if (
not res
and self.company_group_member_ids
# Need to check _origin because the field company_group_ids is a recordset of
# NewIds that have False values on the field property_product_pricelist.
and self.company_group_member_ids._origin.mapped(
"property_product_pricelist"
)
- self.property_product_pricelist
):
company_members = self.company_group_member_ids.filtered(
lambda cm: cm.property_product_pricelist
!= self.property_product_pricelist
)
members_str = ""
for member in company_members.sorted(key="display_name"):
members_str += "\t- %s\n" % member.display_name
res["warning"] = {
"title": _("Warning"),
"message": _(
"This contact has members of a company group with"
f" different pricelists, the members are:\n{members_str}"
),
}
return res
| 38.454545
| 2,115
|
554
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 ACSONE SA/NV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Partner Industry Parent",
"summary": """
This module add a parent relation to the partner industry""",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "ACSONE SA/NV," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"depends": ["base"],
"data": [
"views/res_partner_views.xml",
"views/res_partner_industry_views.xml",
],
"demo": [],
}
| 30.777778
| 554
|
1,045
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests.common import TransactionCase
class TestResPartnerIndustry(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.industry_1 = cls.env.ref("base.res_partner_industry_O")
cls.industry_2 = cls.env.ref("base.res_partner_industry_P")
cls.industry_3 = cls.env.ref("base.res_partner_industry_Q")
def test_res_partner_industry_complete_name(self):
self.assertEqual(self.industry_1.complete_name, "Public Administration")
self.industry_1.parent_id = self.industry_2
self.assertEqual(
self.industry_1.complete_name, "Education / Public Administration"
)
self.industry_2.parent_id = self.industry_3
self.assertEqual(
self.industry_1.complete_name,
"Health/Social / Education / Public Administration",
)
| 40.192308
| 1,045
|
2,560
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 ACSONE SA/NV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ResPartnerIndustry(models.Model):
_inherit = "res.partner.industry"
_parent_name = "parent_id"
_parent_store = True
_rec_name = "complete_name"
_order = "complete_name"
complete_name = fields.Char(
compute="_compute_complete_name",
store=True,
recursive=True,
)
parent_path = fields.Char(index=True)
parent_id = fields.Many2one(
comodel_name="res.partner.industry", index=True, ondelete="cascade"
)
child_ids = fields.One2many(
comodel_name="res.partner.industry",
inverse_name="parent_id",
string="Children Industry",
)
partner_count = fields.Integer(
"# Partners",
compute="_compute_partner_count",
help="The number of partners under this industry "
"(Does not consider the children categories)",
)
@api.depends("name", "parent_id.complete_name")
def _compute_complete_name(self):
for industry in self:
if industry.parent_id:
industry.complete_name = "%s / %s" % (
industry.parent_id.complete_name,
industry.name,
)
else:
industry.complete_name = industry.name
def _compute_partner_count(self):
read_group_res = self.env["res.partner"].read_group(
[("industry_id", "child_of", self.ids)],
["industry_id"],
["industry_id"],
)
group_data = {
data["industry_id"][0]: data["industry_id_count"] for data in read_group_res
}
for industry in self:
partner_count = 0
for sub_industry_id in industry.search(
[("id", "child_of", industry.ids)]
).ids:
partner_count += group_data.get(sub_industry_id, 0)
industry.partner_count = partner_count
@api.constrains("parent_id")
def _check_category_recursion(self):
if not self._check_recursion():
raise ValidationError(_("You cannot create recursive categories."))
@api.model
def name_create(self, name):
return self.create({"name": name}).name_get()[0]
def name_get(self):
if not self.env.context.get("hierarchical_naming", True):
return [(record.id, record.name) for record in self]
return super().name_get()
| 33.684211
| 2,560
|
1,622
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import SUPERUSER_ID, _, api, models
class Partner(models.Model):
_inherit = "res.partner"
@api.model
def _search(
self,
args,
offset=0,
limit=None,
order=None,
count=False,
access_rights_uid=None,
):
if self._context.get("search_default_industry_id"):
args.append(
(
"industry_id",
"child_of",
self._context["search_default_industry_id"],
)
)
return super()._search(
args,
offset=offset,
limit=limit,
order=order,
count=count,
access_rights_uid=access_rights_uid,
)
@api.model
def view_header_get(self, view_id, view_type):
if self._context.get("industry_id"):
return _(
"Partners: %(industry)s",
industry=self.env["res.partner.industry"]
.browse(self.env.context["industry_id"])
.name,
)
return super().view_header_get(view_id, view_type)
def _read_group_industry_id(self, industries, domain, order):
industry_ids = self.env.context.get("default_industry_id")
if not industry_ids and self.env.context.get("group_expand"):
industry_ids = industries._search(
[], order=order, access_rights_uid=SUPERUSER_ID
)
return industries.browse(industry_ids)
| 30.037037
| 1,622
|
1,030
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Nicolas Bessi, Camptocamp SA
# Copyright 2018-2021 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Location management (aka Better ZIP)",
"version": "15.0.1.0.2",
"development_status": "Mature",
"depends": ["base_address_city", "contacts"],
"author": (
"Camptocamp,"
"ACYSOS S.L.,"
"Alejandro Santana,"
"Tecnativa,"
"AdaptiveCity,"
"Odoo Community Association (OCA)"
),
"license": "AGPL-3",
"summary": """Enhanced zip/npa management system""",
"website": "https://github.com/OCA/partner-contact",
"data": [
"security/ir.model.access.csv",
"views/res_city_zip_view.xml",
"views/res_city_view.xml",
"views/res_country_view.xml",
"views/res_company_view.xml",
"views/res_partner_view.xml",
],
"demo": ["demo/res_city_zip.xml"],
"installable": True,
"auto_install": False,
"maintainers": ["pedrobaeza"],
}
| 31.212121
| 1,030
|
11,531
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Yannick Vaucher, Camptocamp SA
# Copyright 2018-2021 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import psycopg2
from odoo.exceptions import ValidationError
from odoo.tests import Form, common
from odoo.tools.misc import mute_logger
class TestBaseLocation(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
state_obj = cls.env["res.country.state"]
city_obj = cls.env["res.city"]
zip_obj = cls.env["res.city.zip"]
cls.partner_obj = cls.env["res.partner"]
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.state_vd = state_obj.create(
{"name": "Vaud", "code": "VD", "country_id": cls.env.ref("base.ch").id}
)
cls.env.ref("base.es").write({"enforce_cities": True})
cls.company = cls.env.ref("base.main_company")
cls.country_es = cls.env.ref("base.es")
cls.state_bcn = state_obj.create(
{"name": "Barcelona", "code": "08", "country_id": cls.country_es.id}
)
cls.state_madrid = state_obj.create(
{"name": "Madrid", "code": "28", "country_id": cls.env.ref("base.es").id}
)
cls.city_bcn = city_obj.create(
{
"name": "Barcelona",
"state_id": cls.state_bcn.id,
"country_id": cls.env.ref("base.es").id,
}
)
cls.city_madrid = city_obj.create(
{
"name": "Madrid",
"state_id": cls.state_madrid.id,
"country_id": cls.env.ref("base.es").id,
}
)
cls.city_lausanne = city_obj.create(
{
"name": "Lausanne",
"state_id": cls.state_vd.id,
"country_id": cls.env.ref("base.ch").id,
}
)
cls.lausanne = zip_obj.create({"name": "666", "city_id": cls.city_lausanne.id})
cls.barcelona = zip_obj.create({"name": "444", "city_id": cls.city_bcn.id})
def test_onchange_partner_city_completion(self):
"""Test that partner data is filled accodingly"""
partner1 = Form(self.env["res.partner"])
partner1.zip_id = self.barcelona
self.assertEqual(partner1.zip, self.barcelona.name)
self.assertEqual(partner1.city, self.barcelona.city_id.name)
self.assertEqual(partner1.state_id, self.barcelona.city_id.state_id)
self.assertEqual(partner1.country_id, self.barcelona.city_id.country_id)
def test_onchange_company_city_completion(self):
"""Test that company data is filled accodingly"""
company = self.env["res.company"].new({"name": "Test"})
company.zip_id = self.lausanne
company._onchange_zip_id()
self.assertEqual(company.zip, self.lausanne.name)
self.assertEqual(company.city, self.lausanne.city_id.name)
self.assertEqual(company.state_id, self.lausanne.city_id.state_id)
self.assertEqual(company.country_id, self.lausanne.city_id.country_id)
def test_company_address_fields(self):
"""Test if the partner address fields changes when
changing the ones from the company"""
company = self.env["res.company"].create({"name": "Test"})
self.assertTrue(company.partner_id)
company.partner_id.write(
{
"zip_id": self.lausanne.id,
"state_id": self.lausanne.city_id.state_id.id,
"country_id": self.lausanne.city_id.country_id.id,
"city_id": self.lausanne.city_id.id,
"city": self.lausanne.city_id.name,
"zip": self.lausanne.name,
}
)
company._compute_address()
self.assertEqual(company.zip_id, company.partner_id.zip_id)
self.assertEqual(company.city_id, company.partner_id.city_id)
def test_company_address_fields_inverse(self):
"""Test inverse fields from res.company"""
company = self.env["res.company"].create({"name": "Test"})
company.zip_id = self.barcelona.id
company._inverse_city_id()
company._inverse_zip_id()
self.assertEqual(company.zip_id, company.partner_id.zip_id)
self.assertEqual(company.city_id, company.partner_id.city_id)
def test_onchange_company_city_id_completion(self):
"""Test city auto-completion when changing zip in a company"""
company = self.env["res.company"].new({"name": "Test"})
company.zip_id = self.barcelona
company._onchange_zip_id()
self.assertEqual(company.city_id, self.barcelona.city_id)
def test_constrains_partner_01(self):
"""Test zip_id constraints"""
with self.assertRaises(ValidationError):
self.partner_obj.create(
{"name": "P1", "zip_id": self.barcelona.id, "state_id": False}
)
with self.assertRaises(ValidationError):
self.partner_obj.create(
{"name": "P1", "zip_id": self.barcelona.id, "country_id": False}
)
with self.assertRaises(ValidationError):
self.partner_obj.create(
{"name": "P1", "zip_id": self.barcelona.id, "city_id": False}
)
with self.assertRaises(ValidationError):
self.partner_obj.create(
{"name": "P1", "zip_id": self.barcelona.id, "zip": False}
)
def test_writing_company(self):
self.company.zip_id = self.barcelona
def test_constrains_partner_country(self):
"""Test partner country constraints"""
partner = self.partner_obj.create(
{
"name": "P1",
"zip_id": self.barcelona.id,
"country_id": self.barcelona.city_id.country_id.id,
"state_id": self.barcelona.city_id.state_id.id,
"city_id": self.barcelona.city_id.id,
}
)
with self.assertRaises(ValidationError):
partner.country_id = self.ref("base.ch")
def test_constrains_partner_state(self):
"""Test partner state constraints"""
partner = self.partner_obj.create(
{
"name": "P1",
"zip_id": self.barcelona.id,
"country_id": self.barcelona.city_id.country_id.id,
"state_id": self.barcelona.city_id.state_id.id,
"city_id": self.barcelona.city_id.id,
}
)
with self.assertRaises(ValidationError):
partner.state_id = self.state_vd.id
def test_constrains_partner_city(self):
"""Test partner city constraints"""
partner = self.partner_obj.create(
{
"name": "P1",
"zip_id": self.barcelona.id,
"country_id": self.barcelona.city_id.country_id.id,
"state_id": self.barcelona.city_id.state_id.id,
"city_id": self.barcelona.city_id.id,
}
)
with self.assertRaises(ValidationError):
partner.city_id = self.city_lausanne
def test_partner_onchange_country(self):
"""Test partner onchange country_id"""
partner = self.partner_obj.new({"name": "TEST", "zip_id": self.lausanne.id})
partner.country_id = self.env.ref("base.es")
partner._onchange_country_id()
self.assertFalse(partner.zip_id)
def test_partner_onchange_city(self):
"""Test partner onchange city_id"""
partner = Form(self.env["res.partner"])
partner.zip_id = self.lausanne
self.city_bcn.country_id.enforce_cities = False
partner.city_id = self.city_bcn
self.assertFalse(partner.zip_id)
def test_partner_onchange_state(self):
"""Test partner onchange state_id"""
partner = Form(self.env["res.partner"])
partner.zip_id = self.lausanne
partner.state_id = self.state_bcn
self.assertFalse(partner.zip_id)
self.assertEqual(partner.country_id, self.country_es)
def test_company_onchange_state(self):
"""Test company onchange state_id"""
self.company.state_id = self.state_bcn
self.company._onchange_state_id()
self.assertEqual(self.company.country_id, self.company.state_id.country_id)
def test_partner_address_field_sync(self):
"""Test that zip_id is correctly synced with parent of contact addresses"""
parent = self.env["res.partner"].create(
{
"name": "ACME Inc.",
"is_company": True,
"street": "123 Fake St.",
"city": "Springfield",
"state_id": self.barcelona.state_id.id,
"country_id": self.barcelona.country_id.id,
"zip_id": self.barcelona.id,
}
)
contact = self.env["res.partner"].create(
{
"name": "John Doe",
"type": "contact",
"parent_id": parent.id,
}
)
parent.zip_id = self.lausanne
self.assertEqual(contact.zip_id, self.lausanne, "Contact should be synced")
def test_display_name(self):
"""Test if the display_name is stored and computed properly"""
self.assertEqual(
self.lausanne.display_name,
"666, Lausanne, Vaud, " + self.browse_ref("base.ch").name,
)
def test_name_search(self):
"""Test that zips can be searched through both the name of the
city or the zip code"""
madrid_data = {"city_id": self.city_madrid.id, "name": "555"}
madrid = self.env["res.city.zip"].create(madrid_data)
found_recs = self.env["res.city.zip"].name_search(name="444")
self.assertEqual(len(found_recs), 1)
self.assertEqual(found_recs[0][0], self.barcelona.id)
found_recs = self.env["res.city.zip"].name_search(name="Barcelona")
self.assertEqual(len(found_recs), 1)
self.assertEqual(found_recs[0][0], self.barcelona.id)
found_recs = self.env["res.city.zip"].name_search(name="555")
self.assertEqual(len(found_recs), 1)
self.assertEqual(found_recs[0][0], madrid.id)
found_recs = self.env["res.city.zip"].name_search(name="Madrid")
self.assertEqual(len(found_recs), 1)
self.assertEqual(found_recs[0][0], madrid.id)
found_recs = self.env["res.city.zip"].name_search(name="666")
self.assertEqual(len(found_recs), 1)
self.assertEqual(found_recs[0][0], self.lausanne.id)
found_recs = self.env["res.city.zip"].name_search(name="Lausanne")
self.assertEqual(len(found_recs), 1)
self.assertEqual(found_recs[0][0], self.lausanne.id)
def test_zip_ql_constraints(self):
"""Test UNIQUE name within it's area for zips"""
with self.assertRaises(psycopg2.IntegrityError), mute_logger("odoo.sql_db"):
self.env["res.city.zip"].create(
{"name": "666", "city_id": self.city_lausanne.id}
)
def test_city_sql_contraint(self):
"""Test UNIQUE name within it's area for cities"""
with self.assertRaises(psycopg2.IntegrityError), mute_logger("odoo.sql_db"):
self.env["res.city"].create(
{
"name": "Barcelona",
"state_id": self.state_bcn.id,
"country_id": self.ref("base.es"),
}
)
| 41.035587
| 11,531
|
610
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Aitor Bouzas <aitor.bouzas@adaptivecity.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class City(models.Model):
_inherit = "res.city"
zip_ids = fields.One2many("res.city.zip", "city_id", string="Zips in this city")
_sql_constraints = [
(
"name_state_country_uniq",
"UNIQUE(name, state_id, country_id)",
"You already have a city with that name in the same state."
"The city must have a unique name within "
"it's state and it's country",
)
]
| 30.5
| 610
|
1,648
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Nicolas Bessi, Camptocamp SA
# Copyright 2018 Aitor Bouzas <aitor.bouzas@adaptivecity.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ResCityZip(models.Model):
"""City/locations completion object"""
_name = "res.city.zip"
_description = __doc__
_order = "name asc"
_rec_name = "display_name"
name = fields.Char("ZIP", required=True)
city_id = fields.Many2one(
"res.city",
"City",
required=True,
auto_join=True,
ondelete="cascade",
index=True,
)
state_id = fields.Many2one(related="city_id.state_id")
country_id = fields.Many2one(related="city_id.country_id")
display_name = fields.Char(
compute="_compute_new_display_name", store=True, index=True
)
_sql_constraints = [
(
"name_city_uniq",
"UNIQUE(name, city_id)",
"You already have a zip with that code in the same city. "
"The zip code must be unique within it's city",
)
]
@api.depends(
"name",
"city_id",
"city_id.name",
"city_id.state_id",
"city_id.state_id.name",
"city_id.country_id",
"city_id.country_id.name",
)
def _compute_new_display_name(self):
for rec in self:
name = [rec.name, rec.city_id.name]
if rec.city_id.state_id:
name.append(rec.city_id.state_id.name)
if rec.city_id.country_id:
name.append(rec.city_id.country_id.name)
rec.display_name = ", ".join(name)
| 29.428571
| 1,648
|
3,082
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Nicolas Bessi, Camptocamp SA
# Copyright 2018 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ResCompany(models.Model):
_inherit = "res.company"
# In order to keep the same logic used in Odoo, fields must be computed
# and inversed, not related. This way we can ensure that it works
# correctly on changes and that inconsistencies cannot happen.
# When you make the fields related, the constrains added in res.partner
# will fail, because when you change the city_id in the company, you are
# effectively changing it in the partner. The constrains on the partner
# are evaluated before the inverse methods update the other fields (city,
# etc..) so we need them to ensure consistency.
# As a conclusion, address fields are very related to each other.
# Either you make them all related to the partner in company, or you
# don't for all of them. Mixing both approaches produces inconsistencies.
city_id = fields.Many2one(
"res.city",
compute="_compute_address",
inverse="_inverse_city_id",
string="City ID",
)
zip_id = fields.Many2one(
"res.city.zip",
string="ZIP Location",
compute="_compute_address",
inverse="_inverse_zip_id",
help="Use the city name or the zip code to search the location",
)
country_enforce_cities = fields.Boolean(
related="partner_id.country_id.enforce_cities"
)
def _get_company_address_field_names(self):
"""Add to the list of field to populate in _compute_address the new
ZIP field + the city that is not handled at company level in
`base_address_city`.
"""
res = super()._get_company_address_field_names()
res += ["city_id", "zip_id"]
return res
def _inverse_city_id(self):
for company in self.with_context(skip_check_zip=True):
company.partner_id.city_id = company.city_id
def _inverse_zip_id(self):
for company in self.with_context(skip_check_zip=True):
company.partner_id.zip_id = company.zip_id
def _inverse_state(self):
self = self.with_context(skip_check_zip=True)
return super(ResCompany, self)._inverse_state()
def _inverse_country(self):
self = self.with_context(skip_check_zip=True)
return super(ResCompany, self)._inverse_country()
@api.onchange("zip_id")
def _onchange_zip_id(self):
if self.zip_id:
self.update(
{
"zip": self.zip_id.name,
"city_id": self.zip_id.city_id,
"city": self.zip_id.city_id.name,
"country_id": self.zip_id.city_id.country_id,
"state_id": self.zip_id.city_id.state_id,
}
)
@api.onchange("state_id")
def _onchange_state_id(self):
if self.state_id.country_id:
self.country_id = self.state_id.country_id.id
| 38.049383
| 3,082
|
6,277
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Nicolas Bessi, Camptocamp SA
# Copyright 2018 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from lxml import etree
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ResPartner(models.Model):
_inherit = "res.partner"
zip_id = fields.Many2one(
comodel_name="res.city.zip",
string="ZIP Location",
index=True,
compute="_compute_zip_id",
readonly=False,
store=True,
)
city_id = fields.Many2one(
index=True, # add index for performance
compute="_compute_city_id",
readonly=False,
store=True,
)
city = fields.Char(compute="_compute_city", readonly=False, store=True)
zip = fields.Char(compute="_compute_zip", readonly=False, store=True)
country_id = fields.Many2one(
compute="_compute_country_id", readonly=False, store=True
)
state_id = fields.Many2one(compute="_compute_state_id", readonly=False, store=True)
@api.depends("state_id", "country_id", "city_id", "zip")
def _compute_zip_id(self):
"""Empty the zip auto-completion field if data mismatch when on UI."""
for record in self.filtered("zip_id"):
fields_map = {
"zip": "name",
"city_id": "city_id",
"state_id": "state_id",
"country_id": "country_id",
}
for rec_field, zip_field in fields_map.items():
if (
record[rec_field]
and record[rec_field] != record._origin[rec_field]
and record[rec_field] != record.zip_id[zip_field]
):
record.zip_id = False
break
@api.depends("zip_id")
def _compute_city_id(self):
if hasattr(super(), "_compute_city_id"):
return super()._compute_city_id() # pragma: no cover
for record in self:
if record.zip_id:
record.city_id = record.zip_id.city_id
elif not record.country_enforce_cities:
record.city_id = False
@api.depends("zip_id")
def _compute_city(self):
if hasattr(super(), "_compute_city"):
return super()._compute_city() # pragma: no cover
for record in self:
if record.zip_id:
record.city = record.zip_id.city_id.name
@api.depends("zip_id")
def _compute_zip(self):
if hasattr(super(), "_compute_zip"):
return super()._compute_zip() # pragma: no cover
for record in self:
if record.zip_id:
record.zip = record.zip_id.name
@api.depends("zip_id", "state_id")
def _compute_country_id(self):
if hasattr(super(), "_compute_country_id"):
return super()._compute_country_id() # pragma: no cover
for record in self:
if record.zip_id.city_id.country_id:
record.country_id = record.zip_id.city_id.country_id
elif record.state_id:
record.country_id = record.state_id.country_id
@api.depends("zip_id")
def _compute_state_id(self):
if hasattr(super(), "_compute_state_id"):
return super()._compute_state_id() # pragma: no cover
for record in self:
state = record.zip_id.city_id.state_id
if state and record.state_id != state:
record.state_id = record.zip_id.city_id.state_id
@api.constrains("zip_id", "country_id", "city_id", "state_id", "zip")
def _check_zip(self):
if self.env.context.get("skip_check_zip"):
return
for rec in self:
if not rec.zip_id:
continue
error_dict = {"partner": rec.name, "location": rec.zip_id.name}
if rec.zip_id.city_id.country_id != rec.country_id:
raise ValidationError(
_(
"The country of the partner %(partner)s differs from that in "
"location %(location)s"
)
% error_dict
)
if rec.zip_id.city_id.state_id != rec.state_id:
raise ValidationError(
_(
"The state of the partner %(partner)s differs from that in "
"location %(location)s"
)
% error_dict
)
if rec.zip_id.city_id != rec.city_id:
raise ValidationError(
_(
"The city of the partner %(partner)s differs from that in "
"location %(location)s"
)
% error_dict
)
if rec.zip_id.name != rec.zip:
raise ValidationError(
_(
"The zip of the partner %(partner)s differs from that in "
"location %(location)s"
)
% error_dict
)
def _zip_id_domain(self):
return """
[
("city_id", "=?", city_id),
("city_id.country_id", "=?", country_id),
("city_id.state_id", "=?", state_id),
]
"""
@api.model
def _fields_view_get_address(self, arch):
# We want to use a domain that requires city_id to be on the view
# but we can't add it directly there, otherwise _fields_view_get_address
# in base_address_city won't do its magic, as it immediately returns
# if city_id is already in there. On the other hand, if city_id is not in the
# views, odoo won't let us use it in zip_id's domain.
# For this reason we need to set the domain here.
arch = super()._fields_view_get_address(arch)
doc = etree.fromstring(arch)
for node in doc.xpath("//field[@name='zip_id']"):
node.attrib["domain"] = self._zip_id_domain()
return etree.tostring(doc, encoding="unicode")
@api.model
def _address_fields(self):
return super()._address_fields() + ["zip_id", "city_id"]
| 38.042424
| 6,277
|
692
|
py
|
PYTHON
|
15.0
|
# Copyright 2019-2020: Druidoo (<https://www.druidoo.io>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Contact's Age Range",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "Druidoo, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"category": "Customer Relationship Management",
"summary": "Age Range for Contact's",
"depends": ["contacts", "partner_contact_birthdate"],
"data": [
"security/ir.model.access.csv",
"data/age_range_cron.xml",
"views/res_partner_view.xml",
"views/res_partner_age_range_view.xml",
],
"installable": True,
}
| 34.6
| 692
|
1,650
|
py
|
PYTHON
|
15.0
|
# Copyright 2019-2020: Druidoo (<https://www.druidoo.io>)
# Copyright 2020 Ecosoft Co., Ltd (http://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo.exceptions import ValidationError
from odoo.tests.common import TransactionCase
class TestRespartnerAgeRange(TransactionCase):
def setUp(self):
super().setUp()
self.range_model = self.env["res.partner.age.range"]
self.partner_model = self.env["res.partner"]
self.baby_range = self.range_model.create(
{"name": "baby", "age_from": 0, "age_to": 2}
)
self.partner = self.partner_model.create(
{
"name": "Test",
"birthdate_date": datetime.today() - relativedelta(years=1, days=10),
}
)
def test_age_from(self):
age_from = self.range_model._default_age_from()
toddler_range = self.range_model.create(
{"name": "Toddler", "age_from": age_from, "age_to": 4}
)
self.assertEqual(toddler_range.age_from, self.baby_range.age_to + 1)
def test_validate_range(self):
with self.assertRaises(ValidationError):
self.range_model.create({"name": "Child", "age_from": 1, "age_to": 12})
with self.assertRaises(ValidationError):
self.range_model.create({"name": "Teenager", "age_from": 16, "age_to": 15})
def test_cron_update_age_range_id(self):
self.partner_model._cron_update_age_range_id()
self.assertEqual(self.partner.age_range_id, self.baby_range)
| 38.372093
| 1,650
|
1,909
|
py
|
PYTHON
|
15.0
|
# Copyright 2019-2020: Druidoo (<https://www.druidoo.io>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ResPartnerDateRange(models.Model):
_name = "res.partner.age.range"
_description = "Partner Age Range"
def _default_age_from(self):
age_from = 0
last_age_range = self.env["res.partner.age.range"].search(
[], order="age_to desc", limit=1
)
if last_age_range:
age_from = last_age_range.age_to + 1
return age_from
name = fields.Char(required=True)
age_from = fields.Integer(
string="From", required=True, default=lambda self: self._default_age_from()
)
age_to = fields.Integer(string="To", required=True)
_sql_constraints = [("name_uniq", "unique (name)", "A name must be unique !")]
@api.constrains("age_from", "age_to")
def _validate_range(self):
for rec in self:
if rec.age_from >= rec.age_to:
raise ValidationError(
_(
"%(name)s is not a valid range (%(age_from)s >= %(age_to)s)",
name=rec.name,
age_from=rec.age_from,
age_to=rec.age_to,
)
)
range_id = rec.search(
[
("age_from", "<=", rec.age_to),
("age_to", ">=", rec.age_from),
("id", "!=", rec.id),
],
limit=1,
)
if range_id:
raise ValidationError(
_(
"%(name)s is overalapping with range %(age_from)s",
name=rec.name,
age_from=range_id.name,
)
)
| 34.089286
| 1,909
|
1,317
|
py
|
PYTHON
|
15.0
|
# Copyright 2019-2020: Druidoo (<https://www.druidoo.io>)
# 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"
age_range_id = fields.Many2one(
"res.partner.age.range",
"Age Range",
compute="_compute_age_range_id",
store=True,
)
@api.depends("age")
def _compute_age_range_id(self):
age_ranges = self.env["res.partner.age.range"].search([])
for record in self:
if record.age >= 0:
age_range = (
age_ranges.filtered(
lambda age_range: age_range.age_from
<= record.age
<= age_range.age_to
)
or False
)
else:
age_range = False
if record.age_range_id != age_range:
record.age_range_id = age_range and age_range.id or age_range
@api.model
def _cron_update_age_range_id(self):
"""
This method is called from a cron job.
It is used to update age range on contact
"""
partners = self.search([("birthdate_date", "!=", False)])
partners._compute_age_range_id()
| 31.357143
| 1,317
|
687
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# Copyright 2015 Antiun Ingenieria S.L. - Antonio Espinosa
# Copyright 2017 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Partner second last name",
"summary": "Have split first and second lastnames",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"website": "https://github.com/OCA/partner-contact",
"author": "Tecnativa, " "Odoo Community Association (OCA)",
"category": "Partner Management",
"depends": ["partner_firstname"],
"data": ["views/res_partner.xml", "views/res_user.xml"],
"installable": True,
}
| 40.352941
| 686
|
1,220
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class TestConfig(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestConfig, cls).setUpClass()
cls.wizard = cls.env["res.config.settings"].create({})
cls.partner = cls.env["res.partner"].create(
{"firstname": "First", "lastname": "Last", "lastname2": "Second"}
)
def test_last_first(self):
self.wizard.partner_names_order = "last_first"
self.wizard.set_values()
self.wizard.action_recalculate_partners_name()
self.assertEqual(self.partner.name, "Last Second First")
def test_last_first_comma(self):
self.wizard.partner_names_order = "last_first_comma"
self.wizard.set_values()
self.wizard.action_recalculate_partners_name()
self.assertEqual(self.partner.name, "Last Second, First")
def test_first_last(self):
self.wizard.partner_names_order = "first_last"
self.wizard.set_values()
self.wizard.action_recalculate_partners_name()
self.assertEqual(self.partner.name, "First Last Second")
| 38.125
| 1,220
|
7,046
|
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
# Copyright 2015 Grupo ESOC Ingeniería de Servicios, S.L.U.
# Copyright 2015 Antiun Ingenieria S.L. - Antonio Espinosa
from odoo.tests.common import TransactionCase
from odoo.addons.partner_firstname.tests.base import MailInstalled
class CompanyCase(TransactionCase):
"""Test ``res.partner`` when it is a company."""
def setUp(self):
super(CompanyCase, self).setUp()
self.env["ir.config_parameter"].set_param("partner_names_order", "first_last")
def tearDown(self):
try:
new = self.env["res.partner"].create(
{"is_company": True, "name": self.name}
)
# Name should be cleaned of unneeded whitespace
clean_name = " ".join(self.name.split(None))
# Check it's saved OK
self.assertEqual(new.name, clean_name, "Saved company name is wrong.")
# Check it's saved in the lastname
self.assertEqual(
new.lastname,
clean_name,
"Company name should be saved in the lastname field.",
)
# Check that other fields are empty
self.assertEqual(
new.firstname, False, "Company first name must always be empty."
)
self.assertEqual(
new.lastname2, False, "Company last name 2 must always be empty."
)
finally:
super(CompanyCase, self).tearDown()
def test_long_name(self):
"""Create a company with a long name."""
self.name = "Söme very lóng nâme"
def test_short_name(self):
"""Create a company with a short name."""
self.name = "Shoŕt"
def test_whitespace_before(self):
"""Create a company with name prefixed with whitespace."""
self.name = " Wĥitespace befòre"
def test_whitespace_after(self):
"""Create a company with name suffixed with whitespace."""
self.name = "Whitespâce aftér "
def test_whitespace_inside(self):
"""Create a company with whitespace inside the name."""
self.name = "Whitespacé ïnside"
def test_whitespace_everywhere(self):
"""Create a company with whitespace everywhere in the name."""
self.name = " A lot öf whitespace "
class PersonCase(TransactionCase):
"""Test ``res.partner`` when it is a person."""
model = "res.partner"
context = dict()
def setUp(self):
super(PersonCase, self).setUp()
self.env["ir.config_parameter"].set_param(
"partner_names_order", "last_first_comma"
)
self.firstname = "Fírstname"
self.lastname = "Làstname1"
self.lastname2 = "Lâstname2"
self.template = "%(last1)s %(last2)s, %(first)s"
def tearDown(self):
try:
new = self.env[self.model].with_context(**self.context).create(self.params)
# Check that each individual field matches
self.assertEqual(self.firstname, new.firstname, "First name saved badly.")
self.assertEqual(self.lastname, new.lastname, "Last name 1 saved badly.")
self.assertEqual(self.lastname2, new.lastname2, "Last name 2 saved badly.")
# Check that name gets saved fine
self.assertEqual(
self.template
% (
{
"last1": self.lastname,
"last2": self.lastname2,
"first": self.firstname,
}
),
new.name,
"Name saved badly.",
)
finally:
super(PersonCase, self).tearDown()
def test_firstname_first(self):
"""Create a person setting his first name first."""
self.env["ir.config_parameter"].set_param("partner_names_order", "first_last")
self.template = "%(first)s %(last1)s %(last2)s"
self.params = {
"is_company": False,
"name": "{} {} {}".format(self.firstname, self.lastname, self.lastname2),
}
def test_firstname_last(self):
"""Create a person setting his first name last."""
self.params = {
"is_company": False,
"name": "{} {}, {}".format(self.lastname, self.lastname2, self.firstname),
}
def test_firstname_last_wo_comma(self):
"""Create a person setting his first name last and the order as 'last_first'"""
self.env["ir.config_parameter"].set_param("partner_names_order", "last_first")
self.template = "%(last1)s %(last2)s %(first)s"
self.params = {
"is_company": False,
"name": "{} {} {}".format(self.lastname, self.lastname2, self.firstname),
}
def test_firstname_only(self):
"""Create a person setting his first name only."""
self.env["ir.config_parameter"].set_param("partner_names_order", "first_last")
self.firstname = self.lastname2 = False
self.template = "%(last1)s"
self.params = {
"is_company": False,
"name": self.lastname,
}
def test_firstname_lastname_only(self):
"""Create a person setting his first name and last name 1 only."""
self.env["ir.config_parameter"].set_param("partner_names_order", "first_last")
self.lastname2 = False
self.template = "%(first)s %(last1)s"
self.params = {
"is_company": False,
"name": "{} {}".format(self.firstname, self.lastname),
}
def test_lastname_firstname_only(self):
"""Create a person setting his last name 1 and first name only."""
self.lastname2 = False
self.template = "%(last1)s, %(first)s"
self.params = {
"is_company": False,
"name": "{}, {}".format(self.lastname, self.firstname),
}
def test_lastname_firstname_only_wo_comma(self):
"""Create a person setting his last name 1 and first name only.
Set order to 'last_first' to test name split without comma"""
self.env["ir.config_parameter"].set_param("partner_names_order", "last_first")
self.lastname2 = False
self.template = "%(last1)s %(first)s"
self.params = {
"is_company": False,
"name": "{} {}".format(self.lastname, self.firstname),
}
def test_separately(self):
"""Create a person setting separately all fields."""
self.params = {
"is_company": False,
"firstname": self.firstname,
"lastname": self.lastname,
"lastname2": self.lastname2,
}
class UserCase(PersonCase, MailInstalled):
"""Test ``res.users``."""
model = "res.users"
context = {"default_login": "user@example.com"}
def tearDown(self):
# Skip if ``mail`` is installed
if not self.mail_installed():
super(UserCase, self).tearDown()
| 35.331658
| 7,031
|
1,225
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Antiun Ingenieria S.L. - Antonio Espinosa
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
def _partner_names_order_selection(self):
options = super(ResConfigSettings, self)._partner_names_order_selection()
new_labels = {
"last_first": "Lastname SecondLastname Firstname",
"last_first_comma": "Lastname SecondLastname, Firstname",
"first_last": "Firstname Lastname SecondLastname",
}
return [(k, new_labels[k]) if k in new_labels else (k, v) for k, v in options]
def _partners_for_recalculating(self):
return self.env["res.partner"].search(
[
("is_company", "=", False),
"|",
"&",
("firstname", "!=", False),
("lastname", "!=", False),
"|",
"&",
("firstname", "!=", False),
("lastname2", "!=", False),
"&",
("lastname", "!=", False),
("lastname2", "!=", False),
]
)
| 35
| 1,225
|
4,171
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# Copyright 2015 Antiun Ingenieria S.L. - Antonio Espinosa
# Copyright 2017 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
from odoo.addons.partner_firstname import exceptions
class ResPartner(models.Model):
"""Adds a second last name."""
_inherit = "res.partner"
lastname2 = fields.Char(
"Second last name",
)
@api.model
def _get_computed_name(self, lastname, firstname, lastname2=None):
"""Compute the name combined with the second lastname too.
We have 2 lastnames, so lastnames and firstname will be separated by a
comma.
"""
order = self._get_names_order()
names = list()
if order == "first_last":
if firstname:
names.append(firstname)
if lastname:
names.append(lastname)
if lastname2:
names.append(lastname2)
else:
if lastname:
names.append(lastname)
if lastname2:
names.append(lastname2)
if names and firstname and order == "last_first_comma":
names[-1] = names[-1] + ","
if firstname:
names.append(firstname)
return " ".join(names)
@api.depends("firstname", "lastname", "lastname2")
def _compute_name(self):
"""Write :attr:`~.name` according to splitted data."""
for partner in self:
partner.name = self._get_computed_name(
partner.lastname,
partner.firstname,
partner.lastname2,
)
def _inverse_name(self):
"""Try to revert the effect of :meth:`._compute_name`."""
self.ensure_one()
parts = self._get_inverse_name(self.name, self.is_company)
# Avoid to hit :meth:`~._check_name` with all 3 fields being ``False``
before, after = {}, {}
for key, value in parts.items():
(before if value else after)[key] = value
if any([before[k] != self[k] for k in list(before.keys())]):
self.update(before)
if any([after[k] != self[k] for k in list(after.keys())]):
self.update(after)
@api.model
def _get_inverse_name(self, name, is_company=False):
"""Compute the inverted name.
- If the partner is a company, save it in the lastname.
- Otherwise, make a guess.
"""
result = {
"firstname": False,
"lastname": name or False,
"lastname2": False,
}
# Company name goes to the lastname
if not name or is_company:
return result
order = self._get_names_order()
result.update(super(ResPartner, self)._get_inverse_name(name, is_company))
if order in ("first_last", "last_first_comma"):
parts = self._split_part("lastname", result)
if parts:
result.update({"lastname": parts[0], "lastname2": " ".join(parts[1:])})
else:
parts = self._split_part("firstname", result)
if parts:
result.update(
{"firstname": parts[-1], "lastname2": " ".join(parts[:-1])}
)
return result
def _split_part(self, name_part, name_split):
"""Split a given part of a name.
:param name_split: The parts of the name
:type dict
:param name_part: The part to split
:type str
"""
name = name_split.get(name_part, False)
parts = name.split(" ", 1) if name else []
if not name or len(parts) < 2:
return False
return parts
@api.constrains("firstname", "lastname", "lastname2")
def _check_name(self):
"""Ensure at least one name is set."""
try:
return super(ResPartner, self)._check_name()
except exceptions.EmptyNamesError:
for partner in self:
if not partner.lastname2:
raise
| 33.36
| 4,170
|
921
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2020 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Animal",
"version": "15.0.1.1.0",
"license": "AGPL-3",
"summary": "Manage animals information",
"author": "Open Source Integrators, Odoo Community Association (OCA)",
"maintainer": "Open Source Integrators",
"website": "https://github.com/OCA/partner-contact",
"depends": ["mail"],
"data": [
"data/ir.module.category.csv",
"data/animal.species.csv",
"data/animal.breed.csv",
"data/animal.color.csv",
"security/res_groups.xml",
"security/ir.model.access.csv",
"views/animal_color.xml",
"views/animal_breed.xml",
"views/animal_species.xml",
"views/animal.xml",
"views/menu.xml",
],
"application": True,
"development_status": "Beta",
"maintainers": ["max3903"],
}
| 32.892857
| 921
|
1,146
|
py
|
PYTHON
|
15.0
|
from odoo.tests.common import TransactionCase
# @tagged('-at_install', 'post_install')
class TestAnimalState(TransactionCase):
def setUp(self, *args, **kwargs):
super(TestAnimalState, self).setUp(*args, **kwargs)
self.test_species = self.env["animal.species"].create({"name": "specie 1"})
self.test_breed = self.env["animal.breed"].create(
{"name": "breed 1", "species_id": self.test_species.id}
)
self.test_animal = self.env["animal"].create(
{
"name": "Animal 1",
"species_id": self.test_species.id,
"breed_id": self.test_breed.id,
}
)
def test_onchange_species(self):
self.test_animal.onchange_species()
self.assertEqual(
self.test_animal.breed_id.id,
False,
"Animal breed_id should be changed to False",
)
def test_onchange_breed(self):
self.test_animal.onchange_breed()
self.assertEqual(
self.test_animal.color_id.id,
False,
"Animal color_id should be changed to False",
)
| 33.705882
| 1,146
|
382
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2020 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AnimalSpecies(models.Model):
_name = "animal.species"
_description = "Animal Species"
_order = "name"
name = fields.Char(translate=True)
breed_ids = fields.One2many("animal.breed", "species_id", string="Breeds")
| 31.833333
| 382
|
1,301
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2020 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class Animal(models.Model):
_name = "animal"
_description = "Animal"
_inherit = ["mail.thread", "mail.activity.mixin"]
_order = "name"
name = fields.Char()
ref = fields.Char(string="Reference")
species_id = fields.Many2one("animal.species", string="Species", required=True)
breed_id = fields.Many2one("animal.breed", string="Breed", required=True)
color_id = fields.Many2one("animal.color", string="Color")
size = fields.Char()
weight = fields.Float(string="Weight (in kg)")
birth_date = fields.Date()
gender = fields.Selection(
selection=[
("female", "Female"),
("male", "Male"),
("hermaphrodite", "Hermaphrodite"),
("neutered", "Neutered"),
],
default="female",
required=True,
)
active = fields.Boolean(default=True)
image = fields.Binary(
attachment=True, help="This field holds the photo of the animal."
)
@api.onchange("species_id")
def onchange_species(self):
self.breed_id = False
@api.onchange("breed_id")
def onchange_breed(self):
self.color_id = False
| 31.731707
| 1,301
|
485
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2020 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AnimalColor(models.Model):
_name = "animal.color"
_description = "Animal Colors"
name = fields.Char(translate=True)
breed_id = fields.Many2one("animal.breed", string="Breed", required=True)
species_id = fields.Many2one(
"animal.species", string="Species", related="breed_id.species_id", readonly=True
)
| 34.642857
| 485
|
382
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2020 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AnimalBreed(models.Model):
_name = "animal.breed"
_description = "Animal Breeds"
_order = "name"
name = fields.Char(translate=True)
species_id = fields.Many2one("animal.species", string="Species", required=True)
| 31.833333
| 382
|
658
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow S.L.
# Copyright 2022 Vauxoo, S.A.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Partner Manual Rank",
"summary": "Be able to manually flag partners as customer or supplier.",
"version": "15.0.1.0.0",
"category": "Partner Management",
"website": "https://github.com/OCA/partner-contact",
"author": "ForgeFlow, Vauxoo, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"maintainers": [
"luisg123v",
"frahikLV",
],
"depends": [
"account",
],
"data": [
"views/res_partner.xml",
],
}
| 27.416667
| 658
|
2,761
|
py
|
PYTHON
|
15.0
|
from odoo.tests import common, tagged
@tagged("res_partner")
class TestResPartner(common.TransactionCase):
def setUp(self):
super().setUp()
self.partner = self.env["res.partner"].create({"name": "Microsoft Corporation"})
self.partner_2 = self.env["res.partner"].create({"name": "Apple Inc."})
def test_01_is_customer(self):
partners = self.partner | self.partner_2
self.assertRecordValues(
partners,
[
{"is_customer": False, "customer_rank": 0},
{"is_customer": False, "customer_rank": 0},
],
)
self.partner.write({"is_customer": True})
self.assertRecordValues(
partners,
[
{"is_customer": True, "customer_rank": 1},
{"is_customer": False, "customer_rank": 0},
],
)
partners_found = self.env["res.partner"].search([("is_customer", "=", True)])
self.assertIn(self.partner, partners_found)
partners.write({"is_customer": True})
self.assertRecordValues(
partners,
[
{"is_customer": True, "customer_rank": 1},
{"is_customer": True, "customer_rank": 1},
],
)
partners.write({"is_customer": False})
self.assertRecordValues(
partners,
[
{"is_customer": False, "customer_rank": 0},
{"is_customer": False, "customer_rank": 0},
],
)
def test_02_is_supplier(self):
partners = self.partner | self.partner_2
self.assertRecordValues(
partners,
[
{"is_supplier": False, "supplier_rank": 0},
{"is_supplier": False, "supplier_rank": 0},
],
)
self.partner.write({"is_supplier": True})
self.assertRecordValues(
partners,
[
{"is_supplier": True, "supplier_rank": 1},
{"is_supplier": False, "supplier_rank": 0},
],
)
partners_found = self.env["res.partner"].search([("is_supplier", "=", True)])
self.assertIn(self.partner, partners_found)
partners.write({"is_supplier": True})
self.assertRecordValues(
partners,
[
{"is_supplier": True, "supplier_rank": 1},
{"is_supplier": True, "supplier_rank": 1},
],
)
partners.write({"is_supplier": False})
self.assertRecordValues(
partners,
[
{"is_supplier": False, "supplier_rank": 0},
{"is_supplier": False, "supplier_rank": 0},
],
)
| 34.08642
| 2,761
|
2,183
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow, S.L.
# Copyright 2022 Vauxoo, S.A.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
DOMAIN_SEARCH = {
("=", False): ("=", 0),
("=", True): (">=", 1),
("!=", False): (">=", 1),
("!=", True): ("=", 0),
}
class ResPartner(models.Model):
_inherit = "res.partner"
is_customer = fields.Boolean(
compute="_compute_is_customer",
inverse="_inverse_is_customer",
search="_search_is_customer",
string="Is a Customer",
)
is_supplier = fields.Boolean(
compute="_compute_is_supplier",
inverse="_inverse_is_supplier",
search="_search_is_supplier",
string="Is a Supplier",
)
@api.depends("customer_rank")
def _compute_is_customer(self):
for partner in self:
partner.is_customer = bool(partner.customer_rank)
@api.depends("supplier_rank")
def _compute_is_supplier(self):
for partner in self:
partner.is_supplier = bool(partner.supplier_rank)
def _inverse_is_customer(self):
self.filtered(lambda p: not p.is_customer).write({"customer_rank": 0})
self.filtered(lambda p: p.is_customer and not p.customer_rank).write(
{"customer_rank": 1}
)
def _search_is_customer(self, operator, value):
if operator not in ["=", "!="] or not isinstance(value, bool):
raise UserError(_("Operation not supported"))
operator, value = DOMAIN_SEARCH.get((operator, value))
return [("customer_rank", operator, value)]
def _inverse_is_supplier(self):
self.filtered(lambda p: not p.is_supplier).write({"supplier_rank": 0})
self.filtered(lambda p: p.is_supplier and not p.supplier_rank).write(
{"supplier_rank": 1}
)
def _search_is_supplier(self, operator, value):
if operator not in ["=", "!="] or not isinstance(value, bool):
raise UserError(_("Operation not supported"))
operator, value = DOMAIN_SEARCH.get((operator, value))
return [("supplier_rank", operator, value)]
| 34.109375
| 2,183
|
443
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Ecosoft Co., Ltd. (https://ecosoft.co.th)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Partner Bank Code",
"summary": "Add fields information in banks",
"version": "15.0.1.0.0",
"website": "https://github.com/OCA/partner-contact",
"author": "Ecosoft, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["base"],
"data": ["views/res_bank.xml"],
}
| 34.076923
| 443
|
472
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Ecosoft Co., Ltd. (https://ecosoft.co.th)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResBank(models.Model):
_inherit = "res.bank"
bank_code = fields.Char()
bank_branch_code = fields.Char()
_sql_constraints = [
(
"bank_code_unique",
"unique(bank_code, bank_branch_code)",
"Bank and Branch Code should be unique.",
),
]
| 24.842105
| 472
|
452
|
py
|
PYTHON
|
15.0
|
# Copyright 2020-2022 Quartile Limited
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Partner Name Hide Parent",
"version": "15.0.1.0.0",
"author": "Quartile Limited,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"category": "Extra Tools",
"license": "AGPL-3",
"depends": ["base"],
"data": ["views/res_partner_views.xml"],
"installable": True,
}
| 34.769231
| 452
|
991
|
py
|
PYTHON
|
15.0
|
# Copyright 2020-2022 Quartile Limited
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests.common import TransactionCase
class TestPartnerNameHideParent(TransactionCase):
def test_display_name(self):
test_parent = self.env["res.partner"].create(
{"name": "parent", "is_company": True}
)
test_child = self.env["res.partner"].create(
{
"name": "child",
"is_company": False,
"parent_id": test_parent.id,
"hide_parent": True,
}
)
self.assertEqual(test_child.display_name, "child")
# Confirm that a change on "hide_parent" works as expected as a
# trigger to update display_name
test_child.write({"hide_parent": False})
self.assertEqual(test_child.display_name, "parent, child")
test_child.write({"hide_parent": True})
self.assertEqual(test_child.display_name, "child")
| 35.392857
| 991
|
768
|
py
|
PYTHON
|
15.0
|
# Copyright 2020-2022 Quartile Limited
# 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"
hide_parent = fields.Boolean(
help="If selected, the parent's name will not be included in the "
"display name of self."
)
def _get_contact_name(self, partner, name):
if partner.hide_parent:
return name
return super()._get_contact_name(partner, name)
# Just add "hide_parent" as a trigger.
@api.depends(
"is_company", "name", "parent_id.name", "type", "company_name", "hide_parent"
)
def _compute_display_name(self):
return super(ResPartner, self)._compute_display_name()
| 30.72
| 768
|
719
|
py
|
PYTHON
|
15.0
|
# Copyright 2012 Camptocamp SA - Yannick Vaucher
# Copyright 2017 Tecnativa - Vicent Cubells
# Copyright 2018 brain-tec AG - Raul Martin
# Copyright 2021 Bloopark Systems - Achraf Mhadhbi
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Partner Affiliates",
"version": "15.0.1.0.0",
"author": "Camptocamp, "
"Tecnativa, "
"brain-tec AG, "
"Onestein, "
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"category": "Customer Relationship Management",
"license": "AGPL-3",
"installable": True,
"depends": ["base"],
"data": ["views/res_partner_view.xml"],
"development_status": "Production/Stable",
}
| 34.238095
| 719
|
707
|
py
|
PYTHON
|
15.0
|
# Copyright 2012 Camptocamp SA - Yannick Vaucher
# Copyright 2018 brain-tec AG - Raul Martin
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResPartner(models.Model):
"""Add relation affiliate_ids."""
_inherit = "res.partner"
# force "active_test" domain to bypass _search() override
child_ids = fields.One2many(
domain=[("active", "=", True), ("is_company", "=", False)]
)
# force "active_test" domain to bypass _search() override
affiliate_ids = fields.One2many(
"res.partner",
"parent_id",
string="Affiliates",
domain=[("active", "=", True), ("is_company", "=", True)],
)
| 29.458333
| 707
|
572
|
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Personal information page for contacts",
"summary": "Add a page to contacts form to put personal information",
"version": "15.0.1.0.0",
"category": "Customer Relationship Management",
"website": "https://github.com/OCA/partner-contact",
"author": "Nicolas JEUDY,Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"auto_install": False,
"depends": ["base"],
"data": ["views/res_partner.xml"],
}
| 35.75
| 572
|
905
|
py
|
PYTHON
|
15.0
|
# Copyright 2004-2009 Tiny SPRL (<https://tiny.be>).
# Copyright 2013 initOS GmbH & Co. KG (<https://www.initos.com>).
# Copyright 2016 Tecnativa - Vicent Cubells
# Copyright 2016 Camptocamp - Akim Juillerat (<https://www.camptocamp.com>).
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"author": (
"Tiny/initOS GmbH & Co. KG,"
"ACSONE SA/NV,"
"Tecnativa,"
"Camptocamp,"
"Odoo Community Association (OCA)"
),
"name": "Add a sequence on customers' code",
"version": "15.0.1.0.2",
"development_status": "Production/Stable",
"category": "Generic Modules/Base",
"website": "https://github.com/OCA/partner-contact",
"depends": ["base"],
"summary": "Sets customer's code from a sequence",
"data": ["data/partner_sequence.xml", "views/partner_view.xml"],
"installable": True,
"license": "AGPL-3",
}
| 37.708333
| 905
|
1,825
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 ACSONE SA/NV (<https://acsone.eu>).
# Copyright 2016 Tecnativa - Vicent Cubells
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import odoo.tests.common as common
class TestBasePartnerSequence(common.TransactionCase):
def setUp(self):
super(TestBasePartnerSequence, self).setUp()
self.res_partner = self.env["res.partner"]
self.partner = self.res_partner.create(
{"name": "test1", "email": "test@test.com"}
)
def test_ref_sequence_on_partner(self):
# Test sequence on creating partner and copying it
self.assertTrue(self.partner.ref, "A partner has always a ref.")
copy = self.partner.copy()
self.assertTrue(
copy.ref, "A partner with ref created by copy has a ref by default."
)
def test_ref_sequence_on_contact(self):
# Test if sequence doesn't increase on creating a contact child
contact = self.res_partner.create(
{
"name": "contact1",
"email": "contact@contact.com",
"parent_id": self.partner.id,
}
)
self.assertEqual(
self.partner.ref, contact.ref, "All it's ok as sequence doesn't increase."
)
def test_unique_ref_on_write(self):
"""Assert that on create or on write, a different ref is assigned"""
vals = [
{"name": "test1", "email": "test@test.com"},
{"name": "test2", "email": "test@test.com"},
]
partners = self.env["res.partner"].create(vals)
self.assertFalse(partners[0].ref == partners[1].ref)
partners.write({"ref": False})
self.assertFalse(partners[0].ref)
partners.write({})
self.assertFalse(partners[0].ref == partners[1].ref)
| 36.5
| 1,825
|
2,422
|
py
|
PYTHON
|
15.0
|
# Copyright 2004-2009 Tiny SPRL (<https://tiny.be>).
# Copyright 2013 initOS GmbH & Co. KG (<https://www.initos.com>).
# Copyright 2016 Tecnativa - Vicent Cubells
# Copyright 2016 Camptocamp - Akim Juillerat (<https://www.camptocamp.com>).
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import _, api, exceptions, models
class ResPartner(models.Model):
"""Assigns 'ref' from a sequence on creation and copying"""
_inherit = "res.partner"
def _get_next_ref(self, vals=None):
return self.env["ir.sequence"].next_by_code("res.partner")
@api.model
def create(self, vals):
if not vals.get("ref") and self._needs_ref(vals=vals):
vals["ref"] = self._get_next_ref(vals=vals)
return super(ResPartner, self).create(vals)
def copy(self, default=None):
default = default or {}
if self._needs_ref():
default["ref"] = self._get_next_ref()
return super(ResPartner, self).copy(default=default)
def write(self, vals):
for partner in self:
partner_vals = vals.copy()
if (
not partner_vals.get("ref")
and partner._needs_ref(vals=partner_vals)
and not partner.ref
):
partner_vals["ref"] = partner._get_next_ref(vals=partner_vals)
super(ResPartner, partner).write(partner_vals)
return True
def _needs_ref(self, vals=None):
"""
Checks whether a sequence value should be assigned to a partner's 'ref'
:param vals: known field values of the partner object
:return: true iff a sequence value should be assigned to the\
partner's 'ref'
"""
if not vals and not self: # pragma: no cover
raise exceptions.UserError(
_("Either field values or an id must be provided.")
)
# only assign a 'ref' to commercial partners
if self:
vals = {}
vals["is_company"] = self.is_company
vals["parent_id"] = self.parent_id
return vals.get("is_company") or not vals.get("parent_id")
@api.model
def _commercial_fields(self):
"""
Make the partner reference a field that is propagated
to the partner's contacts
"""
return super(ResPartner, self)._commercial_fields() + ["ref"]
| 36.149254
| 2,422
|
572
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Pedro M. Baeza
# Copyright 2017 Tecnativa - Vicent Cubells
# Copyright 2018 Tecnativa - Cristina Martin
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Deduplicate Contacts by Website",
"version": "15.0.1.0.0",
"category": "Tools",
"website": "https://github.com/OCA/partner-contact",
"author": "Tecnativa, " "Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": ["partner_deduplicate_acl"],
"data": ["wizards/partner_merge_view.xml"],
}
| 35.75
| 572
|
2,449
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Pedro M. Baeza
# Copyright 2018 Tecnativa - Cristina Martin
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
from odoo.tools.safe_eval import safe_eval
class TestDeduplicateByWebsite(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner_1 = (
cls.env["res.partner"]
.with_context(tracking_disable=True)
.create(
{
"name": "Partner 1",
"website": "www.test-deduplicate.com",
"email": "test@deduplicate.com",
}
)
)
def test_deduplicate_by_website(self):
self.partner_2 = (
self.env["res.partner"]
.with_context(tracking_disable=True)
.create(
{
"name": "Partner 2",
"website": "www.test-deduplicate.com",
"email": "test2@deduplicate.com",
}
)
)
wizard = self.env["base.partner.merge.automatic.wizard"].create(
{"group_by_website": True}
)
wizard.action_start_manual_process()
found_match = False
for line in wizard.line_ids:
match_ids = safe_eval(line.aggr_ids)
if self.partner_1.id in match_ids and self.partner_2.id in match_ids:
found_match = True
break
self.assertTrue(found_match)
def test_deduplicate_by_website_and_is_company(self):
self.partner_2 = (
self.env["res.partner"]
.with_context(tracking_disable=True)
.create(
{
"name": "Partner 2",
"website": "www.test-deduplicate.com",
"email": "test@deduplicate.com",
}
)
)
wizard = self.env["base.partner.merge.automatic.wizard"].create(
{"group_by_website": True, "group_by_email": True}
)
wizard.action_start_manual_process()
found_match = False
for line in wizard.line_ids:
match_ids = safe_eval(line.aggr_ids)
if self.partner_1.id in match_ids and self.partner_2.id in match_ids:
found_match = True
break
self.assertTrue(found_match)
| 34.492958
| 2,449
|
1,118
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
group_by_website = fields.Boolean("Website")
def _generate_query(self, fields, maximum_group=100):
"""Inject the additional criteria 'website IS NOT NULL' when needed.
There's no better way to do it, as there are no hooks for adding
this criteria regularly.
"""
query = super(BasePartnerMergeAutomaticWizard, self)._generate_query(
fields, maximum_group=maximum_group
)
if "website" in fields:
if "WHERE" in query:
index = query.find("WHERE")
query = (
query[: index + 6] + "website IS NOT NULL AND " + query[index + 6 :]
)
else:
index = query.find(" GROUP BY")
query = query[:index] + " WHERE website IS NOT NULL" + query[index:]
return query
| 38.551724
| 1,118
|
915
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2020 Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
def post_init_hook(cr, registry):
"""Add street3 to address format"""
query = """
UPDATE res_country
SET address_format = replace(
address_format,
E'%(street2)s\n',
E'%(street2)s\n%(street3)s\n'
)
"""
cr.execute(query)
def uninstall_hook(cr, registry):
"""Remove street3 from address format"""
# Remove %(street3)s\n from address_format
query = """
UPDATE res_country
SET address_format = replace(
address_format,
E'%(street3)s\n',
''
)
"""
cr.execute(query)
# Remove %(street3)s from address_format
query = """
UPDATE res_country
SET address_format = replace(
address_format,
E'%(street3)s',
''
)
"""
cr.execute(query)
| 22.875
| 915
|
646
|
py
|
PYTHON
|
15.0
|
# Copyright 2014-2020 Camptocamp SA
# @author: Nicolas Bessi
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Street3 in addresses",
"summary": "Add a third address line on partners",
"license": "AGPL-3",
"version": "15.0.1.0.0",
"author": "Camptocamp,Odoo Community Association (OCA)",
"maintainer": "Camptocamp",
"category": "Sales",
"depends": ["base_view_inheritance_extension"],
"website": "https://github.com/OCA/partner-contact",
"data": ["views/res_partner.xml"],
"post_init_hook": "post_init_hook",
"uninstall_hook": "uninstall_hook",
"installable": True,
}
| 34
| 646
|
1,319
|
py
|
PYTHON
|
15.0
|
# Copyright 2014-2020 Camptocamp SA
# @author: Nicolas Bessi
# Copyright 2016-2020 Akretion (http://www.akretion.com/)
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests.common import TransactionCase
class TestStreet3(TransactionCase):
def test_partner(self):
# Test address_format has been updated on existing countries
us_country = self.env.ref("base.us")
self.assertTrue("%(street3)s" in us_country.address_format)
homer = self.env["res.partner"].create(
{
"name": "Homer Simpson",
"city": "Springfield",
"street": "742 Evergreen Terrace",
"street2": "Donut Lane",
"street3": "Tho",
"country_id": us_country.id,
}
)
# test synchro of street3 on create
bart = self.env["res.partner"].create(
{
"name": "Bart Simpson",
"parent_id": homer.id,
"type": "contact",
}
)
self.assertEqual(bart.street3, "Tho")
# test synchro of street3 on write
homer.write({"street3": "in OCA we trust"})
self.assertEqual(bart.street3, "in OCA we trust")
| 33.820513
| 1,319
|
483
|
py
|
PYTHON
|
15.0
|
# Copyright 2014-2020 Camptocamp SA
# @author: Nicolas Bessi
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResCountry(models.Model):
"""Override default adresses formatting of countries"""
_inherit = "res.country"
address_format = fields.Text(
default=(
"%(street)s\n%(street2)s\n%(street3)s\n"
"%(city)s %(state_code)s %(zip)s\n"
"%(country_name)s"
)
)
| 25.421053
| 483
|
738
|
py
|
PYTHON
|
15.0
|
# Copyright 2014-2020 Camptocamp SA
# @author: Nicolas Bessi
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ResPartner(models.Model):
"""Add third field in address"""
_inherit = "res.partner"
street3 = fields.Char("Street 3")
@api.model
def _address_fields(self):
res = super()._address_fields()
res.append("street3")
return res
def _display_address(self, without_company=False):
"""Remove empty lines which can happen when street3 field is empty."""
res = super()._display_address(without_company=without_company)
while "\n\n" in res:
res = res.replace("\n\n", "\n")
return res
| 28.384615
| 738
|
599
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Jairo Llopis <jairo.llopis@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Partner phonecalls schedule",
"summary": "Track the time and days your partners expect phone calls",
"version": "15.0.1.0.1",
"category": "Customer Relationship Management",
"website": "https://github.com/OCA/partner-contact",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": ["resource"],
"data": ["security/ir.model.access.csv", "views/res_partner_view.xml"],
}
| 42.785714
| 599
|
6,514
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Jairo Llopis <jairo.llopis@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import datetime, timedelta
from mock import patch
from odoo import fields
from odoo.tests.common import TransactionCase
PATH = "odoo.addons.partner_phonecall_schedule.models.res_partner.datetime"
class CanICallCase(TransactionCase):
@classmethod
def setUpClass(cls):
super(CanICallCase, cls).setUpClass()
cls.Calendar = cls.env["resource.calendar"].with_context(tz="UTC")
cls.Partner = cls.env["res.partner"].with_context(tz="UTC")
cls.some_mornings = cls.Calendar.create(
{
"name": "Some mornings",
"attendance_ids": [
(
0,
0,
{
"name": "Friday morning",
"dayofweek": "4",
"hour_from": 8,
"hour_to": 12,
},
),
(
0,
0,
{
"name": "Next monday morning",
"dayofweek": "0",
"hour_from": 8,
"hour_to": 12,
"date_from": "2017-09-18",
"date_to": "2017-09-18",
},
),
],
}
)
cls.some_evenings = cls.Calendar.create(
{
"name": "Some evenings",
"attendance_ids": [
(
0,
0,
{
"name": "Friday evening",
"dayofweek": "4",
"hour_from": 15,
"hour_to": 19,
},
),
(
0,
0,
{
"name": "Next monday evening",
"dayofweek": "0",
"hour_from": 15,
"hour_to": 19,
"date_from": "2017-09-18",
"date_to": "2017-09-18",
},
),
],
}
)
cls.dude = cls.Partner.create({"name": "Dude"})
cls.dude.phonecall_calendar_ids = cls.some_mornings
def setUp(self):
super(CanICallCase, self).setUp()
# Now it is a friday morning
self.datetime = datetime(2017, 9, 15, 10, 53, 30)
def _allowed(self, now=None):
dude, Partner = self.dude, self.Partner
if now:
dude = dude.with_context(now=now)
Partner = Partner.with_context(now=now)
self.assertTrue(dude.phonecall_available)
self.assertTrue(
Partner.search([("id", "=", dude.id), ("phonecall_available", "=", True)])
)
self.assertTrue(
Partner.search([("id", "=", dude.id), ("phonecall_available", "!=", False)])
)
self.assertFalse(
Partner.search([("id", "=", dude.id), ("phonecall_available", "=", False)])
)
self.assertFalse(
Partner.search([("id", "=", dude.id), ("phonecall_available", "!=", True)])
)
def allowed(self):
# Test mocking datetime.now()
with patch(PATH) as mocked_dt:
mocked_dt.now.return_value = self.datetime
mocked_dt.date.return_value = self.datetime.date()
self._allowed()
# Test sending a datetime object in the context
self._allowed(self.datetime)
# Test sending a string in the context
self._allowed(fields.Datetime.to_string(self.datetime))
def _disallowed(self, now=None):
dude, Partner = self.dude, self.Partner
if now:
dude = dude.with_context(now=now)
Partner = Partner.with_context(now=now)
self.assertFalse(dude.phonecall_available)
self.assertFalse(
Partner.search([("id", "=", dude.id), ("phonecall_available", "=", True)])
)
self.assertFalse(
Partner.search([("id", "=", dude.id), ("phonecall_available", "!=", False)])
)
self.assertTrue(
Partner.search([("id", "=", dude.id), ("phonecall_available", "=", False)])
)
self.assertTrue(
Partner.search([("id", "=", dude.id), ("phonecall_available", "!=", True)])
)
def disallowed(self):
# Test mocking datetime.now()
with patch(PATH) as mocked_dt:
mocked_dt.now.return_value = self.datetime
mocked_dt.date.return_value = self.datetime.date()
self._disallowed()
# Test sending a datetime object in the context
self._disallowed(self.datetime)
# Test sending a string in the context
self._disallowed(fields.Datetime.to_string(self.datetime))
def test_friday_morning(self):
"""I can call dude this morning"""
self.allowed()
def test_friday_evening(self):
"""I cannot call dude this evening"""
self.datetime += timedelta(hours=4)
self.disallowed()
def test_saturday_morning(self):
"""I cannot call dude tomorrow morning"""
self.datetime += timedelta(days=1)
self.disallowed()
def test_saturday_evening(self):
"""I cannot call dude tomorrow evening"""
self.datetime += timedelta(days=1, hours=4)
self.disallowed()
def test_next_monday_morning(self):
"""I can call dude next monday morning"""
self.datetime += timedelta(days=3)
self.allowed()
def test_second_next_monday_morning(self):
"""I cannot call dude second next monday morning"""
self.datetime += timedelta(days=10, hours=4)
self.disallowed()
def test_aggregated_attendances(self):
"""I get aggregated schedules correctly."""
self.dude.phonecall_calendar_ids |= self.some_evenings
all_attendances = (self.some_mornings | self.some_evenings).mapped(
"attendance_ids"
)
self.assertEqual(self.dude.phonecall_calendar_attendance_ids, all_attendances)
| 35.98895
| 6,514
|
3,091
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Jairo Llopis <jairo.llopis@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from __future__ import division
from datetime import datetime
from odoo import api, fields, models
class ResPartner(models.Model):
"""Added phonecall details in the partner."""
_inherit = "res.partner"
phonecall_available = fields.Boolean(
"Available to call",
compute="_compute_phonecall_available",
search="_search_phonecall_available",
help="Is it now a good time to call this partner?",
)
phonecall_calendar_ids = fields.Many2many(
comodel_name="resource.calendar",
string="Phonecall schedule",
help="Best schedule when the contact expects to be called.",
)
phonecall_calendar_attendance_ids = fields.One2many(
comodel_name="resource.calendar.attendance",
string="Aggregated phonecall schedule",
compute="_compute_phonecall_calendar_ids",
help="Aggregation of all available phonecall schedules.",
)
@api.depends("phonecall_calendar_ids", "phonecall_calendar_attendance_ids")
def _compute_phonecall_available(self):
"""Know if a partner is available to call right now."""
Attendance = self.env["resource.calendar.attendance"]
for one in self:
domain = [
("calendar_id", "in", one.phonecall_calendar_ids.ids)
] + one._phonecall_available_domain()
found = Attendance.search(domain, limit=1)
one.phonecall_available = bool(found)
@api.depends("phonecall_calendar_ids")
def _compute_phonecall_calendar_ids(self):
"""Fill attendance aggregation."""
for one in self:
one.phonecall_calendar_attendance_ids = one.mapped(
"phonecall_calendar_ids.attendance_ids"
)
def _search_phonecall_available(self, operator, value):
"""Search quickly if partner is available to call right now."""
Attendance = self.env["resource.calendar.attendance"]
available = Attendance.search(self._phonecall_available_domain())
if operator == "!=" or "not" in operator:
value = not value
operator = "in" if value else "not in"
return [("phonecall_calendar_ids.attendance_ids", operator, available.ids)]
def _phonecall_available_domain(self):
"""Get a domain to know if we are available to call a partner."""
now = fields.Datetime.from_string(self.env.context.get("now", datetime.now()))
date = fields.Date.to_string(now)
now_tz = fields.Datetime.context_timestamp(self, now)
float_time = now_tz.hour + ((now_tz.minute / 60) + now_tz.second) / 60
return [
("dayofweek", "=", str(now.weekday())),
"|",
("date_from", "=", False),
("date_from", "<=", date),
"|",
("date_to", "=", False),
("date_to", ">=", date),
("hour_from", "<=", float_time),
("hour_to", ">=", float_time),
]
| 39.628205
| 3,091
|
643
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Carlos Dauden
# Copyright 2020 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Partner Contact address default",
"summary": "Set a default delivery and invoice address for contacts",
"version": "15.0.1.0.0",
"development_status": "Beta",
"category": "Generic Modules/Base",
"website": "https://github.com/OCA/partner-contact",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["base"],
"data": ["views/res_partner_views.xml"],
}
| 37.823529
| 643
|
2,424
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Carlos Dauden
# Copyright 2020 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
class TestPartnerContactAddressDefault(common.TransactionCase):
def setUp(self):
super().setUp()
self.Partner = self.env["res.partner"]
self.partner = self.Partner.create({"name": "Parent partner"})
self.partner_child_delivery1 = self.Partner.create(
{
"name": "Child delivery 1",
"type": "delivery",
"parent_id": self.partner.id,
}
)
self.partner_child_delivery2 = self.Partner.create(
{
"name": "Child delivery 2",
"type": "delivery",
"parent_id": self.partner.id,
}
)
self.partner_child_invoice = self.Partner.create(
{"name": "Child invoice", "type": "invoice", "parent_id": self.partner.id}
)
def test_contact_address_default(self):
self.partner.partner_delivery_id = self.partner
self.partner.partner_invoice_id = self.partner
res = self.partner.address_get(["delivery", "invoice"])
self.assertEqual(res["delivery"], self.partner.id)
self.assertEqual(res["invoice"], self.partner.id)
self.partner_child_delivery2.partner_delivery_id = self.partner_child_delivery2
self.partner_child_delivery2.partner_invoice_id = self.partner_child_delivery2
res = self.partner_child_delivery2.address_get(["delivery", "invoice"])
self.assertEqual(res["delivery"], self.partner_child_delivery2.id)
self.assertEqual(res["invoice"], self.partner_child_delivery2.id)
def test_contact_address_archived(self):
self.partner.partner_delivery_id = self.partner_child_delivery2
self.partner.partner_invoice_id = self.partner_child_invoice
self.partner_child_invoice.write({"active": False})
self.partner_child_delivery2.write({"active": False})
res = self.partner.address_get(["delivery", "invoice"])
# As partner_child_delivery2 is archived, even though it is set as
# partner_delivery_id it should fall back to partner_child_delivery1 here:
self.assertEqual(res["delivery"], self.partner_child_delivery1.id)
self.assertEqual(res["invoice"], self.partner.id)
| 46.615385
| 2,424
|
1,865
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Carlos Dauden
# Copyright 2020 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
partner_delivery_id = fields.Many2one(
comodel_name="res.partner",
string="Shipping address",
)
partner_invoice_id = fields.Many2one(
comodel_name="res.partner",
string="Invoice address",
)
def get_address_default_type(self):
"""This will be the extension method for other contact types"""
return ["delivery", "invoice"]
def address_get(self, adr_pref=None):
"""Force the delivery or invoice addresses. It will try to default
to the one set in the commercial partner if any"""
res = super().address_get(adr_pref)
adr_pref = adr_pref or []
default_address_type_list = {
x for x in adr_pref if x in self.get_address_default_type()
}
for partner in self:
for addr_type in default_address_type_list:
default_address_id = (
partner["partner_{}_id".format(addr_type)]
or partner.commercial_partner_id["partner_{}_id".format(addr_type)]
)
if default_address_id:
res[addr_type] = default_address_id.id
return res
def write(self, vals):
"""We want to prevent archived contacts as default addresses"""
if vals.get("active") is False:
self.search([("partner_delivery_id", "in", self.ids)]).write(
{"partner_delivery_id": False}
)
self.search([("partner_invoice_id", "in", self.ids)]).write(
{"partner_invoice_id": False}
)
return super().write(vals)
| 37.3
| 1,865
|
645
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Xtendoo - Dani Domínguez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Res partner journal items link",
"summary": "Adds a smart button to grant direct access to their accounting notes",
"version": "15.0.1.0.0",
"category": "Account",
"author": "Dani Domínguez - Xtendoo, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"license": "AGPL-3",
"depends": [
"contacts",
"account",
],
"data": [
"views/account_move_line.xml",
"views/res_partner_view.xml",
],
"installable": True,
}
| 32.15
| 643
|
520
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Partner language according country",
"version": "15.0.1.0.0",
"category": "Customer Relationship Management",
"website": "https://github.com/OCA/partner-contact",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["base"],
"installable": True,
"data": ["views/res_country_view.xml"],
"maintainers": ["victoralmau"],
}
| 37
| 518
|
1,104
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests import Form, TransactionCase
class TestPartnerCountryLang(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.lang_fr = cls.env.ref("base.lang_fr")
cls.lang_fr.active = True
cls.country_fr = cls.env.ref("base.fr")
cls.country_fr.lang = cls.lang_fr.code
cls.partner = cls.env["res.partner"].create({"name": "Mr Odoo"})
def test_partner_onchange(self):
partner_form = Form(self.partner)
partner_form.country_id = self.country_fr
self.assertEqual(partner_form.lang, self.lang_fr.code)
def test_partner_create(self):
partner = self.env["res.partner"].create(
{"name": "Mrs Odoo", "country_id": self.country_fr.id}
)
self.assertEqual(partner.lang, self.lang_fr.code)
def test_partner_write(self):
self.partner.write({"country_id": self.country_fr.id})
self.assertEqual(self.partner.lang, self.lang_fr.code)
| 36.733333
| 1,102
|
441
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
from odoo.addons.base.models.res_partner import _lang_get
class ResCountry(models.Model):
_inherit = "res.country"
lang = fields.Selection(
_lang_get,
string="Enforce language",
help="This country partners' language will be set to this value by default",
)
| 27.4375
| 439
|
1,336
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class ResPartner(models.Model):
_inherit = "res.partner"
@api.onchange("country_id")
def _onchange_country_id(self):
result = super()._onchange_country_id()
if self.country_id.lang:
self.lang = self.country_id.lang
return result
def _adjust_lang_by_country(self, vals):
"""Adjust vals dictionary for adding the language of the country
if no one is included in it, but country is.
"""
if vals.get("country_id") and "lang" not in vals:
country = self.env["res.country"].browse(vals["country_id"])
if country.lang:
vals["lang"] = country.lang
@api.model_create_multi
def create(self, vals_list):
"""Add lang if the partner is created with a country through code
and no language is specified.
"""
for vals in vals_list:
self._adjust_lang_by_country(vals)
return super().create(vals_list)
def write(self, vals):
"""Change language if a country is written through code and no
one is modified as well.
"""
self._adjust_lang_by_country(vals)
return super().write(vals)
| 33.35
| 1,334
|
631
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Komit <https://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Email Format Checker",
"version": "15.0.1.0.1",
"summary": "Validate email address field",
"author": "Komit, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"category": "Tools",
"depends": ["base_setup"],
"installable": True,
"application": False,
"license": "AGPL-3",
"external_dependencies": {"python": ["email-validator"]},
"data": ["views/base_config_view.xml"],
"demo": ["demo/res_company_demo.xml"],
}
| 35.055556
| 631
|
6,159
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Komit <https://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from unittest.mock import patch
from odoo.exceptions import UserError, ValidationError
from odoo.tests.common import TransactionCase
from odoo.tools.misc import mute_logger
class TestPartnerEmailCheck(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.test_partner = cls.env["res.partner"].create({"name": "test"})
cls.env.company.partner_email_check_syntax = True
cls.env.company.partner_email_check_filter_duplicates = False
cls.env.company.partner_email_check_check_deliverability = False
def test_bad_email(self):
"""Test rejection of bad emails."""
with self.assertRaises(ValidationError):
self.test_partner.email = "bad@email@domain..com"
def test_good_email(self):
"""Test acceptance of good"""
self.test_partner.email = "goodemail@domain.com"
self.assertTrue(self.test_partner.email)
def test_bad_emails(self):
"""Test rejection of bad emails."""
with self.assertRaises(ValidationError):
self.test_partner.email = "good@domain.com,bad@email@domain..com"
def test_good_emails(self):
"""Test acceptance of good"""
self.test_partner.email = "goodemail@domain.com,goodemail2@domain.com"
self.assertTrue(self.test_partner.email)
def test_email_domain_normalization(self):
"""Test normalization of email domain names, including punycode."""
self.test_partner.write({"email": "goodemail@xn--xamPle-9ua.com"})
self.assertEqual(self.test_partner.email, "goodemail@éxample.com")
def test_multi_email_domain_normalization(self):
"""Test normalization of email domain names of multiple addresses."""
self.test_partner.write(
{"email": "goodemail@doMAIN.com,othergood@xn--xample-9ua.com"}
)
self.assertEqual(
self.test_partner.email, "goodemail@domain.com,othergood@éxample.com"
)
def test_email_local_normalization(self):
"""Test normalization of the local part of email addresses."""
self.test_partner.write({"email": "Me@mail.org"})
# .lower() is locale-dependent, so don't hardcode the result
self.assertEqual(self.test_partner.email, "Me".lower() + "@mail.org")
def test_multi_email_local_normalization(self):
"""Test normalization of the local part of multiple addresses."""
self.test_partner.write({"email": "You@mAiL.net,mE@mail.com"})
self.assertEqual(
self.test_partner.email,
"You".lower() + "@mail.net," + "mE".lower() + "@mail.com",
)
def disallow_duplicates(self):
self.env.company.partner_email_check_filter_duplicates = True
def test_duplicate_addresses_disallowed(self):
self.disallow_duplicates()
self.test_partner.write({"email": "email@domain.tld"})
with self.assertRaises(UserError):
self.env["res.partner"].create(
{"name": "alsotest", "email": "email@domain.tld"}
)
def test_duplicate_after_normalization_addresses_disallowed(self):
self.disallow_duplicates()
self.env["res.partner"].create(
{"name": "alsotest", "email": "email@doMAIN.tld"}
)
with self.assertRaises(UserError):
self.test_partner.email = "email@domain.tld"
def test_multiple_addresses_disallowed_when_duplicates_filtered(self):
self.disallow_duplicates()
with self.assertRaises(UserError):
self.test_partner.email = "foo@bar.org,email@domain.tld"
def test_duplicate_addresses_disallowed_copy_partner(self):
self.disallow_duplicates()
self.test_partner.write({"email": "email@domain.tld"})
partner_copy = self.test_partner.copy()
self.assertFalse(partner_copy.email)
def test_duplicate_addresses_allowed_by_default(self):
self.env["res.partner"].create(
{"name": "alsotest", "email": "email@domain.tld"}
)
self.test_partner.email = "email@domain.tld"
def check_deliverability(self):
self.env.company.partner_email_check_check_deliverability = True
def test_deliverable_addresses_allowed(self):
self.check_deliverability()
# We only need a resolving domain, not a real user
self.test_partner.email = "gooddomain-icraglusrk@gmail.com"
self.assertTrue(self.test_partner.email)
def test_nondeliverable_addresses_not_allowed(self):
self.check_deliverability()
with self.assertRaises(ValidationError):
# This domain may resolve by mistake on certain network setups
# At least until a new version of email-validator is released
# See https://github.com/JoshData/python-email-validator/pull/30
self.test_partner.email = "cezrik@acoa.nrdkt"
@mute_logger("odoo.addons.partner_email_check.models.res_partner")
def test_lacking_dependency_does_not_halt_execution(self):
with patch(
"odoo.addons.partner_email_check.models.res_partner." "validate_email", None
):
self.test_partner.email = "notatallvalid@@domain"
@mute_logger("odoo.addons.partner_email_check.models.res_partner")
def test_lacking_dependency_keeps_uniqueness_constraint_working(self):
self.disallow_duplicates()
with patch(
"odoo.addons.partner_email_check.models.res_partner." "validate_email", None
):
self.env["res.partner"].create(
{"name": "alsotest", "email": "email@domain.tld"}
)
with self.assertRaises(UserError):
self.test_partner.email = "email@domain.tld"
def test_invalid_email_addresses_allowed(self):
self.env.company.partner_email_check_syntax = False
self.test_partner.email = "bad@email@domain..com"
self.assertTrue(self.test_partner.email)
| 42.756944
| 6,157
|
788
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ACSONE SA/NV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
partner_email_check_syntax = fields.Boolean(
string="Check syntax of email addresses",
help="Don't allow email addresses with wrong syntax",
default=True,
)
partner_email_check_filter_duplicates = fields.Boolean(
string="Filter duplicate partner email addresses",
help="Don't allow multiple partners to have the same email address.",
)
partner_email_check_check_deliverability = fields.Boolean(
string="Check deliverability of email addresses",
help="Don't allow email addresses with providers that don't exist",
)
| 34.26087
| 788
|
867
|
py
|
PYTHON
|
15.0
|
from odoo import api, fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
partner_email_check_syntax = fields.Boolean(
related="company_id.partner_email_check_syntax",
readonly=False,
)
partner_email_check_filter_duplicates = fields.Boolean(
related="company_id.partner_email_check_filter_duplicates",
readonly=False,
)
partner_email_check_check_deliverability = fields.Boolean(
related="company_id.partner_email_check_check_deliverability",
readonly=False,
)
@api.onchange(
"partner_email_check_syntax", "partner_email_check_check_deliverability"
)
def _onchange_partner_email_check_check_deliverability(self):
if self.partner_email_check_check_deliverability:
self.partner_email_check_syntax = True
| 32.111111
| 867
|
3,330
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Komit <https://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import _, api, models
from odoo.exceptions import UserError, ValidationError
_logger = logging.getLogger(__name__)
try:
from email_validator import (
EmailSyntaxError,
EmailUndeliverableError,
validate_email,
)
except ImportError:
_logger.debug('Cannot import "email_validator".')
validate_email = None
class ResPartner(models.Model):
_inherit = "res.partner"
def copy_data(self, default=None):
res = super(ResPartner, self).copy_data(default=default)
if self._should_filter_duplicates():
for copy_vals in res:
copy_vals.pop("email", None)
return res
@api.model
def email_check(self, emails):
return ",".join(
self._normalize_email(email.strip())
for email in emails.split(",")
if email.strip()
)
@api.constrains("email")
def _check_email_unique(self):
if self._should_filter_duplicates():
for rec in self.filtered("email"):
if "," in rec.email:
raise UserError(
_(
"Field contains multiple email addresses. This is "
"not supported when duplicate email addresses are "
"not allowed."
)
)
if self.search_count([("email", "=", rec.email), ("id", "!=", rec.id)]):
raise UserError(
_("Email '%s' is already in use.") % rec.email.strip()
)
def _normalize_email(self, email):
if not self._should_check_syntax():
return email
if validate_email is None:
_logger.warning(
"Can not validate email, "
'python dependency required "email_validator"'
)
return email
try:
result = validate_email(
email,
check_deliverability=self._should_check_deliverability(),
)
except EmailSyntaxError:
raise ValidationError(
_("%s is an invalid email") % email.strip()
) from EmailSyntaxError
except EmailUndeliverableError:
raise ValidationError(
_("Cannot deliver to email address %s") % email.strip()
) from EmailUndeliverableError
return result["local"].lower() + "@" + result["domain_i18n"]
def _should_check_syntax(self):
return self.env.company.partner_email_check_syntax
def _should_filter_duplicates(self):
return self.env.company.partner_email_check_filter_duplicates
def _should_check_deliverability(self):
return self.env.company.partner_email_check_check_deliverability
@api.model
def create(self, vals):
if vals.get("email"):
vals["email"] = self.email_check(vals["email"])
return super(ResPartner, self).create(vals)
def write(self, vals):
if vals.get("email"):
vals["email"] = self.email_check(vals["email"])
return super(ResPartner, self).write(vals)
| 32.970297
| 3,330
|
668
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Antiun Ingenieria S.L. - Antonio Espinosa
# Copyright 2017 Tecnativa - Vicent Cubells
# Copyright 2020 Tecnativa - João Marques
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Partner unique reference",
"summary": "Add an unique constraint to partner ref field",
"version": "15.0.1.0.0",
"category": "Customer Relationship Management",
"website": "https://github.com/OCA/partner-contact",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["base"],
"data": ["views/res_company_view.xml"],
}
| 37.055556
| 667
|
4,681
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Tecnativa - Vicent Cubells
# Copyright 2020 Tecnativa - João Marques
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.exceptions import ValidationError
from odoo.tests import common
class TestResPartnerRefUnique(common.SavepointCase):
@classmethod
def setUpClass(cls):
super(TestResPartnerRefUnique, cls).setUpClass()
cls.partner_obj = cls.env["res.partner"]
cls.company_obj = cls.env["res.company"]
# look for possible already duplicated refs for being resilient
cls.partner_obj.search([("ref", "!=", False)]).write({"ref": False})
cls.company = cls.company_obj.create({"name": "Test company"})
cls.env.user.write(
{"company_id": cls.company.id, "company_ids": cls.company.ids}
)
cls.partner1 = cls.partner_obj.create({"name": "Partner1", "company_id": False})
cls.partner2 = cls.partner_obj.create({"name": "Partner2", "company_id": False})
def test_check_ref_company(self):
(self.partner1 + self.partner2).write({"company_id": self.company.id})
# Test that we can create/modify partners with same ref in current situation
self.partner1.ref = "same_ref"
partner = self.partner_obj.create({"name": "other", "ref": "same_ref"})
# Try to activate restriction
with self.assertRaises(ValidationError):
self.company.partner_ref_unique = "all"
# Let the situation without duplicate refs and apply global condition
partner.unlink()
self.company.partner_ref_unique = "all"
with self.assertRaises(ValidationError):
self.partner2.ref = "same_ref"
with self.assertRaises(ValidationError):
self.partner_obj.create(
{"name": "other", "ref": "same_ref", "company_id": self.company.id}
)
# This one should also raise the constraint as the no-company contact
# collapses with the company specific contact
with self.assertRaises(ValidationError):
self.partner_obj.create(
{"name": "other", "ref": "same_ref", "company_id": False}
)
def test_partner1_wo_company_new_partner_w_company(self):
self.company.partner_ref_unique = "all"
self.partner1.write({"company_id": False, "ref": "same_ref"})
with self.assertRaises(ValidationError):
self.partner_obj.create(
{"name": "other", "ref": "same_ref", "company_id": self.company.id}
)
self.partner1.unlink()
def test_partner1_w_company_new_partner_wo_company(self):
self.company.partner_ref_unique = "all"
self.partner1.ref = "same_ref"
with self.assertRaises(ValidationError):
self.partner_obj.create(
{"name": "other", "ref": "same_ref", "company_id": False}
)
self.partner1.unlink()
def test_check_ref_companies(self):
self.company.partner_ref_unique = (
"none" # Ensure no constraint is applied at beginning
)
self.partner1.is_company = True
self.partner2.is_company = True
# Test that we can create/modify company partners
# with same ref in current situation
self.partner1.ref = "same_ref"
partner3 = self.partner_obj.create(
{"name": "Company3", "ref": "same_ref", "is_company": True}
)
# Try to activate restriction
with self.assertRaises(ValidationError):
self.company.partner_ref_unique = "companies"
# Let the situation without duplicate refs and apply global condition
partner3.unlink()
self.company.partner_ref_unique = "companies"
with self.assertRaises(ValidationError):
self.partner2.ref = "same_ref"
with self.assertRaises(ValidationError):
self.partner_obj.create(
{"is_company": True, "name": "other", "ref": "same_ref"}
)
# Here there shouldn't be any problem
self.partner_obj.create(
{"is_company": False, "name": "other", "ref": "same_ref"}
)
def test_merge(self):
self.company.partner_ref_unique = "all"
self.partner1.ref = "same_ref"
wizard = self.env["base.partner.merge.automatic.wizard"].create(
{
"partner_ids": [(4, self.partner1.id), (4, self.partner2.id)],
"dst_partner_id": self.partner2.id,
"state": "selection",
}
)
# this shouldn't raise error
wizard.action_merge()
| 43.738318
| 4,680
|
1,003
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Antonio Espinosa
# Copyright 2020 Tecnativa - João Marques
# 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"
partner_ref_unique = fields.Selection(
selection=[
("none", "None"),
("companies", "Only companies"),
("all", "All partners"),
],
string="Unique partner reference for",
default="none",
)
def write(self, vals):
"""Launch manually the constraint check in partners as current ORM
doesn't trigger the constraint on related fields.
"""
res = super().write(vals)
if "partner_ref_unique" in vals:
partners = (
self.env["res.partner"]
.with_context(active_test=False)
.search([("company_id", "in", [False] + self.ids)])
)
partners._check_ref()
return res
| 30.363636
| 1,002
|
1,319
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Antonio Espinosa
# Copyright 2020 Tecnativa - João Marques
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, api, models
from odoo.exceptions import ValidationError
class ResPartner(models.Model):
_inherit = "res.partner"
@api.constrains("ref", "is_company", "company_id")
def _check_ref(self):
for partner in self.filtered("ref"):
# If the company is not defined in the partner, take current user company
company = partner.company_id or self.env.company
mode = company.partner_ref_unique
if mode == "all" or (mode == "companies" and partner.is_company):
domain = [
("id", "!=", partner.id),
("ref", "=", partner.ref),
]
if mode == "companies":
domain.append(("is_company", "=", True))
other = self.search(domain)
# Don't raise when coming from contact merge wizard or no duplicates
if other and not self.env.context.get("partner_ref_unique_merging"):
raise ValidationError(
_("This reference is equal to partner '%s'")
% other[0].display_name
)
| 42.516129
| 1,318
|
625
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
def action_merge(self):
"""Inject context for avoiding the duplicate reference constraint that
happens when merging one contact with reference in another without
reference.
"""
return super(
BasePartnerMergeAutomaticWizard,
self.with_context(partner_ref_unique_merging=True),
).action_merge()
| 34.722222
| 625
|
639
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Pedro M. Baeza <pedro.baeza@tecnativa.com>
# Copyright 2017 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# Copyright 2020 Pesol - Pedro Evaristo Gonzalez Sanchez <pedro.gonzalez@pesol.es>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Manage language in contacts",
"version": "15.0.1.0.0",
"category": "Sales",
"license": "AGPL-3",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/partner-contact",
"depends": ["base"],
"data": ["views/res_partner_view.xml"],
"installable": True,
}
| 39.9375
| 639
|
1,405
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Pedro M. Baeza <pedro.baeza@tecnativa.com>
# Copyright 2017 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# Copyright 2018 Tecnativa - Cristina Martín
# Copyright 2021 Pesol - Pedro Evaristo Gonzalez Sanchez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
class TestPartnerContactLang(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestPartnerContactLang, cls).setUpClass()
cls.ResPartner = cls.env["res.partner"]
cls.partner = cls.ResPartner.create({"name": "Partner test", "lang": "en_US"})
cls.contact = cls.ResPartner.create(
{"name": "Contact test", "lang": False, "parent_id": cls.partner.id}
)
def test_onchange_parent_id(self):
self.contact.parent_id = False
res = self.contact.onchange_parent_id()
self.assertIsNone(res)
self.contact.parent_id = self.partner
res = self.contact.onchange_parent_id()
self.assertEqual(self.contact.lang, "en_US")
def test_write_parent_lang(self):
"""First empty the field for filling it again afterwards to see if
the contact gets the same value.
"""
self.contact.lang = False
self.partner.lang = False
self.partner.lang = "en_US"
self.assertEqual(self.contact.lang, "en_US")
| 40.114286
| 1,404
|
1,326
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2020 Tecnativa - Pedro M. Baeza
# Copyright 2017 Tecnativa - Vicent Cubells
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class ResPartner(models.Model):
_inherit = "res.partner"
def write(self, vals):
"""Propagate a language change in the partner to the child contacts."""
res = super(ResPartner, self).write(vals)
if vals.get("lang"):
childs = self.search([("id", "child_of", self.ids), ("lang", "=", False)])
if childs:
childs.write({"lang": vals["lang"]})
return res
@api.onchange("parent_id")
def onchange_parent_id(self):
"""Change language if the parent company changes and there's no
language defined yet.
A special case is made for virtual records, where default lang value
is assigned at startup, so we always overwrite language in that case.
"""
res = super(ResPartner, self).onchange_parent_id()
if (
self.parent_id.lang
and (
not self.lang
or (isinstance(self.id, models.NewId) and not self._origin)
)
and self.parent_id.lang != self.lang
):
self.lang = self.parent_id.lang
return res
| 34.894737
| 1,326
|
578
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Pedro M. Baeza
# Copyright 2017 Tecnativa - Vicent Cubells
# Copyright 2019 Tecnativa - Victor M.M Torres
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Exclude records from the deduplication",
"version": "15.0.1.0.0",
"category": "Tools",
"website": "https://github.com/OCA/partner-contact",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": ["partner_deduplicate_acl"],
"data": ["wizards/partner_merge_view.xml"],
}
| 36.125
| 578
|
3,111
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
from odoo.tools.safe_eval import safe_eval
class TestDeduplicateFilter(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_1.copy()
self.partner_2 = self.env["res.partner"].create(
{
"name": "Partner 2",
"email": "partner2@example.org",
"is_company": False,
"parent_id": self.partner_1.id,
}
)
self.partner_2.copy()
self.partner_3 = self.env["res.partner"].create(
{
"name": "Partner 3",
"email": "partner3@example.org",
"is_company": False,
"parent_id": False,
}
)
self.partner_3.copy()
self.wizard = self.env["base.partner.merge.automatic.wizard"].create(
{"group_by_email": True}
)
def test_deduplicate_exclude_is_company(self):
self.wizard.exclude_is_company = True
self.wizard.action_start_manual_process()
matched_founds = 0
for line in self.wizard.line_ids:
match_ids = safe_eval(line.aggr_ids)
if self.partner_1.id in match_ids:
self.assertTrue(False, "Partner with is company not excluded")
if self.partner_2.id in match_ids:
matched_founds += 1
if self.partner_3.id in match_ids:
matched_founds += 1
self.assertEqual(matched_founds, 2)
def test_deduplicate_exclude_not_parent(self):
self.wizard.exclude_not_parent = True
self.wizard.action_start_manual_process()
matched_founds = 0
for line in self.wizard.line_ids:
match_ids = safe_eval(line.aggr_ids)
if self.partner_1.id in match_ids:
self.assertTrue(False, "Partner without parent not excluded")
if self.partner_3.id in match_ids:
self.assertTrue(False, "Partner without parent not excluded")
if self.partner_2.id in match_ids:
matched_founds += 1
self.assertEqual(matched_founds, 1)
def test_deduplicate_exclude_parent(self):
self.wizard.exclude_parent = True
self.wizard.action_start_manual_process()
matched_founds = 0
for line in self.wizard.line_ids:
match_ids = safe_eval(line.aggr_ids)
if self.partner_2.id in match_ids:
self.assertTrue(False, "Partner with parent not excluded")
if self.partner_1.id in match_ids:
matched_founds += 1
if self.partner_3.id in match_ids:
matched_founds += 1
self.assertEqual(matched_founds, 2)
| 37.939024
| 3,111
|
1,347
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
exclude_is_company = fields.Boolean("'Is a company?' field selected")
exclude_not_parent = fields.Boolean("Parent company not set")
exclude_parent = fields.Boolean("Parent company set (Contacts)")
def _process_query(self, query):
if any([self.exclude_is_company, self.exclude_not_parent, self.exclude_parent]):
filters = []
if self.exclude_is_company:
filters.append("is_company = False")
if self.exclude_not_parent:
filters.append("parent_id IS NOT NULL")
if self.exclude_parent:
filters.append("parent_id IS NULL")
index_where = query.find("WHERE")
index_group_by = query.find("GROUP BY")
subquery = "%s" % " AND ".join(filters)
if index_where > 0:
subquery = "AND (%s) " % subquery
else: # pragma: no cover
subquery = "WHERE %s " % subquery
query = query[:index_group_by] + subquery + query[index_group_by:]
return super()._process_query(query)
| 43.451613
| 1,347
|
618
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Jairo Llopis
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Partner contact access link",
"summary": "Allow to visit the full contact form from a company",
"version": "15.0.1.1.0",
"development_status": "Production/Stable",
"category": "Tools",
"website": "https://github.com/OCA/partner-contact",
"author": "Tecnativa, Odoo Community Association (OCA)",
"maintainers": ["Yajo"],
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["base"],
"data": ["views/res_partner_views.xml"],
}
| 36.352941
| 618
|
1,022
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Ecosoft Co., Ltd (http://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import TransactionCase
class TestPartnerContactAccessLink(TransactionCase):
def setUp(self):
super().setUp()
self.partner_model = self.env["res.partner"]
self.company = self.partner_model.create(
{"name": "Test Company", "company_type": "company"}
)
self.contact = self.partner_model.create(
{"name": "Test Contact", "type": "contact", "parent_id": self.company.id}
)
def test_partner_contact_access_link(self):
res = self.contact.open_child_form()
self.assertEqual(res["type"], "ir.actions.act_window")
self.assertEqual(res["res_model"], "res.partner")
self.assertEqual(res["res_id"], self.contact.id)
self.assertEqual(res["view_mode"], "form")
self.assertEqual(res["view_type"], "form")
self.assertEqual(res["target"], "current")
| 40.88
| 1,022
|
541
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Jairo Llopis
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class ResPartner(models.Model):
_inherit = "res.partner"
def open_child_form(self):
"""Open child contact form from the parent partner form view"""
return {
"type": "ir.actions.act_window",
"res_model": "res.partner",
"res_id": self.id,
"view_mode": "form",
"view_type": "form",
"target": "current",
}
| 28.473684
| 541
|
437
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 initOS GmbH
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Translate Country States",
"version": "15.0.1.0.0",
"depends": ["base"],
"website": "https://github.com/OCA/partner-contact",
"summary": "Translate Country States",
"author": "initOS GmbH, Odoo Community Association (OCA)",
"category": "Localisation",
"license": "AGPL-3",
"installable": True,
}
| 31.214286
| 437
|
237
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 initOS GmbH
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class CountryState(models.Model):
_inherit = "res.country.state"
name = fields.Char(translate=True)
| 23.7
| 237
|
823
|
py
|
PYTHON
|
15.0
|
# Copyright 2014 Pedro M. Baeza <pedro.baeza@tecnativa.com>
# Copyright 2015 Antonio Espinosa <antonioea@antiun.com>
# Copyright 2015 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2017 David Vidal <david.vidal@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Partner Job Position",
"summary": "Categorize job positions for contacts",
"version": "15.0.1.0.1",
"category": "Customer Relationship Management",
"website": "https://github.com/OCA/partner-contact",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": ["contacts"],
"data": [
"security/ir.model.access.csv",
"views/res_partner_job_position_view.xml",
"views/res_partner_view.xml",
],
}
| 37.409091
| 823
|
619
|
py
|
PYTHON
|
15.0
|
# Copyright 2014 Pedro M. Baeza <pedro.baeza@tecnativa.com>
# Copyright 2015 Antonio Espinosa <antonioea@antiun.com>
# Copyright 2015 Jairo Llopis <jairo.llopis@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
job_position_id = fields.Many2one(
"res.partner.job_position", "Categorized job position"
)
class ResPartnerJobPosition(models.Model):
_name = "res.partner.job_position"
_description = "Job position"
name = fields.Char(required=True, translate=True)
| 29.47619
| 619
|
1,519
|
py
|
PYTHON
|
15.0
|
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name": "Environment Management System",
"version": "15.0.1.0.0",
"author": "Savoir-faire Linux, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/management-system",
"license": "AGPL-3",
"category": "Management System",
"depends": [
"mgmtsystem_audit",
"mgmtsystem_review",
"document_page_environment_manual",
"document_page_environmental_aspect",
],
"data": ["data/environment.xml"],
"demo": [],
"installable": True,
"application": True,
}
| 41.054054
| 1,519
|
514
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Management System - Survey",
"version": "15.0.1.0.0",
"author": "Savoir-faire Linux,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/management-system",
"license": "AGPL-3",
"category": "Management System",
"depends": ["mgmtsystem", "survey"],
"data": ["views/survey_survey.xml"],
"installable": True,
}
| 36.714286
| 514
|
949
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Management System - Audit",
"version": "15.0.1.0.0",
"author": "Savoir-faire Linux, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/management-system",
"license": "AGPL-3",
"category": "Management System",
"depends": ["mgmtsystem_nonconformity", "base_automation"],
"data": [
"security/ir.model.access.csv",
"security/mgmtsystem_audit_security.xml",
"data/audit_sequence.xml",
"data/audit_automated_actions.xml",
"views/mgmtsystem_audit.xml",
"views/res_users.xml",
"report/audit.xml",
"report/verification.xml",
"report/report.xml",
"report/mgmtsystem_audit_pivot.xml",
"wizard/copy_verification_lines.xml",
],
"demo": ["demo/demo_audit.xml"],
}
| 37.96
| 949
|
1,390
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests import common
class TestModelAudit(common.TransactionCase):
def test_get_action_url(self):
"""Test if action url start with http."""
record = self.env.ref("mgmtsystem_audit.mgmtsystem_audit_demo")
ret = record.get_action_url()
self.assertEqual(isinstance(ret, str), True)
self.assertEqual(ret.startswith("http"), True)
def test_button_close(self):
"""Test if button close change audit state to close."""
record = self.env.ref("mgmtsystem_audit.mgmtsystem_audit_demo")
record.state = "open"
self.assertEqual(record.state, "open")
record.button_close()
self.assertEqual(record.state, "done")
def test_get_lines_by_procedure(self):
line_id = self.env["mgmtsystem.verification.line"].create(
{
"name": "test",
"procedure_id": self.env.ref("document_page.demo_page1").id,
}
)
line_id2 = self.env["mgmtsystem.verification.line"].create({"name": "test2"})
record = self.env.ref("mgmtsystem_audit.mgmtsystem_audit_demo")
record.line_ids = [line_id.id, line_id2.id]
q = record.get_lines_by_procedure()
self.assertTrue(q)
| 36.578947
| 1,390
|
1,071
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests import common
class TestModelCopyVerificationLines(common.TransactionCase):
"""Test wizard's method."""
def test_copyVerificationLines(self):
line_id = self.env["mgmtsystem.verification.line"].create(
{
"name": "What",
"procedure_id": self.env.ref("document_page.demo_page1").id,
}
)
src_record = self.env.ref("mgmtsystem_audit.mgmtsystem_audit_demo")
src_record.line_ids = [line_id.id]
dest_record = self.env.ref("mgmtsystem_audit.mgmtsystem_audit_demo2")
copy_record = self.env["copy.verification.lines"].create(
{"audit_src": src_record.id}
)
copy_record = copy_record.with_context(
active_id=dest_record.id, active_model="mgmtsystem.audit"
)
copy_record.copyVerificationLines()
self.assertGreater(len(dest_record.line_ids), 0)
| 35.7
| 1,071
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.