forked from sped-br/python-sped
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcampos.py
More file actions
277 lines (213 loc) · 7.31 KB
/
campos.py
File metadata and controls
277 lines (213 loc) · 7.31 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
# -*- coding: utf-8 -*-
import re
from datetime import date
from datetime import datetime
from decimal import Decimal
from .erros import CampoFixoError
from .erros import CampoObrigatorioError
from .erros import FormatoInvalidoError
class Campo(object):
"""
Classe base para definição de um campo de um registro do SPED.
>>> campo = Campo(1, 'TESTE', True)
>>> campo
<sped.campos.Campo(1, TESTE)>
>>> campo.indice
1
>>> campo.nome
'TESTE'
>>> campo.obrigatorio
True
"""
def __init__(self, indice, nome, obrigatorio=False):
self._indice = indice
self._nome = nome
self._obrigatorio = obrigatorio
def __repr__(self):
return '<%s.%s(%s, %s)>' % (self.__class__.__module__,
self.__class__.__name__,
self._indice, self._nome)
@property
def indice(self):
return self._indice
@property
def nome(self):
return self._nome
@property
def obrigatorio(self):
return self._obrigatorio
def get(self, registro):
return registro.valores[self._indice] or None
def set(self, registro, valor):
if self._obrigatorio and not valor:
raise CampoObrigatorioError(registro, self.nome)
if not valor:
registro.valores[self._indice] = ''
return
if valor and not self.__class__.validar(valor):
raise FormatoInvalidoError(registro, self.nome)
if not isinstance(valor, str):
raise FormatoInvalidoError(registro, self.nome)
registro.valores[self._indice] = valor or ''
@staticmethod
def validar(valor):
return True
class CampoFixo(Campo):
"""
Classe base para definição de um campo de um registro do SPED.
>>> campo = CampoFixo(1, 'REG', '0000')
>>> campo
<sped.campos.CampoFixo(1, REG)>
>>> campo.indice
1
>>> campo.nome
'REG'
>>> campo.obrigatorio
True
>>> campo.valor
'0000'
"""
def __init__(self, indice, nome, valor):
super().__init__(indice, nome, True)
self._valor = valor
@property
def valor(self):
return self._valor
def get(self, registro):
return self._valor
def set(self, registro, valor):
if valor != self._valor:
raise CampoFixoError(registro, self.nome)
class CampoAlfanumerico(Campo):
def __init__(self, indice, nome, obrigatorio=False, tamanho=None):
super().__init__(indice, nome, obrigatorio)
self._tamanho = tamanho
@property
def tamanho(self):
return self._tamanho
def set(self, registro, valor):
valor = valor or ''
if self._tamanho is not None:
valor = valor[:self._tamanho]
super().set(registro, valor)
class CampoBool(Campo):
def __init__(self, indice, nome, obrigatorio=False, valorVerdadeiro='S', valorFalso='N'):
super().__init__(indice, nome, obrigatorio)
self.valorVerdadeiro = valorVerdadeiro
self.valorFalso = valorFalso
def get(self, registro):
valor = super().get(registro)
if not valor:
return None
return valor == self.valorVerdadeiro
def set(self, registro, valor):
if isinstance(valor, bool):
super().set(registro, self.valorVerdadeiro if valor else self.valorFalso)
elif valor is None:
super().set(registro, None)
else:
raise FormatoInvalidoError(registro, self.nome)
class CampoNumerico(Campo):
def __init__(self, indice, nome, obrigatorio=False,
precisao=None, minimo=0, maximo=1000):
super().__init__(indice, nome, obrigatorio)
self._precisao = precisao if precisao is not None else 0
self._minimo = minimo
self._maximo = maximo
@property
def precisao(self):
return self._precisao
@property
def minimo(self):
return self._minimo
@property
def maximo(self):
return self._maximo
def get(self, registro):
valor = super().get(registro)
if not valor:
return None
return Decimal(valor.replace(',', '.'))
def set(self, registro, valor):
if isinstance(valor, str):
valor = Decimal(valor.replace(',', '.'))
if isinstance(valor, Decimal) or isinstance(valor, float):
super().set(registro, (('%.' + str(self._precisao) + 'f') % valor).replace('.', ','))
elif isinstance(valor, int):
super().set(registro, str(valor))
elif not valor:
super().set(registro, '0')
else:
raise FormatoInvalidoError(registro, self.nome)
class CampoData(Campo):
def __init__(self, indice, nome, obrigatorio=False):
super().__init__(indice, nome, obrigatorio)
def get(self, registro):
valor = super().get(registro)
if not valor:
return None
return datetime.strptime(valor, '%d%m%Y').date()
def set(self, registro, valor):
if isinstance(valor, date):
super().set(registro, valor.strftime('%d%m%Y'))
elif not valor:
super().set(registro, None)
else:
raise FormatoInvalidoError(registro, self.nome)
class CampoRegex(Campo):
def __init__(self, indice, nome, obrigatorio=False, regex=None):
super().__init__(indice, nome, obrigatorio)
self._regex = re.compile('^' + regex + '$')
def set(self, registro, valor):
if not isinstance(valor, str):
valor = str(valor)
if not valor or self._regex.match(valor):
super().set(registro, valor)
else:
raise FormatoInvalidoError(registro, str(self))
# def __repr__(self):
# return '' f'{self.__class__.__name__}({self.indice}, {self.nome}, {self._obrigatorio}, {self._regex})'
class CampoCNPJ(Campo):
@staticmethod
def validar(valor):
if len(valor) != 14:
return False
multiplicadores = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
cnpj = [int(c) for c in valor]
soma1 = sum([cnpj[i] * multiplicadores[i+1] for i in range(12)])
soma2 = sum([cnpj[i] * multiplicadores[i] for i in range(13)])
digito1 = 11 - (soma1 % 11)
digito2 = 11 - (soma2 % 11)
if digito1 >= 10:
digito1 = 0
if digito2 >= 10:
digito2 = 0
if cnpj[12] != digito1 or cnpj[13] != digito2:
return False
return True
class CampoCPF(Campo):
@staticmethod
def validar(valor):
if len(valor) != 11:
return False
multiplicadores = [11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
cpf = [int(c) for c in valor]
soma1 = sum([cpf[i] * multiplicadores[i+1] for i in range(9)])
soma2 = sum([cpf[i] * multiplicadores[i] for i in range(10)])
digito1 = 11 - (soma1 % 11)
digito2 = 11 - (soma2 % 11)
if digito1 >= 10:
digito1 = 0
if digito2 >= 10:
digito2 = 0
if cpf[9] != digito1 or cpf[10] != digito2:
return False
return True
class CampoCPFouCNPJ(Campo):
@staticmethod
def validar(valor):
if len(valor) == 14:
return CampoCNPJ.validar(valor)
if len(valor) == 11:
return CampoCPF.validar(valor)
return False