-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathtipos.py
More file actions
437 lines (336 loc) · 14.5 KB
/
tipos.py
File metadata and controls
437 lines (336 loc) · 14.5 KB
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
# -*- encoding: utf8 -*-
import codecs
import importlib
from datetime import datetime
from cnab240 import errors
class Evento(object):
def __init__(self, banco, codigo_evento):
self._segmentos = []
self.banco = banco
self.codigo_evento = codigo_evento
self._codigo_lote = None
def adicionar_segmento(self, segmento):
self._segmentos.append(segmento)
for segmento in self._segmentos:
segmento.servico_codigo_movimento = self.codigo_evento
@property
def segmentos(self):
return self._segmentos
def __getattribute__(self, name):
for segmento in object.__getattribute__(self, '_segmentos'):
if hasattr(segmento, name):
return getattr(segmento, name)
return object.__getattribute__(self, name)
def __unicode__(self):
return u'\r\n'.join(unicode(seg) for seg in self._segmentos)
def __len__(self):
return len(self._segmentos)
@property
def codigo_lote(self):
return self._codigo_lote
@codigo_lote.setter
def codigo_lote(self, valor):
self._codigo_lote = valor
for segmento in self._segmentos:
segmento.controle_lote = valor
def atualizar_codigo_registros(self, last_id):
current_id = last_id
for segmento in self._segmentos:
current_id += 1
segmento.servico_numero_registro = current_id
return current_id
class Lote(object):
def __init__(self, banco, header=None, trailer=None):
self.banco = banco
self.header = header
self.trailer = trailer
self._codigo = None
if self.trailer != None:
self.trailer.quantidade_registros = 2
self._eventos = []
@property
def codigo(self):
return self._codigo
@codigo.setter
def codigo(self, valor):
self._codigo = valor
if self.header != None:
self.header.controle_lote = valor
if self.trailer != None:
self.trailer.controle_lote = valor
self.atualizar_codigo_eventos()
def atualizar_codigo_eventos(self):
for evento in self._eventos:
evento.codigo_lote = self._codigo
def atualizar_codigo_registros(self):
last_id = 0
for evento in self._eventos:
last_id = evento.atualizar_codigo_registros(last_id)
@property
def eventos(self):
return self._eventos
def adicionar_evento(self, evento):
if not isinstance(evento, Evento):
raise TypeError
self._eventos.append(evento)
if self.trailer != None and hasattr(self.trailer, 'quantidade_registros'):
self.trailer.quantidade_registros += len(evento)
self.atualizar_codigo_registros()
if self._codigo:
self.atualizar_codigo_eventos()
# Breakpoint
def __unicode__(self):
if not self._eventos:
raise errors.NenhumEventoError()
result = []
if self.header != None:
result.append(unicode(self.header))
result.extend(unicode(evento) for evento in self._eventos)
if self.trailer != None:
result.append(unicode(self.trailer))
return '\r\n'.join(result)
def __len__(self):
if self.trailer != None and hasattr(self.trailer, 'quantidade_registros'):
return self.trailer.quantidade_registros
else:
return len(self._eventos)
class Arquivo(object):
def __init__(self, banco, **kwargs):
"""Arquivo Cnab240."""
self._lotes = []
self.banco = banco
arquivo = kwargs.get('arquivo')
if isinstance(arquivo, (file, codecs.StreamReaderWriter)):
return self.carregar_retorno(arquivo)
self.header = self.banco.registros.HeaderArquivo(**kwargs)
self.trailer = self.banco.registros.TrailerArquivo(**kwargs)
self.trailer.totais_quantidade_lotes = 0
self.trailer.totais_quantidade_registros = 2
if "arquivo_data_de_geracao" in dir(self.header) and \
self.header.arquivo_data_de_geracao is None:
now = datetime.now()
self.header.arquivo_data_de_geracao = int(now.strftime("%d%m%Y"))
if "arquivo_hora_de_geracao" in dir(self.header) and \
self.header.arquivo_hora_de_geracao is None:
if now is None:
now = datetime.now()
self.header.arquivo_hora_de_geracao = int(now.strftime("%H%M%S"))
def carregar_retorno(self, arquivo):
lote_aberto = None
evento_aberto = None
for linha in arquivo:
tipo_registro = linha[7]
if tipo_registro == '0':
self.header = self.banco.registros.HeaderArquivo()
self.header.carregar(linha)
elif tipo_registro == '1':
codigo_servico = linha[9:11]
if codigo_servico == '01':
header_lote = self.banco.registros.HeaderLoteCobranca()
header_lote.carregar(linha)
trailer_lote = self.banco.registros.TrailerLoteCobranca()
lote_aberto = Lote(self.banco, header_lote, trailer_lote)
self._lotes.append(lote_aberto)
elif codigo_servico == '04':
header_lote = self.banco.registros.HeaderLoteExtrato()
header_lote.carregar(linha)
trailer_lote = self.banco.registros.TrailerLoteExtrato()
lote_aberto = Lote(self.banco, header_lote, trailer_lote)
self._lotes.append(lote_aberto)
elif tipo_registro == '3':
tipo_segmento = linha[13]
codigo_evento = linha[15:17]
if tipo_segmento == 'T':
seg_t = self.banco.registros.SegmentoT()
seg_t.carregar(linha)
evento_aberto = Evento(self.banco, int(codigo_evento))
lote_aberto._eventos.append(evento_aberto)
evento_aberto._segmentos.append(seg_t)
elif tipo_segmento == 'U':
seg_u = self.banco.registros.SegmentoU()
seg_u.carregar(linha)
evento_aberto._segmentos.append(seg_u)
evento_aberto = None
elif tipo_segmento == 'E':
seg_e = self.banco.registros.SegmentoE()
seg_e.carregar(linha)
if codigo_evento == ' ':
codigo_evento = 0
evento_aberto = Evento(self.banco, int(codigo_evento))
lote_aberto._eventos.append(evento_aberto)
evento_aberto._segmentos.append(seg_e)
elif tipo_registro == '5':
if trailer_lote is not None:
lote_aberto.trailer.carregar(linha)
else:
raise Exception
elif tipo_registro == '9':
self.trailer = self.banco.registros.TrailerArquivo()
self.trailer.carregar(linha)
@property
def lotes(self):
return self._lotes
def incluir_evento(self, header, codigo_movimento, **kwargs):
codigo_evento = codigo_movimento
evento = Evento(self.banco, codigo_evento)
seg_p = self.banco.registros.SegmentoP(**kwargs)
evento.adicionar_segmento(seg_p)
seg_q = self.banco.registros.SegmentoQ(**kwargs)
evento.adicionar_segmento(seg_q)
seg_r = self.banco.registros.SegmentoR(**kwargs)
if seg_r.necessario():
evento.adicionar_segmento(seg_r)
lote_cobranca = self.encontrar_lote(codigo_evento)
if lote_cobranca is None:
header = self.banco.registros.HeaderLoteCobranca(**header)
trailer = self.banco.registros.TrailerLoteCobranca()
lote_cobranca = Lote(self.banco, header, trailer)
self.adicionar_lote(lote_cobranca)
if "controlecob_numero" not in dir(header):
header.controlecob_numero = int('{0}{1:02}'.format(
self.header.arquivo_sequencia,
lote_cobranca.codigo))
if "controlecob_data_gravacao" not in dir(header):
header.controlecob_data_gravacao = self.header.arquivo_data_de_geracao
lote_cobranca.adicionar_evento(evento)
# Incrementar numero de registros no trailer do arquivo
self.trailer.totais_quantidade_registros += len(evento)
def incluir_cobranca(self, header, **kwargs):
# 1 = codigo de cobranca
self.incluir_evento(header, 1, **kwargs)
def incluir_baixa(self, header, **kwargs):
# 2 = codigo de solicitacao de baixa
self.incluir_evento(header, 2, **kwargs)
def encontrar_lote(self, codigo_servico):
for lote in self.lotes:
if lote.header.servico_servico == codigo_servico:
return lote
def adicionar_lote(self, lote):
if not isinstance(lote, Lote):
raise TypeError('Objeto deve ser instancia de "Lote"')
self._lotes.append(lote)
lote.codigo = len(self._lotes)
if self.trailer is not None:
if hasattr(self.trailer, 'totais_quantidade_lotes'):
# Incrementar numero de lotes no trailer do arquivo
self.trailer.totais_quantidade_lotes += 1
if hasattr(self.trailer, 'totais_quantidade_registros'):
# Incrementar numero de registros no trailer do arquivo
self.trailer.totais_quantidade_registros += len(lote)
def escrever(self, file_):
file_.write(unicode(self).encode('ascii'))
def __unicode__(self):
if not self._lotes:
raise errors.ArquivoVazioError()
result = []
result.append(unicode(self.header))
result.extend(unicode(lote) for lote in self._lotes)
result.append(unicode(self.trailer))
# Adicionar elemento vazio para arquivo terminar com \r\n
result.append(u'')
return u'\r\n'.join(result)
def encontrar_lote_pag(self, codigo_servico):
for lote in self.lotes:
# FIXME
if codigo_servico == 20:
return lote
#
if lote.header.servico_servico == codigo_servico:
return lote
# Implementação para Pag_For
def incluir_pagamento(self, **kwargs):
# 20: PAGTO FORNECEDORES
codigo_evento = 20
evento = Evento(self.banco, codigo_evento)
t_pag_for = self.banco.registros.TransacaoPagFor(**kwargs)
evento.adicionar_segmento(t_pag_for)
lote_pag = self.encontrar_lote_pag(codigo_evento)
if lote_pag is None:
header = None
trailer = None
lote_pag = Lote(self.banco, header, trailer)
self.adicionar_lote(lote_pag)
lote_pag.adicionar_evento(evento)
# Incrementar numero de registros no trailer do arquivo
self.trailer.totais_quantidade_registros += len(evento)
class ArquivoCobranca400(object):
def __init__(self, banco, **kwargs):
"""Arquivo Cnab400."""
self._lotes = []
self.banco = banco
arquivo = kwargs.get('arquivo')
if isinstance(arquivo, (file, codecs.StreamReaderWriter)):
return self.carregar_retorno(arquivo)
self.header = self.banco.registros.HeaderArquivo(**kwargs)
self.trailer = self.banco.registros.TrailerArquivo(**kwargs)
if self.header.arquivo_data_de_geracao is None:
now = datetime.now()
self.header.arquivo_data_de_geracao = int(now.strftime("%d%m%Y"))
def carregar_retorno(self, arquivo):
lote_aberto = None
evento_aberto = None
for linha in arquivo:
tipo_registro = linha[0]
if tipo_registro == '0':
self.header = self.banco.registros.HeaderArquivo()
self.header.carregar(linha)
lote_aberto = Lote(self.banco)
self._lotes.append(lote_aberto)
elif tipo_registro == '1':
tipo_segmento = linha[0]
# codigo_evento = linha[15:17]
if tipo_segmento == '1':
trans_tipo1 = self.banco.registros.TransacaoTipo1()
trans_tipo1.carregar(linha)
evento_aberto = Evento(self.banco, 1)
lote_aberto._eventos.append(evento_aberto)
evento_aberto._segmentos.append(trans_tipo1)
evento_aberto = None
elif tipo_registro == '9':
self.trailer = self.banco.registros.TrailerArquivo()
self.trailer.carregar(linha)
@property
def lotes(self):
return self._lotes
def incluir_cobranca(self, **kwargs):
# 1 eh o codigo de cobranca
codigo_evento = 1
evento = Evento(self.banco, codigo_evento)
trans_tp1 = self.banco.registros.TransacaoTipo1(**kwargs)
evento.adicionar_segmento(trans_tp1)
lote_cobranca = self.encontrar_lote(codigo_evento)
if lote_cobranca is None:
header = None
trailer = None
lote_cobranca = Lote(self.banco, header, trailer)
self.adicionar_lote(lote_cobranca)
lote_cobranca.adicionar_evento(evento)
def encontrar_lote(self, codigo_servico):
for lote in self.lotes:
# if lote.header.codigo_servico == codigo_servico:
# return lote
return lote
def adicionar_lote(self, lote):
if not isinstance(lote, Lote):
raise TypeError('Objeto deve ser instancia de "Lote"')
self._lotes.append(lote)
lote.codigo = len(self._lotes)
if self.trailer != None:
if hasattr(self.trailer, 'totais_quantidade_lotes'):
# Incrementar numero de lotes no trailer do arquivo
self.trailer.totais_quantidade_lotes += 1
if hasattr(self.trailer, 'totais_quantidade_registros'):
# Incrementar numero de registros no trailer do arquivo
self.trailer.totais_quantidade_registros += len(lote)
def escrever(self, file_):
file_.write(unicode(self).encode('ascii'))
def __unicode__(self):
if not self._lotes:
raise errors.ArquivoVazioError()
result = []
result.append(unicode(self.header))
result.extend(unicode(lote) for lote in self._lotes)
result.append(unicode(self.trailer))
# Adicionar elemento vazio para arquivo terminar com \r\n
result.append(u'')
return u'\r\n'.join(result)