Atualiza versão do IRPF para aceitar declaração.
[cascardo/declara.git] / lib / gera.c
1 /*
2  *  Copyright (C) 2015  Thadeu Lima de Souza Cascardo <cascardo@minaslivre.org>
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 3 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License along
15  *  with this program; if not, write to the Free Software Foundation, Inc.,
16  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 #include "gera.h"
20 #include <errno.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <zlib.h>
25 #include "declaracao.h"
26 #include "cmd.h"
27 #include "rendimento.h"
28 #include "isento.h"
29 #include "pagamento.h"
30 #include "bem.h"
31 #include "dependente.h"
32 #include "totais.h"
33 #include "sistema.h"
34
35 static void gera_header(struct declaracao *dec, FILE *f)
36 {
37         fprintf(f, "IRPF    ");
38         fprintf(f, "%04d", dec->ano); /* Exercício */
39         fprintf(f, "%04d", dec->ano - 1); /* Ano base */
40         fprintf(f, "2500"); /* Código */
41         fprintf(f, "%s", dec->retifica ? "1" : "0"); /* Retificadora */
42         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
43         fprintf(f, "   "); /* Filler */
44         fprintf(f, "1"); /* Tipo NI: Pessoa Física (1) */
45         fprintf(f, "130"); /* Versão IRPF */
46         fprintf(f, "%-60.60s", dec->nome);
47         fprintf(f, "%s", dec->contribuinte.uf);
48         fprintf(f, "%s", "0000000000"); /* FIXME: hash */
49         fprintf(f, "1"); /* TODO: certificavel */
50         fprintf(f, "%-8.8s", dec->contribuinte.dn);
51         fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
52         fprintf(f, "%s", dec->restituicao ? "2" : "0"); /* TODO: resultado imposto, 2 - restituicao */
53         fprintf(f, "S"); /* TODO: gerada? */
54         fprintf(f, "%-10.10s", dec->retifica ?: ""); /* recibo retificada ex. atual */
55         fprintf(f, "2"); /* TODO: PGD */
56         fprintf(f, "%-14.14s", sistema_get_so(dec));
57         fprintf(f, "%-7.7s", sistema_get_so_versao(dec));
58         fprintf(f, "%-9.9s", sistema_get_jvm_versao(dec));
59         fprintf(f, "%-10.10s", ""); /* TODO: última declaração transmitida (pode ser vazio?) */
60         fprintf(f, "%04d", dec->contribuinte.cd_municipio);
61         fprintf(f, "%-11.11s", dec->conjuge.cpf ? : ""); /* TODO: CPF conjuge */
62         fprintf(f, "%d", dec->obrigatoria ? 1 : 0); /* obrigatoria entrega */
63         fprintf(f, "%013lld", dec->devido); /* imposto devido, carne-leao, complementar dos dependentes */
64         fprintf(f, "%-10.10s", dec->recibo ?: ""); /* recibo ex. anterior */
65         /* Indicador de segurança: 0 se retificadora, 2 se recibo
66          * anterior, se não 1. */
67         fprintf(f, "%d", dec->retifica ? 0 : (dec->recibo ? 2 : 1));
68         /* Indicador imposto pago, TODO: carnê leão e Lei 11.033. */
69         fprintf(f, "%02d", dec->retido ? 1 : 0);
70         /* Indicador imposto antecipado, TODO: carnê leão, Lei 11.033,
71          * outros. */
72         fprintf(f, "%d", dec->retido ? 1 : 0);
73         fprintf(f, "0"); /* TODO: mudanca endereco */
74         fprintf(f, "%s", dec->contribuinte.cep);
75         fprintf(f, "0"); /* TODO: debito 1a quota */
76         fprintf(f, "%-3.3s", dec->banco); /* no banco */
77         fprintf(f, "%-4.4s", dec->agencia); /* agencia */
78         fprintf(f, " "); /* TODO: filler */
79         fprintf(f, "00000000"); /* transito julgado, gravado apenas se espolio */
80         fprintf(f, "%013lld", dec->pagar); /* imposto a pagar */
81         fprintf(f, " "); /* RRA1 */
82         fprintf(f, "%-11.11s", ""); /* CPF RRA1 */
83         fprintf(f, " "); /* RRA2 */
84         fprintf(f, "%-11.11s", ""); /* CPF RRA2 */
85         fprintf(f, " "); /* RRA3 */
86         fprintf(f, "%-11.11s", ""); /* CPF RRA3 */
87         fprintf(f, " "); /* RRA4 */
88         fprintf(f, "%-11.11s", ""); /* CPF RRA4 */
89         fprintf(f, "0000000000000"); /* TODO: Doacao ECA */
90         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0)); /* TODO: CNPJ maior */
91         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 1)); /* TODO: CNPJ maior 2 */
92         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 2)); /* TODO: CNPJ maior 3 */
93         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 3)); /* TODO: CNPJ maior 4 */
94         fprintf(f, "%-11.11s", ""); /* CPF Dependente 1 */
95         fprintf(f, "%-8.8s", ""); /* DN Dependente 1 */
96         fprintf(f, "%-11.11s", ""); /* CPF Dependente 2 */
97         fprintf(f, "%-8.8s", ""); /* DN Dependente 2 */
98         fprintf(f, "%-11.11s", ""); /* CPF Dependente 3 */
99         fprintf(f, "%-8.8s", ""); /* DN Dependente 3 */
100         fprintf(f, "%-11.11s", ""); /* CPF Dependente 4 */
101         fprintf(f, "%-8.8s", ""); /* DN Dependente 4 */
102         fprintf(f, "%-11.11s", ""); /* CPF Dependente 5 */
103         fprintf(f, "%-8.8s", ""); /* DN Dependente 5 */
104         fprintf(f, "%-11.11s", ""); /* CPF Dependente 6 */
105         fprintf(f, "%-8.8s", ""); /* DN Dependente 6 */
106         /* medico maior, TODO: outros códigos */
107         fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 26, 0));
108         /* medico maior 2, TODO: outros códigos */
109         fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 26, 1));
110         fprintf(f, "%-11.11s", ""); /* CPF pensao */
111         fprintf(f, "%-11.11s", ""); /* CPF inventariante */
112         fprintf(f, "%-40.40s", dec->contribuinte.municipio);
113         fprintf(f, "%-60.60s", dec->nome);
114         fprintf(f, "%-11.11s", ""); /* CPF empregada */
115         fprintf(f, "%-12.12s", sistema_get_mac(dec));
116         fprintf(f, "%08d", 0); /* Data saída */
117         fprintf(f, "%-11.11s", ""); /* CPF procurador */
118         fprintf(f, "%03d", dec->obrigatoria); /* criterio obrigatoriedade */
119         fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* Total tributavel */
120         /* CNPJ previdencia */
121         fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 36, 0));
122         /* CNPJ previdencia 2 */
123         fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 36, 1));
124         /* Total isentos */
125         fprintf(f, "%013lld", totais_get(dec, "ISENTOS"));
126         /* Total exclusivo */
127         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS"));
128         /* Total pagamentos */
129         fprintf(f, "%013lld", totais_get(dec, "PAGAMENTOS"));
130         fprintf(f, "%-13.13s", dec->contacorrente); /* numero conta */
131         fprintf(f, "%-2.2s", dec->dvconta); /* DV conta */
132         fprintf(f, "0"); /* TODO: revalidar DV conta */
133
134         /* Mudanças de 2015 */
135
136         fprintf(f, "%02d", dec->contribuinte.natureza_ocupacao); /* natureza ocupacao */
137         fprintf(f, "%-11.11s", ""); /* CPF domestica */
138         fprintf(f, "%-11.11s", ""); /* NI domestica */
139         fprintf(f, "%-11.11s", ""); /* CPF domestica 2 */
140         fprintf(f, "%-11.11s", ""); /* NI domestica 2 */
141         fprintf(f, "%-11.11s", ""); /* CPF domestica 3 */
142         fprintf(f, "%-11.11s", ""); /* NI domestica 3 */
143         fprintf(f, "1"); /* Declaracao iniciada */
144         fprintf(f, "1"); /* Utilizou PGD */
145         fprintf(f, "0"); /* Utilizou APP */
146         fprintf(f, "0"); /* Utilizou online */
147         fprintf(f, "0"); /* Utilizou rascunho */
148         fprintf(f, "0"); /* Utilizou pre preenchida */
149         fprintf(f, "0"); /* Utilizou fontes */
150         fprintf(f, "0"); /* Utilizou plano saude */
151         fprintf(f, "0"); /* Utilizou recuperar */
152         fprintf(f, "1"); /* Declaracao iniciada */
153
154         /* Fim das mudanças de 2015 */
155
156         fprintf(f, "   "); /* Teste PGD, FILLER2 */
157 }
158
159 static void gera_contribuinte(struct declaracao *dec, FILE *f)
160 {
161         fprintf(f, "16");
162         fprintf(f, "%s", dec->cpf);
163         fprintf(f, "%-60.60s", dec->nome);
164         fprintf(f, "%-15.15s", dec->contribuinte.tipo_logradouro);
165         fprintf(f, "%-40.40s", dec->contribuinte.logradouro);
166         fprintf(f, "%-6.6s", dec->contribuinte.numero);
167         fprintf(f, "%-21.21s", dec->contribuinte.complemento);
168         fprintf(f, "%-19.19s", dec->contribuinte.bairro);
169         fprintf(f, "%-9.9s", dec->contribuinte.cep);
170         fprintf(f, "%04d", dec->contribuinte.cd_municipio);
171         fprintf(f, "%-40.40s", dec->contribuinte.municipio);
172         fprintf(f, "%-2.2s", dec->contribuinte.uf);
173         fprintf(f, "   "); /* TODO: código exterior */
174         fprintf(f, "105"); /* TODO: código país */
175         fprintf(f, "%-100.100s", ""); /* TODO: FILLER3 */
176         fprintf(f, "%-4.4s", ""); /* TODO: FILLER1 */
177         fprintf(f, "%-8.8s", ""); /* TODO: FILLER2 */
178         fprintf(f, "%-4.4s", dec->contribuinte.ddd);
179         fprintf(f, "%-9.9s", dec->contribuinte.telefone);
180         fprintf(f, "%-8.8s", dec->contribuinte.dn);
181         fprintf(f, "%-13.13s", dec->contribuinte.titulo_eleitor);
182         fprintf(f, "%03d", dec->contribuinte.ocupacao_principal);
183         fprintf(f, "%02d", dec->contribuinte.natureza_ocupacao);
184         fprintf(f, "0"); /* TODO: qnt quotas */
185         fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
186         fprintf(f, "%s", dec->retifica ? "S" : "N");
187         fprintf(f, "S"); /* GERADO */
188         fprintf(f, "N"); /* TODO: mudança de endereço */
189         fprintf(f, "%-12.12s", dec->retifica ? : ""); /* Recibo declaração original */
190         fprintf(f, "%-3.3s", dec->banco); /* banco */
191         fprintf(f, "%-4.4s", dec->agencia); /* agência */
192         fprintf(f, "N"); /* TODO: deficiência */
193         fprintf(f, "0"); /* FILLER: pré-preenchida */
194         fprintf(f, "%-13.13s", dec->contacorrente); /* conta */
195         fprintf(f, "%-2.2s", dec->dvconta); /* DV conta */
196         fprintf(f, "N"); /* TODO: débito automático */
197         fprintf(f, "0"); /* TODO: débito primeira quota */
198         /* CNPJ principal fonte */
199         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0));
200         fprintf(f, "%-10.10s", dec->recibo ?: ""); /* Recibo última declaração ano anterior */
201         fprintf(f, "A"); /* Declaração de Ajuste */
202         fprintf(f, "%-11.11s", ""); /* TODO: CPF procurador */
203 }
204
205 static void gera_simples(struct declaracao *dec, FILE *f)
206 {
207         fprintf(f, "17");
208         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
209         fprintf(f, "%013lld", 0); /* TODO: carnê leão */
210         fprintf(f, "%013lld", 0); /* TODO: lucros e dividendos */
211         /* rendimentos isentos */
212         fprintf(f, "%013lld", totais_get(dec, "ISENTOS"));
213         /* rendimentos tributação exclusiva, exceto décimo terceiro */
214         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS_SEM_13o"));
215         /* 13o. */
216         fprintf(f, "%013lld", totais_get(dec, "DECIMOTERCEIRO"));
217         fprintf(f, "%013lld", 0); /* TODO: retido na fonte (Lei 11.033) */
218         fprintf(f, "%013lld", 0); /* TODO: 13o. dependentes */
219         fprintf(f, "%013lld", 0); /* TODO: lucros dependentes */
220         fprintf(f, "%013lld", 0); /* TODO: isentos dependentes */
221         fprintf(f, "%013lld", 0); /* TODO: exclusivos dependentes */
222         fprintf(f, "%-13.13s", ""); /* FILLER */
223         fprintf(f, "%-13.13s", ""); /* FILLER */
224         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF */
225         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF dependentes */
226         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior */
227         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF ext. depend. */
228         fprintf(f, "%013lld", 0); /* TODO: carnê-leão PF? */
229         fprintf(f, "%013lld", 0); /* TODO: carnê-leão dependentes */
230         fprintf(f, "%013lld", totais_get(dec, "DEPENDENTES")); /* TODO: dedução dependentes */
231         fprintf(f, "%013lld", 0); /* TODO: previdência RRA */
232         fprintf(f, "%013lld", 0); /* TODO: previdência RRA dependentes */
233         fprintf(f, "%013lld", 0); /* TODO: pensão RRA */
234         fprintf(f, "%013lld", 0); /* TODO: pensão RRA dependentes */
235         fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
236         fprintf(f, "%013lld", 0); /* TODO: imposto devido sem rendimento exterior */
237         fprintf(f, "%013lld", 0); /* TODO: limite imposto pago exterior */
238 }
239
240 static void gera_totais_simples(struct declaracao *dec, FILE *f)
241 {
242         fprintf(f, "18");
243         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
244         fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* TODO: rendimentos tributáveis */
245         /* desconto simplificado */
246         fprintf(f, "%013lld", totais_get(dec, "DESCONTO"));
247          /* base de cálculo */
248         fprintf(f, "%013lld", totais_get(dec, "BASE"));
249         fprintf(f, "%013lld", dec->devido); /* imposto devido */
250         fprintf(f, "%013lld", dec->retido); /* imposto retido */
251         fprintf(f, "%013lld", 0); /* TODO: imposto complementar */
252         fprintf(f, "%013lld", 0); /* TODO: carnê-leão */
253         fprintf(f, "%013lld", 0); /* TODO: imposto retido Lei 11.033 */
254         fprintf(f, "%013lld", dec->restituicao); /* imposto a restituir */
255         fprintf(f, "%013lld", dec->pagar); /* imposto pagar */
256         fprintf(f, "%d", 0); /* TODO: quotas */
257         fprintf(f, "%013lld", 0); /* TODO: valor quota */
258         fprintf(f, "%013lld", totais_get(dec, "ISENTOS")); /* rendimentos isentos */
259         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS")); /* rendimentos tributação exclusiva */
260         fprintf(f, "%013lld", dec->conjuge.total); /* TODO: conjuge */
261         fprintf(f, "%013lld", 0); /* TODO: rendimento PJ dependente */
262         fprintf(f, "%013lld", 0); /* TODO: imposto retido dependente */
263         fprintf(f, "%013lld", 0); /* TODO: imposto ganhos de capital */
264         fprintf(f, "%013lld", totais_get(dec, "RENDPJTIT")); /* rendimento tributável PJ titular */
265         fprintf(f, "%013lld", 0); /* TODO: total rural */
266         fprintf(f, "%013lld", dec->retido); /* imposto retido titular */
267         fprintf(f, "%013lld", totais_get(dec, "BENSANTERIOR")); /* total bens ano anterior */
268         fprintf(f, "%013lld", totais_get(dec, "BENS")); /* total bens ano base */
269         fprintf(f, "%013lld", totais_get(dec, "ISENTOSTIT")); /* rendimentos isentos titular */
270         fprintf(f, "%013lld", 0); /* TODO: rendimentos isentos dependentes */
271         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSTIT")); /* TODO: tributação exclusiva titular */
272         fprintf(f, "%013lld", 0); /* TODO: tributação exclusiva dependentes */
273         fprintf(f, "%013lld", 0); /* TODO: total não tributável */
274         fprintf(f, "%013lld", 0); /* TODO: total dívidas ano anterior */
275         fprintf(f, "%013lld", 0); /* TODO: total dívidas ano base */
276         fprintf(f, "%013lld", 0); /* TODO: retido fonte Lei 11.033 */
277         fprintf(f, "%013lld", 0); /* TODO: isentos e não tributáveis, transportado */
278         fprintf(f, "%013lld", 0); /* TODO: tributação exclusiva, transportado */
279         fprintf(f, "%013lld", 0); /* TODO: ganhos líquidos renda variável */
280         fprintf(f, "%013lld", 0); /* TODO: parcela isenta ganhos capital */
281         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior titular */
282         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior dependentes */
283         fprintf(f, "%013lld", 0); /* TODO: doações campanha */
284         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa titular */
285         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa dependentes */
286         fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa titular */
287         fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa dependentes */
288         fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA titular */
289         fprintf(f, "%013lld", 0); /* TODO: IRF RRA titular */
290         fprintf(f, "%013lld", 0); /* TODO: imposto RRA titular */
291         fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA dependentes */
292         fprintf(f, "%013lld", 0); /* TODO: IRF RRA dependentes */
293         fprintf(f, "%013lld", 0); /* TODO: imposto RRA dependentes */
294         fprintf(f, "%013lld", dec->devido); /* imposto devido */
295         fprintf(f, "%013lld", 0); /* TODO: imposto diferido ganho capital */
296         fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital */
297         fprintf(f, "%013lld", 0); /* TODO: imposto ganho líquido renda variável */
298         fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital moeda estrangeira */
299         fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
300 }
301
302 static void gera_completa(struct declaracao *dec, FILE *f)
303 {
304         fprintf(f, "19");
305         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
306         fprintf(f, "%-14.14s", ""); /* TODO: CNPJ maior */
307         /* FIXME: completar campos */
308 }
309
310 static void gera_totais_completa(struct declaracao *dec, FILE *f)
311 {
312         fprintf(f, "20");
313         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
314         /* FIXME: completar campos */
315 }
316
317 static void gera_isentos(struct declaracao *dec, FILE *f)
318 {
319         fprintf(f, "23");
320         fprintf(f, "%-11.11s", dec->cpf);
321         fprintf(f, "%013lld", 0); /* TODO: bolsa de estudo */
322         fprintf(f, "%013lld", 0); /* TODO: pecúlio de previdência privada */
323         fprintf(f, "%013lld", 0); /* TODO: FGTS, aviso prévio indenizado */
324         fprintf(f, "%013lld", 0); /* TODO: ganho de capital isento */
325         fprintf(f, "%013lld", 0); /* TODO: lucros e dividendos */
326         fprintf(f, "%013lld", 0); /* TODO: atividade rural */
327         fprintf(f, "%013lld", 0); /* TODO: contribuintes com 65 anos ou mais */
328         fprintf(f, "%013lld", 0); /* TODO: pensão por invalidez */
329         fprintf(f, "%013lld", totais_get(dec, "POUPANCA"));
330         fprintf(f, "%013lld", 0); /* TODO: sócio ou titular de empresa */
331         fprintf(f, "%013lld", 0); /* TODO: herança, transferências patrimoniais */
332         fprintf(f, "%013lld", 0); /* TODO: outros rendimentos isentos */
333         fprintf(f, "%-60.60s", ""); /* FILLER1 */
334         fprintf(f, "%-13.13s", ""); /* FILLER2 */
335         fprintf(f, "%013lld", 0); /* TODO: alienação bens pequeno valor */
336         fprintf(f, "%013lld", 0); /* TODO: alienação único imóvel */
337         fprintf(f, "%013lld", 0); /* TODO: redução ganho capital */
338         fprintf(f, "%013lld", 0); /* TODO: total bens pequeno valor, transportado GC */
339         fprintf(f, "%013lld", 0); /* TODO: alienção único imóvel, transportado GC */
340         fprintf(f, "%013lld", 0); /* TODO: redução ganho capital, transportado GC */
341         fprintf(f, "%013lld", 0); /* TODO: ganho capital - moeda estrangeira */
342         fprintf(f, "%013lld", 0); /* TODO: ganho capital - moeda estrangeira, transportado */
343         fprintf(f, "%013lld", 0); /* TODO: GC total informado */
344         fprintf(f, "%013lld", 0); /* TODO: GC total transportado */
345         fprintf(f, "%013lld", 0); /* TODO: imposto renda anos anteriores */
346         fprintf(f, "%013lld", 0); /* TODO: rencimentos assalariados moeda estrangeira */
347         fprintf(f, "%013lld", 0); /* TODO: bonificações ações */
348         fprintf(f, "%013lld", 0); /* TODO: médicos residentes */
349         fprintf(f, "%013lld", 0); /* TODO: volutários da Copa */
350         fprintf(f, "%013lld", 0); /* TODO: meação e dissolução */
351         fprintf(f, "%013lld", 0); /* TODO: ganhos líquidos com ações */
352         fprintf(f, "%013lld", 0); /* TODO: ganhos de capital com ouro */
353         fprintf(f, "%013lld", 0); /* TODO: recuperação prejuízos na bolsa */
354         fprintf(f, "%013lld", 0); /* TODO: transportador de cargas */
355         fprintf(f, "%013lld", 0); /* TODO: transportador de passageiros */
356         fprintf(f, "%013lld", 0); /* TODO: retistuição imposto anos anteriores */
357 }
358
359 static void gera_exclusivos(struct declaracao *dec, FILE *f)
360 {
361         fprintf(f, "24");
362         fprintf(f, "%-11.11s", dec->cpf);
363         fprintf(f, "%013lld", totais_get(dec, "DECIMOTERCEIRO"));
364         fprintf(f, "%013lld", 0); /* TODO: ganho de capital */
365         fprintf(f, "%013lld", 0); /* TODO: ganho líquido renda variável */
366         fprintf(f, "%013lld", totais_get(dec, "APLICACOES")); /* TODO: aplicações financeiras */
367         fprintf(f, "%013lld", 0); /* TODO: outros */
368         fprintf(f, "%-60.60s", ""); /* FILLER1 */
369         fprintf(f, "%013lld", 0); /* TODO: ganhos de capital alienação de bens */
370         fprintf(f, "%013lld", 0); /* TODO: ganhos de capital moeda estrangeira */
371         fprintf(f, "%013lld", 0); /* TODO: décimo terceiro dependentes */
372         fprintf(f, "%-13.13s", ""); /* FILLER2 */
373         fprintf(f, "%-60.60s", ""); /* FILLER3 */
374         fprintf(f, "%013lld", 0); /* TODO: RRA */
375         fprintf(f, "%013lld", 0); /* TODO: RRA dependentes */
376         fprintf(f, "%013lld", 0); /* TODO: Juros capital próprio */
377         fprintf(f, "%013lld", totais_get(dec, "PLR"));
378 }
379
380 static void gera_conjuge(struct declaracao *dec, FILE *f)
381 {
382         fprintf(f, "29");
383         fprintf(f, "%-11.11s", dec->cpf);
384         fprintf(f, "%-11.11s", dec->conjuge.cpf);
385         fprintf(f, "%013lld", dec->conjuge.base);
386         fprintf(f, "%013lld", dec->conjuge.imposto);
387         fprintf(f, "%013lld", dec->conjuge.isento);
388         fprintf(f, "%013lld", dec->conjuge.exclusivo);
389         fprintf(f, "%013lld", dec->conjuge.rendpj_exigibilidade_suspensa);
390         fprintf(f, "%013lld", dec->conjuge.total);
391         fprintf(f, "%c", dec->conjuge.entregou ? 'S' : 'N');
392 }
393
394 static void gera_trailler(struct declaracao *dec, FILE *f)
395 {
396         int i;
397         fprintf(f, "T9");
398         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
399         fprintf(f, "%06d", dec->linhas[0]);
400         for (i = 16; i < 100; i++)
401                 if (i == 44)
402                         fprintf(f, "%-5.5s", "0"); /* FILLER */
403                 else if (i == 49 || i == 57 || i == 64 || i == 79)
404                         ;
405                 else
406                         fprintf(f, "%05d", dec->linhas[i]);
407 }
408
409 static void gera_reciboheader(struct declaracao *dec, FILE *f)
410 {
411         fprintf(f, "HR");
412         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
413         fprintf(f, "%-3.3s", ""); /* FILLER */
414 }
415
416 static void gera_recibodetalhe(struct declaracao *dec, FILE *f)
417 {
418         fprintf(f, "DR");
419         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
420         fprintf(f, "%-3.3s", ""); /* FILLER */
421         fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
422         fprintf(f, "%-60.60s", dec->nome);
423         fprintf(f, "%-15.15s", dec->contribuinte.tipo_logradouro);
424         fprintf(f, "%-40.40s", dec->contribuinte.logradouro);
425         fprintf(f, "%-6.6s", dec->contribuinte.numero);
426         fprintf(f, "%-21.21s", dec->contribuinte.complemento);
427         fprintf(f, "%-19.19s", dec->contribuinte.bairro);
428         fprintf(f, "%-9.9s", dec->contribuinte.cep);
429         fprintf(f, "%04d", dec->contribuinte.cd_municipio);
430         fprintf(f, "%-40.40s", dec->contribuinte.municipio);
431         fprintf(f, "%-2.2s", dec->contribuinte.uf);
432         fprintf(f, "%-100.100s", ""); /* FILLER */
433         fprintf(f, "%-4.4s", ""); /* FILLER */
434         fprintf(f, "%-8.8s", ""); /* FILLER */
435         fprintf(f, "%-4.4s", dec->contribuinte.ddd);
436         fprintf(f, "%-9.9s", dec->contribuinte.telefone);
437         fprintf(f, "%s", dec->retifica ? "S" : "N"); /* Retificadora */
438         fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* Total tributavel */
439         fprintf(f, "%013lld", dec->devido); /* Imposto devido */
440         fprintf(f, "%013lld", dec->restituicao); /* Imposto a restituir */
441         fprintf(f, "%013lld", dec->pagar); /* Imposto a pagar */
442         fprintf(f, "%d", 0); /* TODO: quotas */
443         fprintf(f, "%013lld", 0); /* TODO: valor quota */
444         fprintf(f, "%-3.3s", dec->banco); /* numero banco */
445         fprintf(f, "%-4.4s", dec->agencia); /* numero agencia */
446         fprintf(f, " "); /* FILLER */
447         fprintf(f, "%d", 0); /* TODO: debito primeira quota */
448         fprintf(f, "%013lld", 0); /* TODO: imposto pago ganho de capital */
449         fprintf(f, "%-13.13s", dec->contacorrente); /* numero conta */
450         fprintf(f, "%-2.2s", dec->dvconta); /* DV conta */
451         fprintf(f, "%013lld", 0); /* TODO: imposto alienacao moeda estrangeira em especie */
452 }
453
454 static void gera_recibotrailler(struct declaracao *dec, FILE *f)
455 {
456         fprintf(f, "R9");
457         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
458         fprintf(f, "%-3.3s", ""); /* FILLER */
459         fprintf(f, "%010u", dec->rhash);
460 }
461
462 static void gera_rendimento(struct declaracao *dec, FILE *f)
463 {
464         struct rendimento *r;
465         r = list_get(dec->rendimento, dec->linhas[21]);
466         fprintf(f, "21");
467         fprintf(f, "%s", dec->cpf);
468         fprintf(f, "%-14.14s", r->cnpj);
469         fprintf(f, "%-60.60s", r->nome);
470         fprintf(f, "%013lld", r->rendimento);
471         fprintf(f, "%013lld", r->previdencia);
472         fprintf(f, "%013lld", r->decimoterceiro);
473         fprintf(f, "%013lld", r->imposto);
474         fprintf(f, "%-8.8s", r->saida);
475         fprintf(f, "%013lld", r->imposto_13o);
476 }
477
478 static void gera_pagamento(struct declaracao *dec, FILE *f)
479 {
480         struct pagamento *p;
481         p = list_get(dec->pagamentos, dec->linhas[26]);
482         fprintf(f, "26");
483         fprintf(f, "%s", dec->cpf);
484         fprintf(f, "%02d", p->codigo);
485         fprintf(f, "%05d", 0); /* TODO: chave dependente */
486         fprintf(f, "%-14.14s", p->cnpj);
487         fprintf(f, "%-60.60s", p->nome);
488         fprintf(f, "%-11.11s", ""); /* TODO: NIT */
489         fprintf(f, "%013lld", p->pagamento);
490         fprintf(f, "%013lld", p->reembolso);
491         /* CPF (1?) ou CNPJ (2), FIXME */
492         fprintf(f, "2");
493         /* Titular (T), Dependente (D), Alimentando (A), FIXME */
494         fprintf(f, "T");
495 }
496
497 static void gera_isento(struct declaracao *dec, FILE *f, int codigo)
498 {
499         struct isento *i;
500         i = isento_get(dec, codigo, dec->linhas[codigo]);
501         fprintf(f, "%02d", codigo);
502         fprintf(f, "%-11.11s", dec->cpf); /* Titular, TODO: dependente */
503         fprintf(f, "%05d", dec->linhas[codigo] + 1); /* Chave */
504         fprintf(f, "%c", 'T'); /* FIXME: dependente */
505         fprintf(f, "%-14.14s", i->cnpj);
506         fprintf(f, "%-60.60s", i->nome);
507         fprintf(f, "%013lld", i->valor);
508         fprintf(f, "%-11.11s", dec->cpf);
509 }
510
511 static void gera_plr(struct declaracao *dec, FILE *f)
512 {
513         gera_isento(dec, f, 96);
514 }
515
516 static void gera_poupanca(struct declaracao *dec, FILE *f)
517 {
518         gera_isento(dec, f, 98);
519 }
520
521 static void gera_aplicacoes(struct declaracao *dec, FILE *f)
522 {
523         gera_isento(dec, f, 99);
524 }
525
526 static void gera_dependente(struct declaracao *dec, FILE *f)
527 {
528         struct dependente *d;
529         d = list_get(dec->dependentes, dec->linhas[25]);
530
531         fprintf(f, "25");
532         fprintf(f, "%s", dec->cpf);
533         fprintf(f, "%05d", dec->linhas[25] + 1);
534         fprintf(f, "%02d", d->codigo);
535         fprintf(f, "%-60.60s", d->nome);
536         fprintf(f, "%-8.8s", d->dn);
537         fprintf(f, "%-11.11s", d->cpf);
538         /* TODO: Indicador de saída */
539         fprintf(f, " ");
540 }
541
542 static void gera_bem(struct declaracao *dec, FILE *f)
543 {
544         struct bem *b;
545         b = list_get(dec->bens, dec->linhas[27]);
546
547         fprintf(f, "27");
548         fprintf(f, "%s", dec->cpf);
549         fprintf(f, "%02d", b->codigo);
550
551         /* FIXME: exterior */
552         fprintf(f, "0");
553         fprintf(f, "105"); /* código Brasil */
554
555         fprintf(f, "%-512.512s", b->descricao);
556         fprintf(f, "%013lld", b->valor_anterior);
557         fprintf(f, "%013lld", b->valor);
558
559         /* Imóvel */
560         fprintf(f, "%-40.40s", b->logradouro ?: "");
561         fprintf(f, "%-6.6s", b->numero ?: "");
562         fprintf(f, "%-40.40s", b->complemento ?: "");
563         fprintf(f, "%-40.40s", b->bairro ?: "");
564         fprintf(f, "%-9.9s", b->cep ?: "");
565         fprintf(f, "%-2.2s", b->uf ?: "");
566         fprintf(f, "%04d", b->cd_municipio);
567         fprintf(f, "%-40.40s", b->municipio ?: "");
568         /* FIXME: Registro de imóveis, Nao (0), Sim (1), Vazio (2) */
569         fprintf(f, "%d", b->registro ? 1 : 0);
570         fprintf(f, "%-40.40s", b->matricula ?: "");
571         fprintf(f, "%-40.40s", b->registro ?: "");
572         fprintf(f, "%011lld", b->area);
573         /* FIXME: Area, M2 (0), Ha (1), Vazio (2) */
574         fprintf(f, "%d", 0);
575         fprintf(f, "%-60.60s", b->cartorio ?: "");
576
577         /* Número de chave */
578         fprintf(f, "%05d", dec->linhas[27] + 1);
579 }
580
581 typedef void (gera_linha)(struct declaracao *dec, FILE *f);
582
583 static void update_hash(struct declaracao *dec, char *buf, size_t len)
584 {
585         int r;
586         int linha;
587         r = sscanf(buf, "%2d", &linha);
588         if (r == 1 || !strncmp(buf, "T9", 2)) {
589                 dec->hash = crc32(dec->hash, buf, len - 2);
590                 dec->rhash = crc32(dec->rhash, buf, len - 2);
591                 return;
592         } else if (strncmp(buf, "R9", 2) && strncmp(buf, "IRPF", 4)) {
593                 dec->rhash = crc32(dec->rhash, buf, len - 2);
594         }
595 }
596
597 static int wrap(gera_linha fn, struct declaracao *dec, struct list *l)
598 {
599         FILE *m;
600         char *buf = NULL;
601         size_t bsize;
602         int linha;
603         int r;
604         uLong c = crc32(0L, Z_NULL, 0);
605         m = open_memstream(&buf, &bsize);
606         if (!m) {
607                 return -errno;
608         }
609         fn(dec, m);
610         dec->linhas[0]++;
611         fflush(m);
612
613         /* Calcula CRC32 para campo de controle dos registros. */
614         c = crc32(c, buf, bsize);
615         fprintf(m, "%010ld\r\n", c);
616
617         fclose(m);
618         r = sscanf(buf, "%2d", &linha);
619         if (r == 1 && linha >= 0 && linha < 100) {
620                 dec->linhas[linha]++;
621         }
622         update_hash(dec, buf, bsize);
623         return list_add(&l, buf);
624 }
625
626 static void insert_hash(struct declaracao *dec, char *irpf)
627 {
628         uLong c = crc32(0L, NULL, 0);
629         char cpf[13];
630         char crc[11];
631         snprintf(cpf, 13, "%-8.8s.DEC", dec->cpf);
632         c = crc32(c, cpf, 12);
633         snprintf(crc, 11, "%010ld", dec->hash);
634         memcpy(irpf + 101, crc, 10);
635         c = crc32(c, irpf, strlen(irpf) - 12);
636         snprintf(crc, 11, "%010ld", c);
637         memcpy(irpf + strlen(irpf) - 12, crc, 10);
638 }
639
640 static int gera(struct declaracao *dec, char *filename)
641 {
642         FILE *f;
643         int r;
644         int i;
645         struct rendimento *rendimento;
646         struct isento *isento;
647         struct pagamento *pagamento;
648         struct bem *bem;
649         struct dependente *dependente;
650         struct list *linhas;
651         char *buf;
652
653         linhas = list_new();
654         if (!linhas)
655                 return -ENOMEM;
656
657         dec->hash = crc32(0L, NULL, 0);
658         dec->rhash = crc32(0L, NULL, 0);
659
660 #define W(fn) \
661         do { \
662                 r = wrap(fn, dec, linhas); \
663                 if (r < 0) \
664                         goto out; \
665         } while (0);
666
667         f = fopen(filename, "w");
668         if (!f)
669                 goto out_file;
670         memset(dec->linhas, 0, sizeof(dec->linhas));
671         W(gera_header);
672         W(gera_contribuinte);
673         if (dec->tipo == COMPLETA) {
674                 W(gera_completa);
675                 W(gera_totais_completa);
676         } else {
677                 W(gera_simples);
678                 W(gera_totais_simples);
679         }
680         for (i = 0; rendimento = list_get(dec->rendimento, i); i++) {
681                 W(gera_rendimento);
682         }
683
684         W(gera_isentos);
685         W(gera_exclusivos);
686
687         for (i = 0; (dependente = list_get(dec->dependentes, i)); i++) {
688                 W(gera_dependente);
689         }
690         for (i = 0; (pagamento = list_get(dec->pagamentos, i)); i++) {
691                 W(gera_pagamento);
692         }
693         for (i = 0; (bem = list_get(dec->bens, i)); i++) {
694                 W(gera_bem);
695         }
696
697         W(gera_conjuge);
698
699         /* Rendimentos isentos e com tributação exclusiva */
700         /* Registros 82 a 89, e 92 a 99 */
701 #define IW(fn, codigo) \
702         for (i = 0; ; i++) { \
703                 isento = isento_get(dec, codigo, i); \
704                 if (!isento) \
705                         break; \
706                 W(fn); \
707         }
708         IW(gera_plr, 96);
709         IW(gera_poupanca, 98);
710         IW(gera_aplicacoes, 99);
711
712         W(gera_trailler);
713         W(gera_reciboheader);
714         W(gera_recibodetalhe);
715         W(gera_recibotrailler);
716
717         insert_hash(dec, list_get(linhas, 0));
718         for (i = 0; (buf = list_get(linhas, i)); i++) {
719                 fwrite(buf, strlen(buf), 1, f);
720         }
721
722         fclose(f);
723         list_free(linhas, free);
724         return 0;
725 out:
726         fclose(f);
727 out_file:
728         list_free(linhas, free);
729         return r;
730 }
731
732 static int run_gera(struct declaracao *dec, char **args, int argc)
733 {
734         if (argc != 2)
735                 return -EINVAL;
736         return gera(dec, args[1]);
737 }
738
739 static struct cmd cmd_gera = {
740         .name = "gera",
741         .run = run_gera,
742 };
743
744 int gera_cmd_init(void)
745 {
746         cmd_add(&cmd_gera);
747         return 0;
748 }