3 # Copyright 2013 Thadeu Lima de Souza Cascardo <cascardo@cascardo.info>
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 # -*- mode: python; encoding: utf-8; -*-
18 import xml.dom.minidom
23 def __init__(self, cpf):
24 irpf_dir = dirs.get_default_irpf_dir()
25 self.cpf = self._minimize_cpf(cpf)
27 if not self._validate_cpf(self.cpf):
28 raise RuntimeError("Invalid CPF: " + self.cpf)
30 if not os.path.exists(irpf_dir.get_resource_dir()):
31 raise RuntimeError("O caminho para o resource não existe: " + \
32 irpf_dir.get_resource_dir())
34 if not os.path.exists(irpf_dir.get_userdata_dir()):
35 raise RuntimeError("O caminho para os dados não existe: " + \
36 irpf_dir.get_userdata_dir())
38 self.cpf_file = irpf_dir.get_userdata_file("%s/%s.xml" % (self.cpf, self.cpf))
39 self.iddecl_file = irpf_dir.get_userdata_file("iddeclaracoes.xml")
40 self.declaracao = self._find_id()
41 self.dados = xml.dom.minidom.parse(self.cpf_file)
42 self.contribuinte = self.dados.getElementsByTagName("contribuinte")[0]
45 cpf = self._normalize_cpf(self.cpf)
46 self.declaracoes = xml.dom.minidom.parse(self.iddecl_file)
47 for i in self.declaracoes.getElementsByTagName("item"):
48 if "cpf" in i.attributes.keys():
49 if i.attributes["cpf"].nodeValue == cpf:
53 # CPF normalizado se parece com 000.000.000-00
54 def _normalize_cpf(self, cpf):
57 if len(ncpf) == 3 or len(ncpf) == 7:
63 if ord(i) >= ord('0') and ord(i) <= ord('9'):
66 raise RuntimeError("Invalid CPF")
69 # CPF minimizado se parece com 01234567890
70 def _minimize_cpf(self, cpf):
71 return self._minimize_valor(cpf)
73 def _minimize_valor(self, valor):
74 nvalor = ''.join(e for e in valor if e.isalnum())
77 def _validate_cpf(self, cpf):
80 return self._validate_generico(cpf)
82 def _validate_generico(self, valor):
83 def calcula_digito_verificador(numero):
88 if i > len(numero) - 1:
90 soma = soma + int(numero[i]) * ( n - i)
99 return numero + str(dv)
101 mcpf = self._minimize_valor(valor)
102 cpf_sem_dv = mcpf[:-2]
104 primeiro_dv = str(calcula_digito_verificador(cpf_sem_dv))
105 segundo_dv = calcula_digito_verificador(primeiro_dv)
107 return segundo_dv == mcpf
110 self.dados.writexml(open(self.cpf_file, "w"))
111 self.declaracoes.writexml(open(self.iddecl_file, "w"))
113 def _get_attr(self, el, attr):
114 if attr in el.attributes.keys():
115 return el.attributes[attr].nodeValue
118 def _set_attr(self, el, attr, val):
119 el.attributes[attr].nodeValue = val
121 def get_declaracao(self, attr):
122 return self._get_attr(self.declaracao, attr)
124 def set_declaracao(self, attr, val):
125 self._set_attr(self.declaracao, attr, val)
128 return self.get_declaracao("nome")
130 def set_nome(self, nome):
131 self.set_declaracao("nome", nome)
133 def get_campo_contribuinte(self, attr):
135 return self.get_nome()
136 return self._get_attr(self.contribuinte, attr)
138 def set_campo_contribuinte(self, attr, val):
142 self._set_attr(self.contribuinte, attr, val)
144 contribuinte_attributes = [
172 declaracao_attributes = [
174 "declaracaoRetificadora",
180 "numeroReciboDecAnterior",
181 "resultadoDeclaracao",
188 if __name__ == '__main__':
190 contribuinte = Contribuinte(sys.argv[1])
191 print "Carregando CPF " + contribuinte._normalize_cpf(sys.argv[1])
193 if len(sys.argv) == 4:
194 print "Valor anterior: " + contribuinte.get_campo_contribuinte(sys.argv[2])
195 contribuinte.set_campo_contribuinte(sys.argv[2], sys.argv[3])
196 print "Valor atual: " + contribuinte.get_campo_contribuinte(sys.argv[2])
199 elif len(sys.argv) == 3:
201 valor = contribuinte.get_campo_contribuinte(campo)
203 print ("Valor de " + campo + ": " + valor)
205 print ("Campo " + campo + " retornou vazio")
207 print "\nCONTRIBUINTE:"
208 for i in contribuinte_attributes:
209 val = contribuinte.get_campo_contribuinte(i)
213 print "\nDECLARACAO:"
214 for i in declaracao_attributes:
215 val = contribuinte.get_declaracao(i)
220 # vim:tabstop=4:expandtab:smartindent