<commit_before># -*- encoding: utf-8 -*-
#################################################################################
#                                                                               #
# Copyright (C) 2009  <NAME> - Akretion, <NAME>                 #
#                                                                               #
#This program is free software: you can redistribute it and/or modify           #
#it under the terms of the GNU 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 General Public License for more details.                                   #
#                                                                               #
#You should have received a copy of the GNU General Public License              #
#along with this program.  If not, see <http://www.gnu.org/licenses/>.          #
#################################################################################

from osv import osv, fields

##############################################################################
# Parceiro Personalizado
##############################################################################
class res_partner(osv.osv):
    _inherit = 'res.partner'
    _columns = {
        'tipo_pessoa': fields.selection([('F', 'Física'), ('J', 'Jurídica')], 'Tipo de pessoa', required=True),
        'cnpj_cpf': fields.char('CNPJ/CPF', size=18),
        'inscr_est': fields.char('Inscr. Estadual', size=16),
        'inscr_mun': fields.char('Inscr. Municipal', size=18),
        'suframa': fields.char('Suframa', size=18),
        'legal_name' : fields.char('Razão Social', size=128, help="nome utilizado em documentos fiscais"),
    }

    _defaults = {
        'tipo_pessoa': lambda *a: 'J',
    }

    def _check_cnpj_cpf(self, cr, uid, ids):
        partner = self.browse(cr, uid, ids)[0]
        if not partner.cnpj_cpf:
            return True

        if partner.tipo_pessoa == 'J':
            return self.validate_cnpj(partner.cnpj_cpf)
        elif partner.tipo_pessoa == 'F':
            return self.validate_cpf(partner.cnpj_cpf)

        return False

    def validate_cnpj(self, cnpj):
        # Limpando o cnpj
        if not cnpj.isdigit():
            import re
            cnpj = re.sub('[^0-9]', '', cnpj)
           
        # verificando o tamano do  cnpj
        if len(cnpj) != 14:
            return False
            
        # Pega apenas os 12 primeiros dígitos do CNPJ e gera os 2 dígitos que faltam
        cnpj= map(int, cnpj)
        novo = cnpj[:12]

        prod = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
        while len(novo) < 14:
            r = sum([x*y for (x, y) in zip(novo, prod)]) % 11
            if r > 1:
                f = 11 - r
            else:
                f = 0
            novo.append(f)
            prod.insert(0, 6)

        # Se o número gerado coincidir com o número original, é válido
        if novo == cnpj:
            return True
            
        return False
    
    def validate_cpf(self, cpf):           
        if not cpf.isdigit():
            import re
            cpf = re.sub('[^0-9]', '', cpf)

        if len(cpf) != 11:
            return False

        # Pega apenas os 9 primeiros dígitos do CPF e gera os 2 dígitos que faltam
        cpf = map(int, cpf)
        novo = cpf[:9]

        while len(novo) < 11:
            r = sum([(len(novo)+1-i)*v for i,v in enumerate(novo)]) % 11

            if r > 1:
                f = 11 - r
            else:
                f = 0
            novo.append(f)

        # Se o número gerado coincidir com o número original, é válido
        if novo == cpf:
            return True
            
        return False

    _constraints = [(_check_cnpj_cpf, 'CNPJ/CPF invalido!', ['cnpj_cpf'])]

    def on_change_mask_cnpj_cpf(self, cr, uid, ids, tipo_pessoa, cnpj_cpf):
        if not cnpj_cpf or not tipo_pessoa:
            return {}

        import re
        val = re.sub('[^0-9]', '', cnpj_cpf)

        if tipo_pessoa == 'J' and len(val) == 14:            
            cnpj_cpf = "%s.%s.%s/%s-%s" % (val[0:2], val[2:5], val[5:8], val[8:12], val[12:14])
        
        elif tipo_pessoa == 'F' and len(val) == 11:
            cnpj_cpf = "%s.%s.%s-%s" % (val[0:3], val[3:6], val[6:9], val[9:11])
        
        return {'value': {'tipo_pessoa': tipo_pessoa, 'cnpj_cpf': cnpj_cpf}}
    
    def zip_search(self, cr, uid, ids, context={}):
        return True    
    
res_partner()

##############################################################################
# Contato do Parceiro Personalizado
##############################################################################
class res_partner_address(osv.osv):
    _inherit = 'res.partner.address'
    _columns = {
	'city_id': fields.many2one('l10n_br_base.city', 'Municipio', domain="[('state_id','=',state_id)]"),
    'district': fields.char('Bairro', size=32),
    'number': fields.char('Número', size=10),
    }

    def on_change_city_id(self, cr, uid, ids, city_id):
        
        result = {'value': {'city': None}}

        if not city_id:
            return result

        obj_city = self.pool.get('l10n_br_base.city').read(cr, uid, city_id, ['name'])
        
        if obj_city:
            result['value'] = {'city': obj_city['name']}
        
        return result

    def on_change_zip(self, cr, uid, ids, zip):
        
        result = {'value': {'street': None, 'city_id': None, 'city': None, 'state_id': None, 'country_id': None, 'zip': None }}

        if not zip:
            return result
        
        obj_cep = self.pool.get('l10n_br_base.cep').browse(cr, uid, zip)
        
        result['value']['street'] = obj_cep.street_type + ' ' + obj_cep.street
        result['value']['city_id'] = obj_cep.city_id.id
        result['value']['city'] = obj_cep.city_id.name
        result['value']['state_id'] = obj_cep.state_id.id
        result['value']['country_id'] = obj_cep.state_id.country_id.id
        result['value']['zip'] = obj_cep.code
        
        return result

res_partner_address()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<commit_msg>Criado modulo l10n_br_data_cep com base de dados de ceps separado do l10n_br_data_base, alterado a dedução da CST por NCM nas linhas das notas fiscais<commit_after># -*- encoding: utf-8 -*-
#################################################################################
#                                                                               #
# Copyright (C) 2009  <NAME> - Akretion, <NAME>                 #
#                                                                               #
#This program is free software: you can redistribute it and/or modify           #
#it under the terms of the GNU 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 General Public License for more details.                                   #
#                                                                               #
#You should have received a copy of the GNU General Public License              #
#along with this program.  If not, see <http://www.gnu.org/licenses/>.          #
#################################################################################

from osv import osv, fields

##############################################################################
# Parceiro Personalizado
##############################################################################
class res_partner(osv.osv):
    _inherit = 'res.partner'
    _columns = {
        'tipo_pessoa': fields.selection([('F', 'Física'), ('J', 'Jurídica')], 'Tipo de pessoa', required=True),
        'cnpj_cpf': fields.char('CNPJ/CPF', size=18),
        'inscr_est': fields.char('Inscr. Estadual', size=16),
        'inscr_mun': fields.char('Inscr. Municipal', size=18),
        'suframa': fields.char('Suframa', size=18),
        'legal_name' : fields.char('Razão Social', size=128, help="nome utilizado em documentos fiscais"),
    }

    _defaults = {
        'tipo_pessoa': lambda *a: 'J',
    }

    def _check_cnpj_cpf(self, cr, uid, ids):
        partner = self.browse(cr, uid, ids)[0]
        if not partner.cnpj_cpf:
            return True

        if partner.tipo_pessoa == 'J':
            return self.validate_cnpj(partner.cnpj_cpf)
        elif partner.tipo_pessoa == 'F':
            return self.validate_cpf(partner.cnpj_cpf)

        return False

    def validate_cnpj(self, cnpj):
        # Limpando o cnpj
        if not cnpj.isdigit():
            import re
            cnpj = re.sub('[^0-9]', '', cnpj)
           
        # verificando o tamano do  cnpj
        if len(cnpj) != 14:
            return False
            
        # Pega apenas os 12 primeiros dígitos do CNPJ e gera os 2 dígitos que faltam
        cnpj= map(int, cnpj)
        novo = cnpj[:12]

        prod = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
        while len(novo) < 14:
            r = sum([x*y for (x, y) in zip(novo, prod)]) % 11
            if r > 1:
                f = 11 - r
            else:
                f = 0
            novo.append(f)
            prod.insert(0, 6)

        # Se o número gerado coincidir com o número original, é válido
        if novo == cnpj:
            return True
            
        return False
    
    def validate_cpf(self, cpf):           
        if not cpf.isdigit():
            import re
            cpf = re.sub('[^0-9]', '', cpf)

        if len(cpf) != 11:
            return False

        # Pega apenas os 9 primeiros dígitos do CPF e gera os 2 dígitos que faltam
        cpf = map(int, cpf)
        novo = cpf[:9]

        while len(novo) < 11:
            r = sum([(len(novo)+1-i)*v for i,v in enumerate(novo)]) % 11

            if r > 1:
                f = 11 - r
            else:
                f = 0
            novo.append(f)

        # Se o número gerado coincidir com o número original, é válido
        if novo == cpf:
            return True
            
        return False

    _constraints = [(_check_cnpj_cpf, 'CNPJ/CPF invalido!', ['cnpj_cpf'])]

    def on_change_mask_cnpj_cpf(self, cr, uid, ids, tipo_pessoa, cnpj_cpf):
        if not cnpj_cpf or not tipo_pessoa:
            return {}

        import re
        val = re.sub('[^0-9]', '', cnpj_cpf)

        if tipo_pessoa == 'J' and len(val) == 14:            
            cnpj_cpf = "%s.%s.%s/%s-%s" % (val[0:2], val[2:5], val[5:8], val[8:12], val[12:14])
        
        elif tipo_pessoa == 'F' and len(val) == 11:
            cnpj_cpf = "%s.%s.%s-%s" % (val[0:3], val[3:6], val[6:9], val[9:11])
        
        return {'value': {'tipo_pessoa': tipo_pessoa, 'cnpj_cpf': cnpj_cpf}}
    
    def zip_search(self, cr, uid, ids, context={}):
        return True    
    
res_partner()

##############################################################################
# Contato do Parceiro Personalizado
##############################################################################
class res_partner_address(osv.osv):
    _inherit = 'res.partner.address'
    _columns = {
	'city_id': fields.many2one('l10n_br_base.city', 'Municipio', domain="[('state_id','=',state_id)]"),
    'district': fields.char('Bairro', size=32),
    'number': fields.char('Número', size=10),
    }

    def on_change_city_id(self, cr, uid, ids, city_id):

        result = {'value': {'city': None}}

        if not city_id:
            return result

        obj_city = self.pool.get('l10n_br_base.city').read(cr, uid, city_id, ['name'])

        if obj_city:
            result['value'] = {'city': obj_city['name']}

        return result

    def on_change_zip(self, cr, uid, ids, zip):
        
        result = {'value': {'street': None, 'city_id': None, 'city': None, 'state_id': None, 'country_id': None, 'zip': None }}

        if not zip:
            return result
        
        obj_cep = self.pool.get('l10n_br_base.cep').browse(cr, uid, zip)
        
        result['value']['street'] = obj_cep.street_type + ' ' + obj_cep.street
        result['value']['city_id'] = obj_cep.city_id.id
        result['value']['city'] = obj_cep.city_id.name
        result['value']['state_id'] = obj_cep.state_id.id
        result['value']['country_id'] = obj_cep.state_id.country_id.id
        result['value']['zip'] = obj_cep.code
        
        return result

res_partner_address()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
{'fraction_non_alphanumeric': 0.18772048337461533, 'fraction_numerical': 0.016362681077835322, 'mean_word_length': 1.890238611713666, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 30, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2814237', 'n_tokens_mistral': 4289, 'n_tokens_neox': 4051, 'n_words': 1046}