Files
partner-tools/partner_phone_country_validation/models/res_partner.py

55 lines
2.2 KiB
Python

from odoo import api, models, _
from odoo.addons.partner_phone_country_validation.tools.get_country_from_phone_number import (
get_country_from_phone_number,
)
from odoo.exceptions import ValidationError
class Partner(models.Model):
_name = "res.partner"
_inherit = ["res.partner", "phone.validation.mixin"]
@api.constrains("country_id", "phone", "mobile")
def _check_country_id(self):
for partner in self:
if not partner.country_id and (partner.phone or partner.mobile):
raise ValidationError(_("You must set a country for the phone number"))
def _normalize_phone_number(self, number):
"""Convert 00xx format to +xx international format."""
if number and number.startswith("00"):
return "+" + number[2:]
return number
def _set_country_from_phone_number(self, phone_number):
"""Auto-detect and set country from phone number prefix if not already set."""
if not phone_number or self.country_id:
return
country_code = get_country_from_phone_number(phone_number)
if country_code:
country = self.env["res.country"].search(
[("code", "=", country_code)], limit=1
)
if country:
self.country_id = country
@api.onchange("phone", "country_id", "company_id")
def _onchange_phone_validation(self):
# Normalize 00xx → +xx before standard processing
if self.phone:
self.phone = self._normalize_phone_number(self.phone)
# Auto-detect country if not set
self._set_country_from_phone_number(self.phone)
# Let standard module do the formatting
super()._onchange_phone_validation()
@api.onchange("mobile", "country_id", "company_id")
def _onchange_mobile_validation(self):
# Normalize 00xx → +xx before standard processing
if self.mobile:
self.mobile = self._normalize_phone_number(self.mobile)
# Auto-detect country if not set
self._set_country_from_phone_number(self.mobile)
# Let standard module do the formatting
super()._onchange_mobile_validation()