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