<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
#    All Rights Reserved
#
#    WARNING: This program as such is intended to be used by professional
#    programmers who take the whole responsibility of assessing all potential
#    consequences resulting from its eventual inadequacies and bugs.
#    End users who are looking for a ready-to-use solution with commercial
#    guarantees and support are strongly advised to contact a Free Software
#    Service Company.
#
#    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/>.
#
##############################################################################

import logging
import phonenumbers as pn

from openerp.osv import orm, fields
from openerp.tools.translate import _

_logger = logging.getLogger(__name__)


"""
Available Types for 'phone.phone':
Fix - Mobile - Fax
"""
PHONE_AVAILABLE_TYPES = [
    ('fix', 'Fix'),
    ('mobile', 'Mobile'),
    ('fax', 'Fax'),
]

phone_available_types = dict(PHONE_AVAILABLE_TYPES)

PREFIX_CODE = 'BE'


class phone_phone(orm.Model):

    _name = 'phone.phone'
    _inherit = ['abstract.ficep.model']
    _description = 'Phone Number'

    def _get_linked_coordinates(self, cr, uid, ids, context=None):
        return self.pool['phone.coordinate'].search(cr, uid, [('phone_id', 'in', ids)], context=context)

    def _check_and_format_number(self, cr, uid, num, context=None):
        """
        ========================
        _check_and_format_number
        ========================
        :param vals: containing at least 'name' that is the phone number
        :type vals: dictionary
        :returns: Number formated into a International Number
                  If number is not starting by '+' then check if it starts by '00'
                  and replace it with '+'. Otherwise set a code value with a PREFIX
        :rtype: char
        :raise: pn.NumberParseException
                * if number is not parsing due to a bad encoded value
        """
        code = False
        if num[:2] == '00':
            num = '%s%s' % (num[:2].replace('00', '+'), num[2:])
        elif not num.startswith('+'):
            code = self.get_default_country_code(cr, uid, context=context)
        try:
            normalized_number = pn.parse(num, code) if code else pn.parse(num)
        except pn.NumberParseException, e:
            errmsg = _('Invalid phone number: %s') % e
            if context.get('install_mode', False):
                # during data migration exception are not allowed
                _logger.warning(errmsg)
                return num
            raise orm.except_orm(_('Error!'), errmsg)
        return pn.format_number(normalized_number, pn.PhoneNumberFormat.INTERNATIONAL)

    _columns = {
        'name': fields.char('Number', size=50, required=True, select=True, track_visibility='onchange'),
        'type': fields.selection(PHONE_AVAILABLE_TYPES, 'Type', required=True, track_visibility='onchange'),

        'phone_coordinate_ids': fields.one2many('phone.coordinate', 'phone_id', 'Phone Coordinates',
                                                domain=[('active', '=', True)]),
        'phone_coordinate_inactive_ids': fields.one2many('phone.coordinate', 'phone_id', 'Phone Coordinates',
                                                domain=[('active', '=', False)]),
    }

    _order = 'name'

    _defaults = {
        'type': PHONE_AVAILABLE_TYPES[0][0],
    }

# constraints

    _unicity_keys = 'name'

# orm methods
<commit_msg>[CHG] allow to load incorrect phone numbers during data migration<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
#    All Rights Reserved
#
#    WARNING: This program as such is intended to be used by professional
#    programmers who take the whole responsibility of assessing all potential
#    consequences resulting from its eventual inadequacies and bugs.
#    End users who are looking for a ready-to-use solution with commercial
#    guarantees and support are strongly advised to contact a Free Software
#    Service Company.
#
#    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/>.
#
##############################################################################

import logging
import phonenumbers as pn

from openerp.osv import orm, fields
from openerp.tools.translate import _

_logger = logging.getLogger(__name__)


"""
Available Types for 'phone.phone':
Fix - Mobile - Fax
"""
PHONE_AVAILABLE_TYPES = [
    ('fix', 'Fix'),
    ('mobile', 'Mobile'),
    ('fax', 'Fax'),
]

phone_available_types = dict(PHONE_AVAILABLE_TYPES)

PREFIX_CODE = 'BE'


class phone_phone(orm.Model):

    _name = 'phone.phone'
    _inherit = ['abstract.ficep.model']
    _description = 'Phone Number'

    def _get_linked_coordinates(self, cr, uid, ids, context=None):
        return self.pool['phone.coordinate'].search(cr, uid, [('phone_id', 'in', ids)], context=context)

    def _check_and_format_number(self, cr, uid, num, context=None):
        """
        ========================
        _check_and_format_number
        ========================
        :param vals: containing at least 'name' that is the phone number
        :type vals: dictionary
        :returns: Number formated into a International Number
                  If number is not starting by '+' then check if it starts by '00'
                  and replace it with '+'. Otherwise set a code value with a PREFIX
        :rtype: char
        :raise: pn.NumberParseException
                * if number is not parsing due to a bad encoded value
        """
        if context.get('install_mode', False) and num[:4] == 'tbc ':
            # during data migration suspect number are not checked
            return num
        code = False
        numero = num
        if num[:2] == '00':
            numero = '%s%s' % (num[:2].replace('00', '+'), num[2:])
        elif not num.startswith('+'):
            code = self.get_default_country_code(cr, uid, context=context)
        try:
            normalized_number = pn.parse(numero, code) if code else pn.parse(numero)
        except pn.NumberParseException, e:
            errmsg = _('Invalid phone number: %s') % e
            if context.get('install_mode', False):
                # during data migration exception are not allowed
                _logger.warning(errmsg)
                return num
            raise orm.except_orm(_('Error!'), errmsg)
        return pn.format_number(normalized_number, pn.PhoneNumberFormat.INTERNATIONAL)

    _columns = {
        'name': fields.char('Number', size=50, required=True, select=True, track_visibility='onchange'),
        'type': fields.selection(PHONE_AVAILABLE_TYPES, 'Type', required=True, track_visibility='onchange'),

        'phone_coordinate_ids': fields.one2many('phone.coordinate', 'phone_id', 'Phone Coordinates',
                                                domain=[('active', '=', True)]),
        'phone_coordinate_inactive_ids': fields.one2many('phone.coordinate', 'phone_id', 'Phone Coordinates',
                                                domain=[('active', '=', False)]),
    }

    _order = 'name'

    _defaults = {
        'type': PHONE_AVAILABLE_TYPES[0][0],
    }

# constraints

    _unicity_keys = 'name'

# orm methods

{'fraction_non_alphanumeric': 0.14559650935813526, 'fraction_numerical': 0.004937421058674934, 'mean_word_length': 2.8797327394209353, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '893036', 'n_tokens_mistral': 2431, 'n_tokens_neox': 2326, 'n_words': 787}