~akretion-team/openerp.pt-br-localiz/demo-data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
# -*- encoding: utf-8 -*-
#################################################################################
#                                                                               #
# Copyright (C) 2009  Renato Lima - Akretion, Gabriel C. Stabel                 #
#                                                                               #
#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 re
import string

from osv import osv, fields

class res_partner(osv.osv):

    _inherit = 'res.partner'

    def _get_partner_address(self, cr, uid, ids, context=None):
        result = {}
        for parnter_addr in self.pool.get('res.partner.address').browse(cr, uid, ids, context=context):
            result[parnter_addr.partner_id.id] = True
        return result.keys()

    def _address_default_fs(self, cr, uid, ids, name, arg, context=None):
        
        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 = {
                '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/RG', 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"),
                '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 = {
                'tipo_pessoa': lambda *a: 'J',
                }

    def _check_cnpj_cpf(self, cr, uid, ids):

        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
            elif partner.tipo_pessoa == 'F':
                if not self._validate_cpf(partner.cnpj_cpf):
                    return False

        return True

    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
    
    def _check_ie(self, cr, uid, ids):
        """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,
        @param uid: the current user’s ID for security checks,
        @param ids: List of partner Ids,
        @return: True or False.
        """

        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':
                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
    
    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
    
    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
    
    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
    
    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
    
    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)

        # verificando o tamano do  cnpj
        if len(inscr_est) != 8:
            return False

        # 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]

        prod = [2, 7, 6, 5, 4, 3, 2]
        while len(nova_ie) < 8:
            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, 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
    
    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 _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 _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
    
    _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)', 
                     u'Já existe um parceiro cadastrado com este CPF/CNPJ !'),
                    ('res_partner_inscr_est_uniq', 'unique (inscr_est)', 
                     u'Já existe um parceiro cadastrado com esta Inscrição Estadual/RG !')
    ]

    def onchange_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}}
    
res_partner()

class res_partner_address(osv.osv):
    
    _inherit = 'res.partner.address'

    _columns = {
	            '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('Número', size=10),
                }

    def onchange_l10n_br_city_id(self, cr, uid, ids, l10n_br_city_id):

        result = {'value': {'city': False, 'l10n_br_city_id': False}}

        if not l10n_br_city_id:
            return result

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

        if obj_city:
            result['value']['city'] = obj_city['name']
            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

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

        if len(val) == 8:
            zip = "%s-%s" % (val[0:5], val[5:8])
            result['value']['zip'] = zip
        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, 
                  '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:
                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))
            
            zip_id = obj_zip.search(cr, uid, domain)

            if not len(zip_id) == 1:

                context.update({
                                'zip': res_partner_address.zip,
                                'street': res_partner_address.street,
                                'district': res_partner_address.district,
                                'country_id': res_partner_address.country_id.id,
                                'state_id': res_partner_address.state_id.id,
                                'l10n_br_city_id': res_partner_address.l10n_br_city_id.id,
                                'address_id': ids,
                                'object_name': self._name,
                                })

                result = {
                        'name': 'Zip Search',
                        'view_type': 'form',
                        'view_mode': 'form',
                        'res_model': 'l10n_br_base.zip.search',
                        'view_id': False,
                        'context': context,
                        'type': 'ir.actions.act_window',
                        'target': 'new',
                        'nodestroy': True,
                        }
                return result

            zip_read = obj_zip.read(cr, uid, zip_id, [
                                                      'street_type', 
                                                      'street','district', 
                                                      'code',
                                                      '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
            result['l10n_br_city_id'] = zip_read['l10n_br_city_id'] and zip_read['l10n_br_city_id'][0] or False
            result['city'] = zip_read['l10n_br_city_id'] and zip_read['l10n_br_city_id'][1] or ''
            result['state_id'] = zip_read['state_id'] and zip_read['state_id'][0] or False
            result['country_id'] = zip_read['country_id'] and zip_read['country_id'][0] or False
            self.write(cr, uid, res_partner_address.id, result)
            return False

res_partner_address()

class res_partner_bank(osv.osv):

    _inherit = 'res.partner.bank'

    _columns = {
                'acc_number': fields.char('Account Number', size=64, required=False),
                'bank': fields.many2one('res.bank', 'Bank', required=False),
                'acc_number_dig': fields.char("Digito Conta", size=8),
                'bra_number': fields.char("Agência", size=8),
                'bra_number_dig': fields.char("Dígito Agência", size=8),
               }

res_partner_bank()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: