Files
odoo_source/addons/phone_validation/tools/phone_validation.py
T
Thibault Delavallée 7e8a02cd6e [IMP] phone_validation: add blacklist mechanism
PURPOSE

SMS are a powerful marketing tool. For instance it is perfect to announce a
sale or to communicate a coupon code, to welcome a new customer in a fidelity
program, ...

Purpose of this task is to integrate SMS sending in batch in mass mailing. It
will use same mailing objects but sending SMS instead of emails. Some metrics
and flows will have to be slightly updated at the same time.

SPECIFICATIONS

Purpose of this commit is to add a blacklist mechanism for phone numbers
used to send SMS like what already exists for email addresses when sending
emails.

Define a new phone.blacklist model, holding a number and the state of the
blacklist (active field), as well as tools methods to access it. Make it
as private as possible, accessing it in sudo once access are granted.

Also clean phone validation tools: lessen number of tool functions and update
caller to simplify code readability. Some fixes are also included in this
commit, notably blank spaces cleaning in phone numbers.

Improve phone.validation.mixin to add a tool method computing a sanitized
number, in addition to formatting it to national / international.

Define a new mail.thread.phone mixin computing the blacklist status of a
record. This mixin

  * inherit from phone.validation.mixin in order to have access to some
    base phone number parsing capabilities;
  * computes a sanitized phone number based on ´´_phone_get_number_fields´´.
    It takes first sanitized value, trying each field returned by the
    method. That means one sanitized phone number is available per record
    even if several fields are available;
  * compute blacklist state of records. It is based on phone.blacklist
    model and give an easy-to-use field and API to manipulate blacklisted
    records;
  * give some API methods :

    * ``_phone_set_blacklisted``: set recordset as blacklisted;
    * ``_phone_reset_blacklisted``: reactivate recordset (even if not blacklisted
        this method can be called safely);

Put menus in technical in order to have access to it. Add a Phone / SMS
menu below "Email" and use it to store SMS / Phone actions.

Finally prepare tests addition by performing some light cleaning while adding
blacklist tests. Purpose is to ease future tests related to SMS.

LINKS

Task 1997464
PR #34424
Original SMS addition: Task 1922163 (4287481)
2019-08-12 12:00:22 +00:00

118 lines
4.9 KiB
Python

# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _
from odoo.exceptions import UserError
import logging
_logger = logging.getLogger(__name__)
_phonenumbers_lib_warning = False
try:
import phonenumbers
def phone_parse(number, country_code):
try:
phone_nbr = phonenumbers.parse(number, region=country_code, keep_raw_input=True)
except phonenumbers.phonenumberutil.NumberParseException as e:
raise UserError(_('Unable to parse %s: %s') % (number, str(e)))
if not phonenumbers.is_possible_number(phone_nbr):
raise UserError(_('Impossible number %s: probably invalid number of digits') % number)
if not phonenumbers.is_valid_number(phone_nbr):
raise UserError(_('Invalid number %s: probably incorrect prefix') % number)
return phone_nbr
def phone_format(number, country_code, country_phone_code, force_format='INTERNATIONAL', raise_exception=True):
""" Format the given phone number according to the localisation and international options.
:param number: number to convert
:param country_code: the ISO country code in two chars
:type country_code: str
:param country_phone_code: country dial in codes, defined by the ITU-T (Ex: 32 for Belgium)
:type country_phone_code: int
:param force_format: stringified version of format globals (see
https://github.com/daviddrysdale/python-phonenumbers/blob/dev/python/phonenumbers/phonenumberutil.py)
'E164' = 0
'INTERNATIONAL' = 1
'NATIONAL' = 2
'RFC3966' = 3
:type force_format: str
:rtype: str
"""
try:
phone_nbr = phone_parse(number, country_code)
except (phonenumbers.phonenumberutil.NumberParseException, UserError) as e:
if raise_exception:
raise
else:
_logger.warning(_('Unable to format %s:\n%s'), number, e)
return number
if force_format == 'E164':
phone_fmt = phonenumbers.PhoneNumberFormat.E164
elif force_format == 'RFC3966':
phone_fmt = phonenumbers.PhoneNumberFormat.RFC3966
elif force_format == 'INTERNATIONAL' or phone_nbr.country_code != country_phone_code:
phone_fmt = phonenumbers.PhoneNumberFormat.INTERNATIONAL
else:
phone_fmt = phonenumbers.PhoneNumberFormat.NATIONAL
return phonenumbers.format_number(phone_nbr, phone_fmt)
except ImportError:
def phone_parse(number, country_code):
return False
def phone_format(number, country_code, country_phone_code, force_format='INTERNATIONAL', raise_exception=True):
global _phonenumbers_lib_warning
if not _phonenumbers_lib_warning:
_logger.warning(
"The `phonenumbers` Python module is not installed, contact numbers will not be "
"verified. Please install the `phonenumbers` Python module."
)
_phonenumbers_lib_warning = True
return number
def phone_sanitize_numbers(numbers, country_code, country_phone_code, force_format='E164'):
""" Given a list of numbers, return parsezd and sanitized information
:return dict: {number: {
'sanitized': sanitized and formated number or False (if cannot format)
'code': 'empty' (number was a void string), 'invalid' (error) or False (sanitize ok)
'msg': error message when 'invalid'
}}
"""
if not isinstance(numbers, (list)):
raise NotImplementedError()
result = dict.fromkeys(numbers, False)
for number in numbers:
if not number:
result[number] = {'sanitized': False, 'code': 'empty', 'msg': False}
continue
try:
stripped = number.strip()
sanitized = phone_format(
stripped, country_code, country_phone_code,
force_format=force_format, raise_exception=True)
except Exception as e:
result[number] = {'sanitized': False, 'code': 'invalid', 'msg': str(e)}
else:
result[number] = {'sanitized': sanitized, 'code': False, 'msg': False}
return result
def phone_sanitize_numbers_w_record(numbers, record, country=False, record_country_fname='country_id', force_format='E164'):
if not isinstance(numbers, (list)):
raise NotImplementedError()
if not country:
if record and record_country_fname and hasattr(record, record_country_fname) and record[record_country_fname]:
country = record[record_country_fname]
elif record:
country = record.env.company.country_id
country_code = country.code if country else None
country_phone_code = country.phone_code if country else None
return phone_sanitize_numbers(numbers, country_code, country_phone_code, force_format=force_format)