<commit_before># -*- coding: utf-8 -*-
# Copyright (C) 2012 - TODAY  <NAME> - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

import re

from openerp import models, fields, api
from openerp.addons.l10n_br_base.tools import fiscal
from openerp.exceptions import ValidationError
from openerp.tools.translate import _


class CrmLead(models.Model):
    """ CRM Lead Case """
    _inherit = "crm.lead"

    legal_name = fields.Char(
        u'Razão Social', size=128,
        help="nome utilizado em documentos fiscais")
    cnpj = fields.Char('CNPJ', size=18)
    inscr_est = fields.Char('Inscr. Estadual/RG', size=16)
    inscr_mun = fields.Char('Inscr. Municipal', size=18)
    suframa = fields.Char('Suframa', size=18)
    l10n_br_city_id = fields.Many2one(
        'l10n_br_base.city', 'Municipio',
        domain="[('state_id','=',state_id)]")
    district = fields.Char('Bairro', size=32)
    number = fields.Char(u'Número', size=10)
    name_surname = fields.Char(u'Nome e sobrenome', size=128,
                               help="Nome utilizado em documentos fiscais")
    cpf = fields.Char('CPF', size=18)
    rg = fields.Char('RG', size=16)

    @api.multi
    @api.constrains('cnpj')
    def _check_cnpj(self):
        for record in self:
            country_code = record.country_id.code or ''
            if record.cnpj and country_code.upper() == 'BR':
                cnpj = re.sub('[^0-9]', '', record.cnpj)
                if not fiscal.validate_cnpj(cnpj):
                    raise ValidationError(_(u'CNPJ inválido!'))
            return True

    @api.multi
    @api.constrains('cpf')
    def _check_cpf(self):
        for record in self:
            country_code = record.country_id.code or ''
            if record.cpf and country_code.upper() == 'BR':
                cpf = re.sub('[^0-9]', '', record.cpf)
                if not fiscal.validate_cpf(cpf):
                    raise ValidationError(_(u'CPF inválido!'))
            return True

    @api.multi
    @api.constrains('inscr_est')
    def _check_ie(self):
        """Checks if company register number in field insc_est is valid,
        this method call others methods because this validation is State wise

        :Return: True or False.
        """
        for record in self:
            result = True
            if record.inscr_est != 'ISENTO' or record.partner_name:
                state_code = record.state_id.code or ''
                uf = state_code.lower()
                try:
                    mod = __import__(
                        'openerp.addons.l10n_br_base.tools.fiscal',
                        globals(), locals(), 'fiscal')
                    validate = getattr(mod, 'validate_ie_%s' % uf)
                    result = validate(record.inscr_est)
                except AttributeError:
                    result = fiscal.validate_ie_param(uf, record.inscr_est)
            if not result:
                raise ValidationError(u"Inscrição Estadual Invalida!")

    @api.onchange('cnpj', 'country_id')
    def _onchange_cnpj(self):
        cnpj = None
        country_code = self.country_id.code or ''
        if self.cnpj and country_code.upper() == 'BR':
            val = re.sub('[^0-9]', '', self.cnpj)
            if len(val) == 14:
                cnpj = "%s.%s.%s/%s-%s" % (
                    val[0:2], val[2:5], val[5:8], val[8:12], val[12:14])
            self.cnpj = cnpj

    @api.onchange('cpf', 'country_id')<commit_msg>[FIX][REF] Fix and refactoring IE validation.<commit_after># -*- coding: utf-8 -*-
# Copyright (C) 2012 - TODAY  <NAME> - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

import re

from openerp import models, fields, api
from openerp.addons.l10n_br_base.tools import fiscal
from openerp.exceptions import ValidationError
from openerp.tools.translate import _


class CrmLead(models.Model):
    """ CRM Lead Case """
    _inherit = "crm.lead"

    legal_name = fields.Char(
        u'Razão Social', size=128,
        help="nome utilizado em documentos fiscais")
    cnpj = fields.Char('CNPJ', size=18)
    inscr_est = fields.Char('Inscr. Estadual/RG', size=16)
    inscr_mun = fields.Char('Inscr. Municipal', size=18)
    suframa = fields.Char('Suframa', size=18)
    l10n_br_city_id = fields.Many2one(
        'l10n_br_base.city', 'Municipio',
        domain="[('state_id','=',state_id)]")
    district = fields.Char('Bairro', size=32)
    number = fields.Char(u'Número', size=10)
    name_surname = fields.Char(u'Nome e sobrenome', size=128,
                               help="Nome utilizado em documentos fiscais")
    cpf = fields.Char('CPF', size=18)
    rg = fields.Char('RG', size=16)

    @api.multi
    @api.constrains('cnpj')
    def _check_cnpj(self):
        for record in self:
            country_code = record.country_id.code or ''
            if record.cnpj and country_code.upper() == 'BR':
                cnpj = re.sub('[^0-9]', '', record.cnpj)
                if not fiscal.validate_cnpj(cnpj):
                    raise ValidationError(_(u'CNPJ inválido!'))
            return True

    @api.multi
    @api.constrains('cpf')
    def _check_cpf(self):
        for record in self:
            country_code = record.country_id.code or ''
            if record.cpf and country_code.upper() == 'BR':
                cpf = re.sub('[^0-9]', '', record.cpf)
                if not fiscal.validate_cpf(cpf):
                    raise ValidationError(_(u'CPF inválido!'))
            return True

    @api.multi
    @api.constrains('inscr_est')
    def _check_ie(self):
        """Checks if company register number in field insc_est is valid,
        this method call others methods because this validation is State wise

        :Return: True or False.
        """
        for record in self:
            result = True
            if record.inscr_est and record.cnpj and record.state_id:
                state_code = record.state_id.code or ''
                uf = state_code.lower()
                result = fiscal.validate_ie(uf, record.inscr_est)
            if not result:
                raise ValidationError(u"Inscrição Estadual Invalida!")

    @api.onchange('cnpj', 'country_id')
    def _onchange_cnpj(self):
        cnpj = None
        country_code = self.country_id.code or ''
        if self.cnpj and country_code.upper() == 'BR':
            val = re.sub('[^0-9]', '', self.cnpj)
            if len(val) == 14:
                cnpj = "%s.%s.%s/%s-%s" % (
                    val[0:2], val[2:5], val[5:8], val[8:12], val[12:14])
            self.cnpj = cnpj

    @api.onchange('cpf', 'country_id')
{'fraction_non_alphanumeric': 0.1310584327344104, 'fraction_numerical': 0.01781669938094519, 'mean_word_length': 2.1393364928909953, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2337700', 'n_tokens_mistral': 2298, 'n_tokens_neox': 2162, 'n_words': 480}