← Back to team overview

openerp-brazil-team team mailing list archive

lp:~openerp-brazil-core-team/openerp.pt-br-localiz/l10n_br_inscr_est_refatorada_v2 into lp:openerp.pt-br-localiz

 

Renato Lima - http://www.akretion.com has proposed merging lp:~openerp-brazil-core-team/openerp.pt-br-localiz/l10n_br_inscr_est_refatorada_v2 into lp:openerp.pt-br-localiz.

Requested reviews:
  OpenERP Brazil Core Team (openerp-brazil-core-team)

For more details, see:
https://code.launchpad.net/~openerp-brazil-core-team/openerp.pt-br-localiz/l10n_br_inscr_est_refatorada_v2/+merge/119740
-- 
https://code.launchpad.net/~openerp-brazil-core-team/openerp.pt-br-localiz/l10n_br_inscr_est_refatorada_v2/+merge/119740
Your team OpenERP Brazil Team is subscribed to branch lp:openerp.pt-br-localiz.
=== modified file 'l10n_br_base/__openerp__.py'
--- l10n_br_base/__openerp__.py	2011-11-29 20:21:17 +0000
+++ l10n_br_base/__openerp__.py	2012-08-15 15:53:26 +0000
@@ -38,7 +38,10 @@
         		'partner_view.xml',
                 'security/ir.model.access.csv',
                 'security/l10n_br_base_security.xml',
-
+    ],
+    'test': [
+            'test/base_inscr_est_valid.yml',
+            'test/base_inscr_est_invalid.yml',
     ],
     'demo_xml': ['l10n_br_base_demo.xml'],
     'installable': True

=== modified file 'l10n_br_base/partner.py'
--- l10n_br_base/partner.py	2012-07-11 17:58:24 +0000
+++ l10n_br_base/partner.py	2012-08-15 15:53:26 +0000
@@ -18,10 +18,31 @@
 #################################################################################
 
 import re
-import string
-
 from osv import osv, fields
 
+parametros = {
+    'ac': {'tam': 13, 'val_tam': 11, 'starts_with': '01'}, #OK
+    'al': {'tam': 9, 'starts_with': '24'},
+    'am': {'tam': 9},
+    'ce': {'tam': 9},
+    'df': {'tam': 13, 'val_tam': 11, 'starts_with': '07'},
+    'es': {'tam': 9},
+    'ma': {'tam': 9, 'starts_with': '12'},
+    'mt': {'tam': 11, 'prod': [3, 2, 9, 8, 7, 6, 5, 4, 3, 2]},
+    'ms': {'tam': 9, 'starts_with': '28'},
+    'pa': {'tam': 9, 'starts_with': '15'},
+    'pb': {'tam': 9},
+    'pr': {'tam': 10, 'val_tam': 8, 'prod': [3, 2, 7, 6, 5, 4, 3, 2]},
+    'pi': {'tam': 9 },
+    'rj': {'tam': 8 , 'prod': [2, 7, 6, 5, 4, 3, 2]},
+    'rn': {'tam': 10, 'val_tam':  9,  'prod' : [10, 9, 8, 7, 6, 5, 4, 3, 2] },
+    'rs': {'tam': 10},
+    'rr': {'tam': 9, 'starts_with': '24', 'prod': [1, 2, 3, 4, 5, 6, 7, 8], 'div':9},
+    'sc': {'tam': 9},
+    'se': {'tam': 9},
+    }
+
+
 class res_partner(osv.osv):
 
     _inherit = 'res.partner'
@@ -33,16 +54,20 @@
         return result.keys()
 
     def _address_default_fs(self, cr, uid, ids, name, arg, context=None):
+<<<<<<< TREE
+=======
+
+>>>>>>> MERGE-SOURCE
         res = {}
         for partner in self.browse(cr, uid, ids, context=context):
             res[partner.id] = {'addr_fs_code': False}
-            
+
             partner_addr = self.pool.get('res.partner').address_get(cr, uid, [partner.id], ['invoice'])
             if partner_addr:
                 partner_addr_default = self.pool.get('res.partner.address').browse(cr, uid, [partner_addr['invoice']])[0]
                 addr_fs_code = partner_addr_default.state_id and partner_addr_default.state_id.code or ''
                 res[partner.id]['addr_fs_code'] = addr_fs_code.lower()
-                
+
         return res
 
     _columns = {
@@ -52,11 +77,11 @@
                 '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"),
-                'addr_fs_code': fields.function(_address_default_fs, method=True, 
-                                                string='Address Federal State Code', 
+                'addr_fs_code': fields.function(_address_default_fs, method=True,
+                                                string='Address Federal State Code',
                                                 type="char", size=2, multi='all',
                                                 store={'res.partner.address': (_get_partner_address, ['country_id', 'state_id'], 20),}),
-                
+
                 }
 
     _defaults = {
@@ -68,7 +93,7 @@
         for partner in self.browse(cr, uid, ids):
             if not partner.cnpj_cpf:
                 continue
-    
+
             if partner.tipo_pessoa == 'J':
                 if not self._validate_cnpj(partner.cnpj_cpf):
                     return False
@@ -79,15 +104,15 @@
         return True
 
     def _validate_cnpj(self, cnpj):
-        
+
         # Limpando o cnpj
         if not cnpj.isdigit():
             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]
@@ -105,10 +130,16 @@
         # Se o número gerado coincidir com o número original, é válido
         if novo == cnpj:
             return True
-            
+
         return False
+<<<<<<< TREE
     
     def _validate_cpf(self, cpf):  
+=======
+
+    def _validate_cpf(self, cpf):
+
+>>>>>>> MERGE-SOURCE
         if not cpf.isdigit():
             cpf = re.sub('[^0-9]', '', cpf)
 
@@ -131,11 +162,60 @@
         # Se o número gerado coincidir com o número original, é válido
         if novo == cpf:
             return True
+
+        return False
+    
+    def _validate_ie_param(self, uf, inscr_est):
+
+        if not uf in parametros:
+            return True
+        
+        tam = parametros[uf].get('tam', 0) 
+         
+        inscr_est = unicode(inscr_est).strip().rjust(int(tam),u'0')
+
+        inscr_est = re.sub('[^0-9]', '', inscr_est)
+        
+        val_tam = parametros[uf].get('val_tam', tam - 1)
+        if isinstance(tam, list):
+            i = tam.find(len(inscr_est))
+            if i == -1:
+                return False
+            else:
+                val_tam = val_tam[i]
+        else:
+            if len(inscr_est) != tam:
+                return False
+    
+        sw = parametros[uf].get('starts_with', '')
+        if not inscr_est.startswith(sw):
+            return False
+    
+        inscr_est_ints = [int(c) for c in inscr_est]
+        nova_ie = inscr_est_ints[:val_tam]
+    
+        prod = parametros[uf].get('prod', [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2])
+        prod = prod[-val_tam:]
+        while len(nova_ie) < tam:
+            r = sum([x * y for (x, y) in zip(nova_ie, prod)]) %  parametros[uf].get('div', 11)
             
-        return False
+            if r > 1:
+                f = 11 - r
+            else:
+                f = 0
+                
+            if not uf in 'rr':    
+                nova_ie.append(f)
+            else:
+                nova_ie.append(r)
+            prod.insert(0, prod[0] + 1)
     
+        # Se o número gerado coincidir com o número original, é válido
+        return nova_ie == inscr_est_ints
+
+
     def _check_ie(self, cr, uid, ids):
-        """Checks if company register number in field insc_est is valid, 
+        """Checks if company register number in field insc_est is valid,
         this method call others methods because this validation is State wise
         @param self: The object pointer
         @param cr: the current row, from the database cursor,
@@ -145,215 +225,184 @@
         """
 
         for partner in self.browse(cr, uid, ids):
-            
-            validate = getattr(self, '_validate_ie_%s' % partner.addr_fs_code, None)
-
-            if not partner.inscr_est or partner.inscr_est == 'ISENTO' or not validate or partner.tipo_pessoa == 'F':
+            if not partner.inscr_est \
+                or partner.inscr_est == 'ISENTO' \
+                or partner.tipo_pessoa == 'F':
                 continue
 
-            if partner.tipo_pessoa == 'J':
-                if callable(validate):
-                    if not validate(partner.inscr_est):
-                        return False
-
-        return True
-
-    def _validate_ie_ac(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Acre
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_al(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Alagoas
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_am(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Amazonas
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
+            uf = partner.addr_fs_code
+            try:
+                validate = getattr(self, '_validate_ie_%s' % uf)
+                if not validate(partner.inscr_est):
+                    return False
+            except AttributeError:
+                if not self._validate_ie_param(uf, partner.inscr_est):
+                    return False
+
+        return True
+
     def _validate_ie_ap(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Amapá
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
+        inscr_est = re.sub('[^0-9]', '', inscr_est)
+
+        # verificando o tamanho da inscrição estadual
+        if len(inscr_est) != 9:
+            return False
+
+        # verificando os dois primeiros dígitos
+        if not inscr_est.startswith('03'):
+            return False
+
+        # Pega apenas os 8 primeiros dígitos da inscrição estadual e
+        # define os valores de 'p' e 'd'
+        inscr_est_int = int(inscr_est[:8])
+        if inscr_est_int <= 3017000:
+            inscr_est_p = 5
+            inscr_est_d = 0
+        elif inscr_est_int <= 3019022:
+            inscr_est_p = 9
+            inscr_est_d = 1
+        else:
+            inscr_est_p = 0
+            inscr_est_d = 0
+
+        # Pega apenas os 8 primeiros dígitos da inscrição estadual e
+        # gera o dígito verificador
+        inscr_est = map(int, inscr_est)
+        nova_ie = inscr_est[:8]
+
+        prod = [9, 8, 7, 6, 5, 4, 3, 2]
+        r = (inscr_est_p + sum([x * y for (x, y) in zip(nova_ie, prod)])) % 11
+        if r > 1:
+            f = 11 - r
+        elif r == 1:
+            f = 0
+        else:
+            f = inscr_est_d
+        nova_ie.append(f)
+
+        return nova_ie == inscr_est
+
     def _validate_ie_ba(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Bahia
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_ce(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Ceará
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_df(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Distitro Federal
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False._check_ie
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_es(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Espirito Santo
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
+        inscr_est = re.sub('[^0-9]', '', inscr_est)
+        inscr_est = map(int, inscr_est)
+
+        # verificando o tamanho da inscrição estadual
+        if len(inscr_est) == 8:
+            tam = 8
+            val_tam = 6
+            test_digit = 0
+        elif len(inscr_est) == 9:
+            tam = 9
+            val_tam = 7
+            test_digit = 1
+        else:
+            return False
+
+        nova_ie = inscr_est[:val_tam]
+
+        prod = [8, 7, 6, 5, 4, 3, 2][-val_tam:]
+
+        if inscr_est[test_digit] in [0, 1, 2, 3, 4, 5, 8]:
+            modulo = 10
+        else:
+            modulo = 11
+
+        while len(nova_ie) < tam:
+            r = sum([x * y for (x, y) in zip(nova_ie, prod)]) % modulo
+            if r > 0:
+                f = modulo - r
+            else:
+                f = 0
+
+            if len(nova_ie) == val_tam:
+                nova_ie.append(f)
+            else:
+                nova_ie.insert(val_tam, f)
+            prod.insert(0, prod[0] + 1)
+
+        return nova_ie == inscr_est
+
     def _validate_ie_go(self, inscr_est):
-        """Checks if company register number is val_check_ieid to Brazilian
-        state Goiais
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_ma(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Maranhão
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO_check_ie
-        return True
-    
+        inscr_est = re.sub('[^0-9]', '', inscr_est)
+
+        # verificando o tamanho da inscrição estadual
+        if len(inscr_est) != 9:
+            return False
+
+        # verificando os dois primeiros dígitos
+        if not inscr_est[:2] in ['10', '11', '15']:
+            return False
+
+        # Pega apenas os 8 primeiros dígitos da inscrição estadual e
+        # define os valores de 'p' e 'd'
+        inscr_est_int = int(inscr_est[:8])
+        if inscr_est_int >= 10103105 and inscr_est_int <= 10119997:
+            inscr_est_d = 1
+        else:
+            inscr_est_d = 0
+
+        # Pega apenas os 8 primeiros dígitos da inscrição estadual e
+        # gera o dígito verificador
+        inscr_est = map(int, inscr_est)
+        nova_ie = inscr_est[:8]
+
+        prod = [9, 8, 7, 6, 5, 4, 3, 2]
+        r = sum([x * y for (x, y) in zip(nova_ie, prod)]) % 11
+        if r > 1:
+            f = 11 - r
+        elif r == 1:
+            f = inscr_est_d
+        else:
+            f = 0
+        nova_ie.append(f)
+
+        return nova_ie == inscr_est
+
     def _validate_ie_mg(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Minas Gerais
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_ms(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Mato Grosso do Sul
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_mt(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Mato Grosso
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_pa(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Pará
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_pb(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Paraíba
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
+        inscr_est = re.sub('[^0-9]', '', inscr_est)
+
+        # verificando o tamanho da inscrição estadual
+        if len(inscr_est) != 13:
+            return False
+
+        # Pega apenas os 11 primeiros dígitos da inscrição estadual e
+        # gera os dígitos verificadores
+        inscr_est = map(int, inscr_est)
+        nova_ie = inscr_est[:11]
+
+        nova_ie_aux = list(nova_ie)
+        nova_ie_aux.insert(3, 0)
+        prod = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
+        r = str([x * y for (x, y) in zip(nova_ie_aux, prod)])
+        r = re.sub('[^0-9]', '', r)
+        r = map(int, r)
+        r = sum(r)
+        r2 = (r / 10 + 1) * 10 
+        r = r2 - r
+           
+        if r >=10:
+            r = 0;
+        
+        nova_ie.append(r)
+
+        prod = [3, 2, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
+        r = sum([x * y for (x, y) in zip(nova_ie, prod)]) % 11
+        if r > 1:
+            f = 11 - r
+        else:
+            f = 0
+        nova_ie.append(f)
+
+        return nova_ie == inscr_est
+
     def _validate_ie_pe(self, inscr_est):
-        """Check if number in insc_est is valid to Brazilian
-        state of Pernambuco
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_pi(self, inscr_est):
-        """Check if number in insc_est is valid to Brazilian
-        state of Piauí
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_pr(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Rio de Paraná
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_rj(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Rio de janeiro
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        
-        # Limpando o cnpj
-        if not inscr_est.isdigit():
-            inscr_est = re.sub('[^0-9]', '', inscr_est)
+        inscr_est = re.sub('[^0-9]', '', inscr_est)
 
-        # verificando o tamano do  cnpj
-        if len(inscr_est) != 8:
+        # verificando o tamanho da inscrição estadual
+        if (len(inscr_est) != 9) and (len(inscr_est) != 14):
             return False
 
+<<<<<<< TREE
         # Pega apenas os 12 primeiros dígitos do CNPJ e gera os 2 dígitos que faltam
         inscr_est = map(int, inscr_est)
         nova_ie = inscr_est[:7]
@@ -365,104 +414,173 @@
                 f = 11 - r
             else:
                 f = 0
+=======
+        inscr_est = map(int, inscr_est)
+
+        # verificando o tamanho da inscrição estadual
+        if len(inscr_est) == 9:
+
+            # Pega apenas os 7 primeiros dígitos da inscrição estadual e
+            # gera os dígitos verificadores
+            inscr_est = map(int, inscr_est)
+            nova_ie = inscr_est[:7]
+
+            prod = [8, 7, 6, 5, 4, 3, 2]
+            while len(nova_ie) < 9:
+                r = sum([x * y for (x, y) in zip(nova_ie, prod)]) % 11
+                if r > 1:
+                    f = 11 - r
+                else:
+                    f = 0
+                nova_ie.append(f)
+                prod.insert(0, 9)
+        elif len(inscr_est) == 14:
+
+            # Pega apenas os 13 primeiros dígitos da inscrição estadual e
+            # gera o dígito verificador
+            inscr_est = map(int, inscr_est)
+            nova_ie = inscr_est[:13]
+
+            prod = [5, 4, 3, 2, 1, 9, 8, 7, 6, 5, 4, 3, 2]
+            r = sum([x * y for (x, y) in zip(nova_ie, prod)]) % 11
+            f = 11 - r
+            if f > 10:
+                f = f - 10
+>>>>>>> MERGE-SOURCE
             nova_ie.append(f)
-            prod.insert(0, 6)
-
-        # Se o número gerado coincidir com o número original, é válido
-        if nova_ie == inscr_est:
-            return True
-
-        return False
-    
-    def _validate_ie_rn(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Rio Grande do Norte
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
+
+        return nova_ie == inscr_est
+
     def _validate_ie_ro(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Rondônia
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_rr(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Roraima
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_rs(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Rio Grande do Sul
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_sc(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Santa Catarina
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
-    def _validate_ie_se(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Sergipe
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
+        def gera_digito_ro(nova_ie, prod):
+            r = sum([x * y for (x, y) in zip(nova_ie, prod)]) % 11
+            f = 11 - r
+            if f > 9:
+                f = f - 10
+            return f
+
+        inscr_est = re.sub('[^0-9]', '', inscr_est)
+        inscr_est = map(int, inscr_est)
+
+        # verificando o tamanho da inscrição estadual
+        if len(inscr_est) == 9:
+            # Despreza-se os 3 primeiros dígitos, pega apenas os 8 primeiros
+            # dígitos da inscrição estadual e gera o dígito verificador
+            nova_ie = inscr_est[3:8]
+
+            prod = [6, 5, 4, 3, 2]
+            f = gera_digito_ro(nova_ie, prod)
+            nova_ie.append(f)
+
+            nova_ie = inscr_est[0:3] + nova_ie
+        elif len(inscr_est) == 14:
+            # Pega apenas os 13 primeiros dígitos da inscrição estadual e
+            # gera o dígito verificador
+            nova_ie = inscr_est[:13]
+
+            prod = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
+            f = gera_digito_ro(nova_ie, prod)
+            nova_ie.append(f)
+        else:
+            return False
+
+        return nova_ie == inscr_est
+
     def _validate_ie_sp(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state São Paulo
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
+        def gera_digito_sp(nova_ie, prod):
+            r = sum([x * y for (x, y) in zip(nova_ie, prod)]) % 11
+            if r < 10:
+                return r
+            elif r == 10:
+                return 0
+            else:
+                return 1
+
+        # Industriais e comerciais
+        if inscr_est[0] != 'P':
+
+            inscr_est = re.sub('[^0-9]', '', inscr_est)
+
+            # verificando o tamanho da inscrição estadual
+            if len(inscr_est) != 12:
+                return False
+
+            # Pega apenas os 8 primeiros dígitos da inscrição estadual e
+            # gera o primeiro dígito verificador
+            inscr_est = map(int, inscr_est)
+            nova_ie = inscr_est[:8]
+
+            prod = [1, 3, 4, 5, 6, 7, 8, 10]
+            f = gera_digito_sp(nova_ie, prod)
+            nova_ie.append(f)
+
+            # gera o segundo dígito verificador
+            nova_ie.extend(inscr_est[9:11])
+            prod = [3, 2, 10, 9, 8, 7, 6, 5, 4, 3, 2]
+            f = gera_digito_sp(nova_ie, prod)
+            nova_ie.append(f)
+
+        # Produtor rural
+        else:
+            inscr_est = re.sub('[^0-9]', '', inscr_est)
+
+            # verificando o tamanho da inscrição estadual
+            if len(inscr_est) != 12:
+                return False
+
+            # verificando o primeiro dígito depois do 'P'
+            if inscr_est[0] != '0':
+                return False
+
+            # Pega apenas os 8 primeiros dígitos da inscrição estadual e
+            # gera o dígito verificador
+            inscr_est = map(int, inscr_est)
+            nova_ie = inscr_est[:8]
+
+            prod = [1, 3, 4, 5, 6, 7, 8, 10]
+            f = gera_digito_sp(nova_ie, prod)
+            nova_ie.append(f)
+
+            nova_ie.extend(inscr_est[9:])
+
+        return nova_ie == inscr_est
+
     def _validate_ie_to(self, inscr_est):
-        """Checks if company register number is valid to Brazilian
-        state Tocantins
-        @param self: The object pointer
-        @param inscr_est: The company state number value,
-        @return: True or False.
-        """
-        #TODO
-        return True
-    
+        inscr_est = re.sub('[^0-9]', '', inscr_est)
+
+        # verificando o tamanho da inscrição estadual
+        if len(inscr_est) != 11:
+            return False
+
+        # verificando os dígitos 3 e 4
+        if not inscr_est[2:4] in ['01', '02', '03', '99']:
+            return False
+
+        # Pega apenas os dígitos que entram no cálculo
+        inscr_est = map(int, inscr_est)
+        nova_ie = inscr_est[:2] + inscr_est[4:10]
+
+        prod = [9, 8, 7, 6, 5, 4, 3, 2]
+        r = sum([x * y for (x, y) in zip(nova_ie, prod)]) % 11
+        if r > 1:
+            f = 11 - r
+        else:
+            f = 0
+        nova_ie.append(f)
+
+        nova_ie = nova_ie[:2] + inscr_est[2:4] + nova_ie[2:]
+
+        return nova_ie == inscr_est
+
     _constraints = [
                     (_check_cnpj_cpf, u'CNPJ/CPF invalido!', ['cnpj_cpf']),
                     (_check_ie, u'Inscrição Estadual inválida!', ['inscr_est'])
     ]
-    
+
     _sql_constraints = [
-                    ('res_partner_cnpj_cpf_uniq', 'unique (cnpj_cpf)', 
+                    ('res_partner_cnpj_cpf_uniq', 'unique (cnpj_cpf)',
                      u'Já existe um parceiro cadastrado com este CPF/CNPJ !'),
-                    ('res_partner_inscr_est_uniq', 'unique (inscr_est)', 
+                    ('res_partner_inscr_est_uniq', 'unique (inscr_est)',
                      u'Já existe um parceiro cadastrado com esta Inscrição Estadual/RG !')
     ]
 
@@ -471,18 +589,18 @@
             return {}
         val = re.sub('[^0-9]', '', cnpj_cpf)
 
-        if tipo_pessoa == 'J' and len(val) == 14:            
+        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}}
-    
+
 res_partner()
 
 class res_partner_address(osv.osv):
-    
+
     _inherit = 'res.partner.address'
 
     _columns = {
@@ -505,11 +623,11 @@
             result['value']['l10n_br_city_id'] = obj_city['id']
 
         return result
-    
+
     def onchange_mask_zip(self, cr, uid, ids, zip):
-        
+
         result = {'value': {'zip': False}}
-        
+
         if not zip:
             return result
 
@@ -521,31 +639,40 @@
         return result
 
     def zip_search(self, cr, uid, ids, context=None):
-        
+
         result = {
-                  'street': False, 
-                  'l10n_br_city_id': False, 
-                  'city': False, 
-                  'state_id': False, 
-                  'country_id': False, 
+                  'street': False,
+                  'l10n_br_city_id': False,
+                  'city': False,
+                  'state_id': False,
+                  'country_id': False,
                   'zip': False
                   }
 
         obj_zip = self.pool.get('l10n_br_base.zip')
-        
+
         for res_partner_address in self.browse(cr, uid, ids):
-            
+
             domain = []
             if res_partner_address.zip:
                 zip = re.sub('[^0-9]', '', res_partner_address.zip or '')
                 domain.append(('code', '=', zip))
             else:
+<<<<<<< TREE
                 domain.append(('street', '=', res_partner_address.street))
                 domain.append(('district', '=', res_partner_address.district))
                 domain.append(('country_id', '=', res_partner_address.country_id.id))
                 domain.append(('state_id', '=', res_partner_address.state_id.id))
                 domain.append(('l10n_br_city_id', '=', res_partner_address.l10n_br_city_id.id))
             
+=======
+                domain.append(('street','=',res_partner_address.street))
+                domain.append(('district','=',res_partner_address.district))
+                domain.append(('country_id','=',res_partner_address.country_id.id))
+                domain.append(('state_id','=',res_partner_address.state_id.id))
+                domain.append(('l10n_br_city_id','=',res_partner_address.l10n_br_city_id.id))
+
+>>>>>>> MERGE-SOURCE
             zip_id = obj_zip.search(cr, uid, domain)
 
             if not len(zip_id) == 1:
@@ -575,17 +702,17 @@
                 return result
 
             zip_read = obj_zip.read(cr, uid, zip_id, [
-                                                      'street_type', 
-                                                      'street','district', 
+                                                      'street_type',
+                                                      'street','district',
                                                       'code',
-                                                      'l10n_br_city_id', 
-                                                      'city', 'state_id', 
+                                                      'l10n_br_city_id',
+                                                      'city', 'state_id',
                                                       'country_id'], context=context)[0]
 
             zip = re.sub('[^0-9]', '', zip_read['code'] or '')
             if len(zip) == 8:
                 zip = '%s-%s' % (zip[0:5], zip[5:8])
-            
+
             result['street'] = ((zip_read['street_type'] or '') + ' ' + (zip_read['street'] or ''))
             result['district'] = zip_read['district']
             result['zip'] = zip

=== added file 'l10n_br_base/test/base_inscr_est_invalid.yml'
--- l10n_br_base/test/base_inscr_est_invalid.yml	1970-01-01 00:00:00 +0000
+++ l10n_br_base/test/base_inscr_est_invalid.yml	2012-08-15 15:53:26 +0000
@@ -0,0 +1,111 @@
+-
+  Testing insc_est validate by state
+-
+ !python {model: res.partner}: |
+    insc_est_ac_valids = ['0102190200161', '0101296300282', '0100258700141', '0101296300101', '0101613200121', '0100662000131']
+    for insc_est in insc_est_ac_valids:
+        assert not self._validate_ie_param('ac', insc_est), 'Error on validate AC insc_est'
+
+    insc_estal_al_valids = ['241065551', '248501412', '240916422', '248540982', '248429982', '246014341']
+    for insc_est in insc_estal_al_valids:
+        assert not self._validate_ie_param('al', insc_est), 'Error on validate AL insc_est'
+
+    insc_est_am_valids = ['042933681', '041330181', '042357072', '042338961', '042215381', '042201621']
+    for insc_est in insc_est_am_valids:
+        assert not self._validate_ie_param('am', insc_est), 'Error on validate AM insc_est'
+
+    insc_est_ap_valids = ['030380341', '030317542', '030273451', '030131811', '030069385']
+    for insc_est in insc_est_ap_valids:
+        assert not self._validate_ie_ap(insc_est), 'Error on validate AP insc_est'
+
+    insc_est_ba_valids = ['41902652', '77893322', '51153772', '14621861', '09874625']
+    for insc_est in insc_est_ba_valids:
+        assert not self._validate_ie_ba(insc_est), 'Error on validate BA insc_est'
+
+    insc_est_ce_valids = ['063873771', '061876641', '062164251', '061970361', '061880991', '069108591']
+    for insc_est in insc_est_ce_valids:
+        assert not self._validate_ie_param('ce', insc_est), 'Error on validate CE insc_est'
+
+    insc_est_df_valids = ['0732709900171', '0730562700171', '0751504400161', '0744409300181', '0748774800131', '0747987900101']
+    for insc_est in insc_est_df_valids:
+        assert not self._validate_ie_param('df', insc_est), 'Error on validate DF insc_est'
+
+    insc_est_es_valids = ['082376121', '082106021', '082467671', '082169711', '082585301', '082588571']
+    for insc_est in insc_est_es_valids:
+        assert not self._validate_ie_param('es', insc_est), 'Error on validate ES insc_est'
+
+    insc_est_go_valids = ['103450591', '104197631', '104345191', '104455571', '104555271']
+    for insc_est in insc_est_go_valids:
+        assert not self._validate_ie_go(insc_est), 'Error on validate GO insc_est'
+
+    insc_est_valids = ['121498291', '122045040', '123214281', '123110131', '123170521', '121530061']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_param('ma', insc_est), 'Error on validate MA insc_est'
+
+    insc_est_mg_valids = ['2615950220091', '7000547460061', '3519900270001', '0621828520091', '5780297160001', '0620297160291']
+    for insc_est in insc_est_mg_valids:
+        assert not self._validate_ie_mg(insc_est), 'Error on validate MG insc_est'
+
+    insc_est_valids = ['283370641', '283238931', '283235561', '283167161', '283267081', '283352121']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_param('ms',insc_est), 'Error on validate MS insc_est'
+
+    insc_est_valids = ['00133337411', '00133110021', '00132040541', '00133095611', '00132390321', '00131235461', '00132465711']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_param('mt', insc_est), 'Error on validate MT insc_est'
+
+    insc_est_valids = ['151925940', '152336261', '152355651', '151386350', '153646720', '152346911']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_param('pa', insc_est), 'Error on validate PA insc_est'
+
+    insc_est_valids = ['161435941', '161462711', '161455741', '161349241', '161427451', '160506321']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_param('pb', insc_est), 'Error on validate PB insc_est'
+
+    insc_est_valids = ['4100161411', '9020581251', '1011473550', '1010586971', '9053527171']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_param('pr', insc_est), 'Error on validate PR insc_est'
+
+    insc_est_valids = ['027693361', '18171203059321', '029748001', '18171001920080', '030374521']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_pe(insc_est), 'Error on validate PE insc_est'
+
+    insc_est_valids = ['169609151', '194549991', '194661051', '194507681', '194010401']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_param('pi', insc_est), 'Error on validate PI insc_est'
+
+    insc_est_valids = ['78890161', '78724991', '78205351', '85190880', '78860051', '78873651']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_param('rj', insc_est), 'Error on validate RJ insc_est'
+
+    insc_est_valids = ['200887891', '200395141', '200653011', '201199350', '2074337761', '2010665161','2075778441']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_param('rn', insc_est), 'Error on validate RN insc_est'
+
+    insc_est_valids = ['0240130110', '0963376211', '0290289001', '1240237331', '0570120201', '0962655441', '0962003671']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_param('rs', insc_est), 'Error on validate RS insc_est'
+
+    insc_est_valids = ['00000001656551', '00000001499391', '00000001727111', '00000002999271', '00000001765930']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_ro(insc_est), 'Error on validate RO insc_est'
+
+    insc_est_valids = ['240151301', '240042101', '240128121', '240146371', '240018111', '240106211', '240003911']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_param('rr', insc_est), 'Error on validate RR insc_est'
+
+    insc_est_valids = ['255830691', '253952661', '253967621', '254086581', '252625081', '251083111', '251130481']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_param('sc', insc_est), 'Error on validate SC insc_est'
+
+    insc_est_valids = ['692015742111', '645274188111', '645169551111', '649005952110', '645098352111']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_sp(insc_est), 'Error on validate SP insc_est'
+
+    insc_est_valids = ['271126971', '271233641', '271200631', '270622021', '271307981']
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_param('se', insc_est), 'Error on validate SE insc_est'
+
+    insc_est_valids = ['56021275421', '62025717871', '27026857781', '35026423361'] 
+    for insc_est in insc_est_valids:
+        assert not self._validate_ie_to(insc_est), 'Error on validate TO insc_est'

=== added file 'l10n_br_base/test/base_inscr_est_valid.yml'
--- l10n_br_base/test/base_inscr_est_valid.yml	1970-01-01 00:00:00 +0000
+++ l10n_br_base/test/base_inscr_est_valid.yml	2012-08-15 15:53:26 +0000
@@ -0,0 +1,111 @@
+-
+  Testing insc_est validate by state
+-
+ !python {model: res.partner}: |
+    insc_est_ac_valids = ['0102190200165', '0101296300289', '0100258700145', '0101296300106', '0101613200122', '0100662000133']
+    for insc_est in insc_est_ac_valids:
+        assert self._validate_ie_param('ac', insc_est), 'Error on validate AC insc_est'
+
+    insc_estal_al_valids = ['241065550', '248501410', '240916425', '248540980', '248429981', '246014342']
+    for insc_est in insc_estal_al_valids:
+        assert self._validate_ie_param('al', insc_est), 'Error on validate AL insc_est'
+
+    insc_est_am_valids = ['042933684', '041330188', '042357071', '042338964', '042215382', '042201624']
+    for insc_est in insc_est_am_valids:
+        assert self._validate_ie_param('am', insc_est), 'Error on validate AM insc_est'
+
+    insc_est_ap_valids = ['030380340', '030317541', '030273455', '030131818', '030069381']
+    for insc_est in insc_est_ap_valids:
+        assert self._validate_ie_ap(insc_est), 'Error on validate AP insc_est'
+
+    insc_est_ba_valids = ['41902653', '77893325', '51153771', '14621862', '09874624']
+    for insc_est in insc_est_ba_valids:
+        assert self._validate_ie_ba(insc_est), 'Error on validate BA insc_est'
+
+    insc_est_ce_valids = ['063873770', '061876640', '062164252', '061970360', '061880990', '069108595']
+    for insc_est in insc_est_ce_valids:
+        assert self._validate_ie_param('ce', insc_est), 'Error on validate CE insc_est'
+
+    insc_est_df_valids = ['0732709900174', '0730562700176', '0751504400168', '0744409300183', '0748774800134', '0747987900103']
+    for insc_est in insc_est_df_valids:
+        assert self._validate_ie_param('df', insc_est), 'Error on validate DF insc_est'
+
+    insc_est_es_valids = ['082376123', '082106029', '082467676', '082169713', '082585300', '082588570']
+    for insc_est in insc_est_es_valids:
+        assert self._validate_ie_param('es', insc_est), 'Error on validate ES insc_est'
+
+    insc_est_go_valids = ['103450599', '104197633', '104345195', '104455578', '104555270']
+    for insc_est in insc_est_go_valids:
+        assert self._validate_ie_go(insc_est), 'Error on validate GO insc_est'
+
+    insc_est_valids = ['121498298', '122045041', '123214289', '123110130', '123170524', '121530060']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_param('ma', insc_est), 'Error on validate MA insc_est'
+
+    insc_est_mg_valids = ['2615950220092', '7000547460067', '3519900270005', '0621828520097', '5780297160005', '0620297160299']
+    for insc_est in insc_est_mg_valids:
+        assert self._validate_ie_mg(insc_est), 'Error on validate MG insc_est'
+
+    insc_est_valids = ['283370645', '283238933', '283235560', '283167165', '283267089', '283352124']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_param('ms',insc_est), 'Error on validate MS insc_est'
+
+    insc_est_valids = ['00133337413', '00133110028', '00132040549', '00133095614', '00132390329', '00131235460', '00132465710']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_param('mt', insc_est), 'Error on validate MT insc_est'
+
+    insc_est_valids = ['151925941', '152336265', '152355650', '151386358', '153646721', '152346910']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_param('pa', insc_est), 'Error on validate PA insc_est'
+
+    insc_est_valids = ['161435947', '161462715', '161455743', '161349242', '161427456', '160506328']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_param('pb', insc_est), 'Error on validate PB insc_est'
+
+    insc_est_valids = ['4100161414', '9020581252', '1011473551', '1010586972', '9053527172']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_param('pr', insc_est), 'Error on validate PR insc_est'
+
+    insc_est_valids = ['027693368', '18171203059328', '029748003', '18171001920081', '030374529']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_pe(insc_est), 'Error on validate PE insc_est'
+
+    insc_est_valids = ['169609154', '194549992', '194661059', '194507688', '194010406']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_param('pi', insc_est), 'Error on validate PI insc_est'
+
+    insc_est_valids = ['78890169', '78724994', '78205350', '85190881', '78860057', '78873655']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_param('rj', insc_est), 'Error on validate RJ insc_est'
+
+    insc_est_valids = ['200887890', '200395149', '200653016', '201199351', '2074337760', '2010665163','2075778442']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_param('rn', insc_est), 'Error on validate RN insc_est'
+
+    insc_est_valids = ['0240130111', '0963376217', '0290289009', '1240237330', '0570120209', '0962655449', '0962003670']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_param('rs', insc_est), 'Error on validate RS insc_est'
+
+    insc_est_valids = ['00000001656554', '00000001499394', '00000001727117', '00000002999277', '00000001765931']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_ro(insc_est), 'Error on validate RO insc_est'
+
+    insc_est_valids = ['240151303', '240042104', '240128125', '240146373', '240018116', '240106210', '240003910']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_param('rr', insc_est), 'Error on validate RR insc_est'
+
+    insc_est_valids = ['255830696', '253952662', '253967627', '254086586', '252625080', '251083110', '251130487']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_param('sc', insc_est), 'Error on validate SC insc_est'
+
+    insc_est_valids = ['692015742119', '645274188118', '645169551117', '649005952111', '645098352117']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_sp(insc_est), 'Error on validate SP insc_est'
+
+    insc_est_valids = ['271126973', '271233648', '271200634', '270622020', '271307986']
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_param('se', insc_est), 'Error on validate SE insc_est'
+
+    insc_est_valids = ['56021275424', '62025717872', '27026857780', '35026423360'] 
+    for insc_est in insc_est_valids:
+        assert self._validate_ie_to(insc_est), 'Error on validate TO insc_est'


Follow ups