07692db78fc520f781cd34a5de0e802909f1baa8
[cascardo/declara.git] / lib / gera.c
1 /*
2  *  Copyright (C) 2015-2017  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 "carne.h"
29 #include "isento.h"
30 #include "pagamento.h"
31 #include "bem.h"
32 #include "dependente.h"
33 #include "totais.h"
34 #include "sistema.h"
35 #include "ano.h"
36
37 static void gera_header(struct declaracao *dec, FILE *f)
38 {
39         int i;
40
41         fprintf(f, "IRPF    ");
42         fprintf(f, "%04d", dec->ano); /* Exercício */
43         fprintf(f, "%04d", dec->ano - 1); /* Ano base */
44         if (dec->ano == 2015)
45                 fprintf(f, "2500"); /* Código */
46         else if (dec->ano == 2016)
47                 fprintf(f, "2600"); /* Código */
48         else if (dec->ano == 2017)
49                 fprintf(f, "2700"); /* Código */
50         else if (dec->ano == 2018)
51                 fprintf(f, "2800"); /* Código */
52         else if (dec->ano == 2019)
53                 fprintf(f, "2900"); /* Código */
54         fprintf(f, "%s", dec->retifica ? "1" : "0"); /* Retificadora */
55         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
56         fprintf(f, "   "); /* Filler */
57         fprintf(f, "1"); /* Tipo NI: Pessoa Física (1) */
58         if (dec->ano == 2015)
59                 fprintf(f, "130"); /* Versão IRPF */
60         else if (dec->ano == 2016)
61                 fprintf(f, "110"); /* Versão IRPF */
62         else if (dec->ano == 2017)
63                 fprintf(f, "130"); /* Versão IRPF */
64         else if (dec->ano == 2018)
65                 fprintf(f, "160"); /* Versão IRPF */
66         else if (dec->ano == 2019)
67                 fprintf(f, "150"); /* Versão IRPF */
68         fprintf(f, "%-60.60s", dec->nome);
69         fprintf(f, "%-2.2s", dec->contribuinte.uf ?: "");
70         fprintf(f, "%s", "0000000000"); /* FIXME: hash */
71         fprintf(f, "1"); /* TODO: certificavel */
72         fprintf(f, "%-8.8s", dec->contribuinte.dn ?: "");
73         fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
74         /* TODO: resultado imposto, 1 - pagar, 2 - restituicao */
75         fprintf(f, "%s", dec->restituicao ? "2" : (dec->pagar ? "1" : "0"));
76         fprintf(f, "S"); /* TODO: gerada? */
77         fprintf(f, "%-10.10s", dec->retifica ?: ""); /* recibo retificada ex. atual */
78         fprintf(f, "2"); /* TODO: PGD */
79         fprintf(f, "%-14.14s", sistema_get_so(dec));
80         fprintf(f, "%-7.7s", sistema_get_so_versao(dec));
81         fprintf(f, "%-9.9s", sistema_get_jvm_versao(dec));
82         fprintf(f, "%-10.10s", ""); /* TODO: última declaração transmitida (pode ser vazio?) */
83         fprintf(f, "%04d", dec->contribuinte.cd_municipio);
84         fprintf(f, "%-11.11s", dec->conjuge.cpf ? : ""); /* TODO: CPF conjuge */
85         fprintf(f, "%d", dec->obrigatoria ? 1 : 0); /* obrigatoria entrega */
86         fprintf(f, "%013lld", dec->devido); /* imposto devido, carne-leao, complementar dos dependentes */
87         fprintf(f, "%-10.10s", dec->recibo ?: ""); /* recibo ex. anterior */
88         /* Indicador de segurança: 0 se retificadora, 2 se recibo
89          * anterior, se não 1. */
90         fprintf(f, "%d", dec->retifica ? 0 : (dec->recibo ? 2 : 1));
91         /* Indicador imposto pago, TODO: carnê leão e Lei 11.033. */
92         fprintf(f, "%02d", totais_get(dec, "CARNE") > 0 ? 7 :
93                                                         (dec->retido ? 1 : 0));
94         /* Indicador imposto antecipado, TODO: carnê leão, Lei 11.033,
95          * outros. */
96         fprintf(f, "%d", dec->retido ? 1 : 0);
97         fprintf(f, "0"); /* TODO: mudanca endereco */
98         fprintf(f, "%-8.8s", dec->contribuinte.cep ?: "");
99         fprintf(f, "0"); /* TODO: debito 1a quota */
100         fprintf(f, "%-3.3s", dec->banco ? : "000"); /* no banco */
101         fprintf(f, "%-4.4s", dec->agencia ? : "0000"); /* agencia */
102         fprintf(f, " "); /* TODO: filler */
103         fprintf(f, "00000000"); /* transito julgado, gravado apenas se espolio */
104         fprintf(f, "%013lld", dec->pagar); /* imposto a pagar */
105         fprintf(f, " "); /* RRA1 */
106         fprintf(f, "%-11.11s", ""); /* CPF RRA1 */
107         fprintf(f, " "); /* RRA2 */
108         fprintf(f, "%-11.11s", ""); /* CPF RRA2 */
109         fprintf(f, " "); /* RRA3 */
110         fprintf(f, "%-11.11s", ""); /* CPF RRA3 */
111         fprintf(f, " "); /* RRA4 */
112         fprintf(f, "%-11.11s", ""); /* CPF RRA4 */
113         fprintf(f, "0000000000000"); /* TODO: Doacao ECA */
114         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0)); /* CNPJ maior */
115         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 1)); /* CNPJ maior 2 */
116         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 2)); /* CNPJ maior 3 */
117         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 3)); /* CNPJ maior 4 */
118         if (dec->ano < 2017 || dec->ano >= 2019) {
119                 /* CPF e DN de dependentes 1 a 6 */
120                 for (i = 1; i <= 6; i++) {
121                         struct dependente *dependente = list_get(dec->dependentes, i - 1);
122                         if (dependente && dependente->cpf && dependente->cpf[0]) {
123                                 fprintf(f, "%-11.11s", dependente->cpf);
124                         } else {
125                                 fprintf(f, "%-11.11s", "");
126                         }
127                         if (dependente && dependente->dn && dependente->dn[0]) {
128                                 fprintf(f, "%-8.8s", dependente->dn);
129                         } else {
130                                 fprintf(f, "%-8.8s", "");
131                         }
132                 }
133         } else {
134                 fprintf(f, "%-114.114s", "");
135         }
136         /* medico maior, TODO: outros códigos */
137         fprintf(f, "%-14.14s", medico_cnpj_ordenado(dec, 0));
138         /* medico maior 2, TODO: outros códigos */
139         fprintf(f, "%-14.14s", medico_cnpj_ordenado(dec, 1));
140         fprintf(f, "%-11.11s", ""); /* CPF pensao */
141         fprintf(f, "%-11.11s", ""); /* CPF inventariante */
142         fprintf(f, "%-40.40s", dec->contribuinte.municipio);
143         fprintf(f, "%-60.60s", dec->nome);
144         if (dec->ano >= 2017)
145                 fprintf(f, "%010u ", crc32(0, dec->cpf, 11)); /* hash CPF */
146         else
147                 fprintf(f, "%-11.11s", ""); /* CPF empregada, FILLER */
148         fprintf(f, "%-12.12s", sistema_get_mac(dec));
149         fprintf(f, "%08d", 0); /* Data saída */
150         fprintf(f, "%-11.11s", ""); /* CPF procurador */
151         fprintf(f, "%03d", dec->obrigatoria); /* criterio obrigatoriedade */
152         fprintf(f, "%013lld", totais_get(dec, "RENDTRIB")); /* Total tributavel */
153         /* CNPJ previdencia */
154         fprintf(f, "%-14.14s", inss_cnpj_ordenado(dec, 0));
155         /* CNPJ previdencia 2 */
156         fprintf(f, "%-14.14s", inss_cnpj_ordenado(dec, 1));
157         /* Total isentos */
158         fprintf(f, "%013lld", totais_get(dec, "ISENTOS"));
159         /* Total exclusivo */
160         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS"));
161         /* Total pagamentos */
162         fprintf(f, "%013lld", totais_get(dec, "PAGAMENTOS"));
163         fprintf(f, "%-13.13s", dec->contacorrente ? : ""); /* numero conta */
164         fprintf(f, "%-2.2s", dec->dvconta ? : ""); /* DV conta */
165         fprintf(f, "0"); /* TODO: revalidar DV conta */
166
167         /* Mudanças de 2015 */
168
169         fprintf(f, "%02d", dec->contribuinte.natureza_ocupacao); /* natureza ocupacao */
170         fprintf(f, "%-11.11s", ""); /* CPF domestica */
171         fprintf(f, "%-11.11s", ""); /* NI domestica */
172         fprintf(f, "%-11.11s", ""); /* CPF domestica 2 */
173         fprintf(f, "%-11.11s", ""); /* NI domestica 2 */
174         fprintf(f, "%-11.11s", ""); /* CPF domestica 3 */
175         fprintf(f, "%-11.11s", ""); /* NI domestica 3 */
176         fprintf(f, "1"); /* Declaracao iniciada */
177         fprintf(f, "1"); /* Utilizou PGD */
178         fprintf(f, "0"); /* Utilizou APP */
179         fprintf(f, "0"); /* Utilizou online */
180         fprintf(f, "0"); /* Utilizou rascunho */
181         fprintf(f, "0"); /* Utilizou pre preenchida */
182         fprintf(f, "0"); /* Utilizou fontes */
183         fprintf(f, "0"); /* Utilizou plano saude */
184         fprintf(f, "0"); /* Utilizou recuperar */
185         fprintf(f, "1"); /* Declaracao iniciada */
186
187         /* Fim das mudanças de 2015 */
188
189         /* Mudanças de 2016 */
190
191         if (dec->ano >= 2016) {
192                 /* CNPJ maior pagamento dedutível */
193                 fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 0));
194                 /* CNPJ maior pagamento dedutível */
195                 fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 1));
196                 /* CNPJ maior pagamento dedutível */
197                 fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 2));
198                 /* CNPJ maior pagamento dedutível */
199                 fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 3));
200                 /* CNPJ maior pagamento dedutível */
201                 fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 4));
202                 /* CNPJ maior pagamento dedutível */
203                 fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 5));
204                 /* TODO: CNPJ maior pagamento FUNPRESP */
205                 fprintf(f, "%-14.14s", "");
206         }
207
208         /* Fim das mudanças de 2016 */
209
210         fprintf(f, "   "); /* Teste PGD, FILLER2 */
211 }
212
213 static void gera_contribuinte(struct declaracao *dec, FILE *f)
214 {
215         fprintf(f, "16");
216         fprintf(f, "%s", dec->cpf);
217         fprintf(f, "%-60.60s", dec->nome);
218         fprintf(f, "%-15.15s", dec->contribuinte.tipo_logradouro);
219         fprintf(f, "%-40.40s", dec->contribuinte.logradouro);
220         fprintf(f, "%-6.6s", dec->contribuinte.numero);
221         fprintf(f, "%-21.21s", dec->contribuinte.complemento ?: "");
222         fprintf(f, "%-19.19s", dec->contribuinte.bairro);
223         fprintf(f, "%-9.9s", dec->contribuinte.cep);
224         fprintf(f, "%04d", dec->contribuinte.cd_municipio);
225         fprintf(f, "%-40.40s", dec->contribuinte.municipio);
226         fprintf(f, "%-2.2s", dec->contribuinte.uf);
227         fprintf(f, "   "); /* TODO: código exterior */
228         fprintf(f, "105"); /* TODO: código país */
229         if (dec->ano == 2015) {
230                 fprintf(f, "%-100.100s", ""); /* FILLER3 */
231                 fprintf(f, "%-4.4s", ""); /* FILLER1 */
232                 fprintf(f, "%-8.8s", ""); /* FILLER2 */
233         } else if (dec->ano >= 2016) {
234                 fprintf(f, "%-90.90s", ""); /* FILLER3 */
235                 /* TODO: NIT/PIS/PASEP de Pessoa Física no exterior */
236                 fprintf(f, "%-11.11s", dec->contribuinte.nit ?: "");
237                 /* CPF do cônjuge */
238                 fprintf(f, "%-11.11s", dec->conjuge.cpf ?: "");
239         }
240         if (dec->ano <= 2017) {
241                 fprintf(f, "%-4.4s", dec->contribuinte.ddd ?: "");
242                 fprintf(f, "%-9.9s", dec->contribuinte.telefone ?: "");
243         } else {
244                 fprintf(f, "%-13.13s", ""); /* FILLER */
245         }
246         fprintf(f, "%-8.8s", dec->contribuinte.dn);
247         fprintf(f, "%-13.13s", dec->contribuinte.titulo_eleitor ?: "");
248         fprintf(f, "%03d", dec->contribuinte.ocupacao_principal);
249         fprintf(f, "%02d", dec->contribuinte.natureza_ocupacao);
250         fprintf(f, "%d", dec->pagar ? 1 : 0); /* TODO/FIXME: qnt quotas */
251         fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
252         fprintf(f, "%s", dec->retifica ? "S" : "N");
253         fprintf(f, "S"); /* GERADO */
254         fprintf(f, "N"); /* TODO: mudança de endereço */
255         fprintf(f, "%-12.12s", dec->retifica ? : ""); /* Recibo declaração original */
256         fprintf(f, "%-3.3s", dec->banco ? : "000"); /* banco */
257         fprintf(f, "%-4.4s", dec->agencia ? : "0000"); /* agência */
258         fprintf(f, "N"); /* TODO: deficiência */
259         fprintf(f, "0"); /* FILLER: pré-preenchida */
260         fprintf(f, "%-13.13s", dec->contacorrente ? : ""); /* conta */
261         fprintf(f, "%-2.2s", dec->dvconta ? : ""); /* DV conta */
262         fprintf(f, "N"); /* TODO: débito automático */
263         fprintf(f, "0"); /* TODO: débito primeira quota */
264         /* CNPJ principal fonte */
265         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0));
266         fprintf(f, "%-10.10s", dec->recibo ?: ""); /* Recibo última declaração ano anterior */
267         fprintf(f, "A"); /* Declaração de Ajuste */
268         fprintf(f, "%-11.11s", ""); /* TODO: CPF procurador */
269         if (dec->ano >= 2016)
270                 fprintf(f, "%-20.20s", ""); /* TODO: registro profissional */
271         if (dec->ano >= 2017) {
272                 fprintf(f, "%-11.11s", dec->contribuinte.celular ?: ""); /* celular */
273                 fprintf(f, "%s", dec->conjuge.cpf ? "S" : "N");
274         }
275         if (dec->ano >= 2018) {
276                 fprintf(f, "%-2.2s%-9.9s", dec->contribuinte.ddd ?: "", dec->contribuinte.telefone ?: "");
277         }
278 }
279
280 static void gera_simples(struct declaracao *dec, FILE *f)
281 {
282         fprintf(f, "17");
283         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
284         fprintf(f, "%013lld", 0); /* TODO: carnê leão */
285         fprintf(f, "%013lld", 0); /* TODO: lucros e dividendos */
286         /* rendimentos isentos titular */
287         fprintf(f, "%013lld", totais_get(dec, "ISENTOSTIT"));
288         /* rendimentos tributação exclusiva, exceto décimo terceiro */
289         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS_SEM_13o"));
290         /* 13o. */
291         fprintf(f, "%013lld", totais_get(dec, "DECIMOTERCEIRO"));
292         fprintf(f, "%013lld", 0); /* TODO: retido na fonte (Lei 11.033) */
293         fprintf(f, "%013lld", 0); /* TODO: 13o. dependentes */
294         fprintf(f, "%013lld", 0); /* TODO: lucros dependentes */
295         /* BUG IRPF: O IRPF imprime 0 aqui mesmo com doações e poupança. */
296         /* fprintf(f, "%013lld", totais_get(dec, "ISENTOSDEP")); */
297         fprintf(f, "%013lld", 0); /* isentos dependentes */
298         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSDEP")); /* exclusivos dependentes */
299         fprintf(f, "%-13.13s", ""); /* FILLER */
300         fprintf(f, "%-13.13s", ""); /* FILLER */
301         fprintf(f, "%013lld", totais_get(dec, "RENDPFTIT")); /* rendimentos PF titular */
302         fprintf(f, "%013lld", totais_get(dec, "RENDPFDEP")); /* rendimentos PF dependentes */
303         fprintf(f, "%013lld", totais_get(dec, "RENDEXTTIT")); /* FIXME: rendimentos PF exterior titular */
304         fprintf(f, "%013lld", totais_get(dec, "RENDEXTDEP")); /* FIXME: rendimentos PF ext. depend. */
305
306         /* FIXME: um teste demonstra que não há valor quando existem rendimentos de PF para o titular */
307         /* totais_get(dec, "RENDPF")); */
308         /* TODO: carnê-leão PF? */
309         fprintf(f, "%013lld", totais_get(dec, "CARNETIT"));
310
311         fprintf(f, "%013lld", totais_get(dec, "CARNEDEP")); /* carnê-leão dependentes */
312         fprintf(f, "%013lld", totais_get(dec, "DEPENDENTES")); /* dedução dependentes */
313         fprintf(f, "%013lld", 0); /* TODO: previdência RRA */
314         fprintf(f, "%013lld", 0); /* TODO: previdência RRA dependentes */
315         fprintf(f, "%013lld", 0); /* TODO: pensão RRA */
316         fprintf(f, "%013lld", 0); /* TODO: pensão RRA dependentes */
317         fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
318         fprintf(f, "%013lld", 0); /* TODO: imposto devido sem rendimento exterior */
319         fprintf(f, "%013lld", 0); /* TODO: limite imposto pago exterior */
320 }
321
322 static void gera_totais_simples(struct declaracao *dec, FILE *f)
323 {
324         fprintf(f, "18");
325         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
326         fprintf(f, "%013lld", totais_get(dec, "RENDTRIB")); /* rendimentos tributáveis */
327         /* desconto simplificado */
328         fprintf(f, "%013lld", totais_get(dec, "DESCONTO"));
329          /* base de cálculo */
330         fprintf(f, "%013lld", totais_get(dec, "BASE"));
331         fprintf(f, "%013lld", dec->devido); /* imposto devido */
332         fprintf(f, "%013lld", dec->retido); /* imposto retido */
333         fprintf(f, "%013lld", 0); /* TODO: imposto complementar */
334         fprintf(f, "%013lld", totais_get(dec, "CARNE")); /* TODO: imposto pago carnê-leão */
335         fprintf(f, "%013lld", 0); /* TODO: imposto retido Lei 11.033 */
336         fprintf(f, "%013lld", dec->restituicao); /* imposto a restituir */
337         fprintf(f, "%013lld", dec->pagar); /* imposto pagar */
338         fprintf(f, "%d", dec->pagar ? 1 : 0); /* TODO/FIXME: quotas */
339         fprintf(f, "%013lld", dec->pagar); /* TODO: valor quota */
340         fprintf(f, "%013lld", totais_get(dec, "ISENTOS")); /* rendimentos isentos */
341         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS")); /* rendimentos tributação exclusiva */
342         if (dec->ano == 2015) {
343                 fprintf(f, "%013lld", dec->conjuge.total); /* conjuge */
344         } else if (dec->ano >= 2016) {
345                 fprintf(f, "%013lld", 0); /* FILLER */
346         }
347         fprintf(f, "%013lld", 0); /* TODO: rendimento PJ dependente */
348         fprintf(f, "%013lld", 0); /* TODO: imposto retido dependente */
349         fprintf(f, "%013lld", 0); /* TODO: imposto ganhos de capital */
350         fprintf(f, "%013lld", totais_get(dec, "RENDPJTIT")); /* rendimento tributável PJ titular */
351         fprintf(f, "%013lld", 0); /* TODO: total rural */
352         fprintf(f, "%013lld", dec->retido); /* FIXME: imposto retido titular */
353         fprintf(f, "%013lld", totais_get(dec, "BENSANTERIOR")); /* total bens ano anterior */
354         fprintf(f, "%013lld", totais_get(dec, "BENS")); /* total bens ano base */
355         fprintf(f, "%013lld", totais_get(dec, "ISENTOSTIT")); /* rendimentos isentos titular */
356         fprintf(f, "%013lld", totais_get(dec, "ISENTOSDEP")); /* rendimentos isentos dependentes */
357         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSTIT")); /* tributação exclusiva titular */
358         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSDEP")); /* tributação exclusiva dependentes */
359         fprintf(f, "%013lld", 0); /* TODO: total não tributável AR */
360         fprintf(f, "%013lld", 0); /* TODO: total dívidas ano anterior */
361         fprintf(f, "%013lld", 0); /* TODO: total dívidas ano base */
362         fprintf(f, "%013lld", 0); /* TODO: retido fonte Lei 11.033 */
363         fprintf(f, "%013lld", 0); /* TODO: isentos e não tributáveis, transportado */
364         fprintf(f, "%013lld", 0); /* TODO: tributação exclusiva, transportado */
365         fprintf(f, "%013lld", 0); /* TODO: ganhos líquidos renda variável */
366         fprintf(f, "%013lld", 0); /* TODO: parcela isenta ganhos capital */
367         fprintf(f, "%013lld", totais_get(dec, "RENDPFTIT") + totais_get(dec, "RENDEXTTIT")); /* TODO: rendimentos PF + exterior titular */
368         fprintf(f, "%013lld", totais_get(dec, "RENDPFDEP") + totais_get(dec, "RENDEXTDEP")); /* TODO: rendimentos PF exterior dependentes */
369         fprintf(f, "%013lld", 0); /* TODO: doações campanha */
370         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa titular */
371         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa dependentes */
372         fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa titular */
373         fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa dependentes */
374         fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA titular */
375         fprintf(f, "%013lld", 0); /* TODO: IRF RRA titular */
376         fprintf(f, "%013lld", 0); /* TODO: imposto RRA titular */
377         fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA dependentes */
378         fprintf(f, "%013lld", 0); /* TODO: IRF RRA dependentes */
379         fprintf(f, "%013lld", 0); /* TODO: imposto RRA dependentes */
380         fprintf(f, "%013lld", dec->devido); /* imposto devido */
381         fprintf(f, "%013lld", 0); /* TODO: imposto diferido ganho capital */
382         fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital */
383         fprintf(f, "%013lld", 0); /* TODO: imposto ganho líquido renda variável */
384         fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital moeda estrangeira */
385         fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
386         if (dec->ano >= 2018) {
387                 fprintf(f, "%05lld", dec->aliquota_efetiva);
388         }
389 }
390
391 static void gera_completa(struct declaracao *dec, FILE *f)
392 {
393         fprintf(f, "19");
394         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
395         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0)); /* CNPJ maior */
396         fprintf(f, "%013lld", 0); /* TODO: imposto pago no exterior */
397         fprintf(f, "%013lld", 0); /* TODO: imposto complementar pago */
398         fprintf(f, "%013lld", 0); /* TODO: retido fonte Lei 11.033 */
399         fprintf(f, "%013lld", 0); /* TODO: rendimentos recebidos no exterior - titular */
400         fprintf(f, "%013lld", 0); /* TODO: livro caixa - titular */
401         fprintf(f, "%013lld", 0); /* TODO: carnê-leão - titular */
402         fprintf(f, "%013lld", 0); /* TODO: rendimentos recebidos no exterior - dependente */
403         fprintf(f, "%013lld", 0); /* TODO: livro caixa - dependente */
404         fprintf(f, "%013lld", 0); /* TODO: carnê-leão - dependente */
405         fprintf(f, "%013lld", totais_get(dec, "PREVIDENCIA")); /* TODO: contribuição previdenciária privada */
406         fprintf(f, "%013lld", 0); /* TODO: contribuição FAPI */
407         /* INSS titular, TODO (2016): sem RRA */
408         fprintf(f, "%013lld", totais_get(dec, "INSS"));
409         /* TODO: INSS dependente, TODO (2016): sem RRA */
410         fprintf(f, "%013lld", 0);
411         fprintf(f, "%013lld", totais_get(dec, "DECIMOTERCEIRO")); /* TODO: 13o titular */
412         fprintf(f, "%013lld", 0); /* TODO: 13o dependente */
413         fprintf(f, "%05d", totais_get(dec, "DEPSINSTRUCAO")); /* dependentes com instrucao */
414         fprintf(f, "%05d", 0); /* TODO: alimentandos com instrucao */
415         fprintf(f, "%013lld", totais_get(dec, "RENDPFTIT")); /* TODO: rendimentos PF titular */
416         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF dependente */
417         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior titular */
418         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior dependente */
419         /* IRPF-2015-1.3 gera este valor como 0, antes era dec->devido */
420         fprintf(f, "%013lld", 0); /* TODO: imposto devido sem rendimento exterior */
421         fprintf(f, "%013lld", 0); /* TODO: limite imposto pago exterior */
422         if (dec->ano >= 2016) {
423                 /* TODO: valor até o limite da FUNPRESP */
424                 fprintf(f, "%013lld", 0);
425                 /* TODO: valor acima do limite da FUNPRESP */
426                 fprintf(f, "%013lld", 0);
427         }
428 }
429
430 static void gera_totais_completa(struct declaracao *dec, FILE *f)
431 {
432         fprintf(f, "20");
433         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
434         /* FIXME: completar campos */
435         fprintf(f, "%013lld", totais_get(dec, "RENDPJTIT")); /* rendimentos PJ titular */
436         fprintf(f, "%013lld", totais_get(dec, "RENDPFTIT")); /* TODO: rendimentos PF titular */
437         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF dependente */
438         fprintf(f, "%013lld", 0); /* TODO: resultado atividade rural */
439         fprintf(f, "%013lld", totais_get(dec, "RENDTRIB")); /* total rendimentos tributáveis */
440         /* TODO (2016): somar FUNPRESP até o limite */
441         fprintf(f, "%013lld", totais_get(dec, "INSS")); /* previdencia oficial */
442         /* TODO (2016): somar FUNPRESP acima do limite */
443         fprintf(f, "%013lld", totais_get(dec, "PREVIDENCIA")); /* previdencia privada */
444         fprintf(f, "%013lld", totais_get(dec, "DEPENDENTES")); /* deducao dependentes */
445         fprintf(f, "%013lld", totais_get(dec, "INSTRUCAO")); /* deducao instrucao */
446         fprintf(f, "%013lld", totais_get(dec, "MEDICAS")); /* despesas medicas */
447         fprintf(f, "%013lld", 0); /* TODO: pensao */
448         fprintf(f, "%013lld", 0); /* TODO: pensao escritura publica */
449         fprintf(f, "%013lld", 0); /* TODO: livro caixa */
450         fprintf(f, "%013lld", totais_get(dec, "DEDUCOES")); /* total deduções */
451         fprintf(f, "%013lld", totais_get(dec, "BASE")); /* base de cálculo */
452         fprintf(f, "%013lld", dec->devido); /* TODO: valor do imposto */
453         fprintf(f, "%013lld", 0); /* TODO: deducao do imposto (limitado a 6%) */
454         fprintf(f, "%013lld", dec->devido); /* imposto devido */
455         fprintf(f, "%013lld", 0); /* TODO: contribuicao patronal */
456         fprintf(f, "%013lld", dec->devido); /* TODO: imposto devido menos patronal */
457         fprintf(f, "%013lld", dec->devido); /* TODO: imposto devido mais RRA */
458         fprintf(f, "%013lld", dec->retido); /* imposto na fonte */
459         fprintf(f, "%013lld", totais_get(dec, "RENDPF")); /* TODO: carne leao */
460
461         fprintf(f, "%013lld", 0); /* TODO: imposto complementar */
462         fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
463         fprintf(f, "%013lld", 0); /* TODO: imposto retido Lei 11.033 */
464         fprintf(f, "%013lld", dec->retido); /* TODO: total imposto pago */
465         fprintf(f, "%013lld", dec->restituicao); /* imposto a restituir */
466         fprintf(f, "%013lld", dec->pagar); /* imposto a pagar */
467         fprintf(f, "%d", dec->pagar ? 1 : 0); /* TODO/FIXME: quotas */
468         fprintf(f, "%013lld", dec->pagar); /* TODO: valor quota */
469
470         fprintf(f, "%013lld", totais_get(dec, "BENSANTERIOR")); /* total bens ano anterior */
471         fprintf(f, "%013lld", totais_get(dec, "BENS")); /* total bens ano base */
472         fprintf(f, "%013lld", 0); /* TODO: total dívidas ano anterior */
473         fprintf(f, "%013lld", 0); /* TODO: total dívidas ano base */
474         if (dec->ano == 2015) {
475                 fprintf(f, "%013lld", dec->conjuge.total); /* conjuge */
476         } else if (dec->ano >= 2016) {
477                 fprintf(f, "%013lld", 0); /* FILLER */
478         }
479         fprintf(f, "%013lld", totais_get(dec, "ISENTOS")); /* rendimentos isentos */
480         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS")); /* rendimentos tributação exclusiva */
481         fprintf(f, "%013lld", 0); /* TODO: imposto ganhos de capital */
482         fprintf(f, "%013lld", 0); /* TODO: retido fonte Lei 11.033 */
483         fprintf(f, "%013lld", 0); /* TODO: imposto renda variável */
484
485         fprintf(f, "%013lld", 0); /* TODO: rendimento PJ dependente */
486         fprintf(f, "%013lld", 0); /* TODO: imposto fonte dependente */
487         fprintf(f, "%013lld", 0); /* TODO: imposto moeda estrangeira */
488         fprintf(f, "%013lld", 0); /* TODO: imposto ganhos capital moeda */
489         fprintf(f, "%013lld", totais_get(dec, "ISENTOSTIT")); /* rendimentos isentos titular */
490         fprintf(f, "%013lld", totais_get(dec, "ISENTOSDEP")); /* rendimentos isentos dependentes */
491         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSTIT")); /* TODO: tributação exclusiva titular */
492         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSDEP")); /* tributação exclusiva dependentes */
493         fprintf(f, "%013lld", 0); /* TODO: doações campanha */
494         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa titular */
495         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa dependentes */
496         fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa titular */
497         fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa dependentes */
498
499         fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA titular */
500         fprintf(f, "%013lld", 0); /* TODO: previdencia RRA titular */
501         fprintf(f, "%013lld", 0); /* TODO: pensao RRA titular */
502         fprintf(f, "%013lld", 0); /* TODO: IRF RRA titular */
503         fprintf(f, "%013lld", 0); /* TODO: imposto RRA titular */
504         fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA dependentes */
505         fprintf(f, "%013lld", 0); /* TODO: previdencia RRA dependentes */
506         fprintf(f, "%013lld", 0); /* TODO: pensao RRA dependentes */
507         fprintf(f, "%013lld", 0); /* TODO: IRF RRA dependentes */
508         fprintf(f, "%013lld", 0); /* TODO: imposto RRA dependentes */
509
510         fprintf(f, "%013lld", 0); /* TODO: imposto diferido ganho capital */
511         fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital */
512         fprintf(f, "%013lld", 0); /* TODO: imposto ganho líquido renda variável */
513         fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital moeda estrangeira */
514         if (dec->ano >= 2018) {
515                 fprintf(f, "%05lld", dec->aliquota_efetiva);
516         }
517 }
518
519 static void gera_isentos(struct declaracao *dec, FILE *f)
520 {
521         fprintf(f, "23");
522         fprintf(f, "%-11.11s", dec->cpf);
523         fprintf(f, "%013lld", 0); /* TODO: bolsa de estudo */
524         fprintf(f, "%013lld", 0); /* TODO: pecúlio de previdência privada */
525         fprintf(f, "%013lld", totais_get(dec, "INDENIZACOES")); /* FGTS, aviso prévio indenizado */
526         fprintf(f, "%013lld", 0); /* TODO: ganho de capital isento */
527         fprintf(f, "%013lld", 0); /* TODO: lucros e dividendos */
528         fprintf(f, "%013lld", 0); /* TODO: atividade rural */
529         fprintf(f, "%013lld", 0); /* TODO: contribuintes com 65 anos ou mais */
530         fprintf(f, "%013lld", 0); /* TODO: pensão por invalidez */
531         fprintf(f, "%013lld", totais_get(dec, "POUPANCA"));
532         fprintf(f, "%013lld", 0); /* TODO: sócio ou titular de empresa */
533         fprintf(f, "%013lld", totais_get(dec, "DOACOES")); /* herança, transferências patrimoniais */
534         fprintf(f, "%013lld", 0); /* TODO: outros rendimentos isentos */
535         fprintf(f, "%-60.60s", ""); /* FILLER1 */
536         fprintf(f, "%-13.13s", ""); /* FILLER2 */
537         fprintf(f, "%013lld", 0); /* TODO: alienação bens pequeno valor */
538         fprintf(f, "%013lld", 0); /* TODO: alienação único imóvel */
539         fprintf(f, "%013lld", 0); /* TODO: redução ganho capital */
540         fprintf(f, "%013lld", 0); /* TODO: total bens pequeno valor, transportado GC */
541         fprintf(f, "%013lld", 0); /* TODO: alienção único imóvel, transportado GC */
542         fprintf(f, "%013lld", 0); /* TODO: redução ganho capital, transportado GC */
543         fprintf(f, "%013lld", 0); /* TODO: ganho capital - moeda estrangeira */
544         fprintf(f, "%013lld", 0); /* TODO: ganho capital - moeda estrangeira, transportado */
545         fprintf(f, "%013lld", 0); /* TODO: GC total informado */
546         fprintf(f, "%013lld", 0); /* TODO: GC total transportado */
547         fprintf(f, "%013lld", 0); /* TODO: imposto renda anos anteriores */
548         fprintf(f, "%013lld", 0); /* TODO: rendimentos assalariados moeda estrangeira */
549         fprintf(f, "%013lld", 0); /* TODO: bonificações ações */
550         fprintf(f, "%013lld", 0); /* TODO: médicos residentes */
551         fprintf(f, "%013lld", 0); /* TODO: volutários da Copa */
552         fprintf(f, "%013lld", 0); /* TODO: meação e dissolução */
553         fprintf(f, "%013lld", 0); /* TODO: ganhos líquidos com ações */
554         fprintf(f, "%013lld", 0); /* TODO: ganhos de capital com ouro */
555         fprintf(f, "%013lld", 0); /* TODO: recuperação prejuízos na bolsa */
556         fprintf(f, "%013lld", 0); /* TODO: transportador de cargas */
557         fprintf(f, "%013lld", 0); /* TODO: transportador de passageiros */
558         fprintf(f, "%013lld", 0); /* TODO: retistuição imposto anos anteriores */
559 }
560
561 static void gera_isentos2(struct declaracao *dec, FILE *f, int codigo, char *nome)
562 {
563         long long total = totais_get(dec, nome);
564         if (total == 0)
565                 return;
566         fprintf(f, "23");
567         fprintf(f, "%-11.11s", dec->cpf);
568         fprintf(f, "%04d", codigo);
569         fprintf(f, "%013lld", total);
570 }
571
572 static void gera_23_poupanca(struct declaracao *dec, FILE *f)
573 {
574         gera_isentos2(dec, f, 12, "POUPANCA");
575 }
576
577 static void gera_23_lucrome(struct declaracao *dec, FILE *f)
578 {
579         gera_isentos2(dec, f, 13, "LUCROME");
580 }
581
582 static void gera_23_outrosisentos(struct declaracao *dec, FILE *f)
583 {
584         gera_isentos2(dec, f, 26, "OUTROSISENTOS");
585 }
586
587 static void gera_exclusivos(struct declaracao *dec, FILE *f)
588 {
589         fprintf(f, "24");
590         fprintf(f, "%-11.11s", dec->cpf);
591         fprintf(f, "%013lld", totais_get(dec, "DECIMOTERCEIRO"));
592         fprintf(f, "%013lld", 0); /* TODO: ganho de capital */
593         fprintf(f, "%013lld", 0); /* TODO: ganho líquido renda variável */
594         fprintf(f, "%013lld", totais_get(dec, "APLICACOES")); /* TODO: aplicações financeiras */
595         fprintf(f, "%013lld", 0); /* TODO: outros */
596         fprintf(f, "%-60.60s", ""); /* FILLER1 */
597         fprintf(f, "%013lld", 0); /* TODO: ganhos de capital alienação de bens */
598         fprintf(f, "%013lld", 0); /* TODO: ganhos de capital moeda estrangeira */
599         fprintf(f, "%013lld", 0); /* TODO: décimo terceiro dependentes */
600         fprintf(f, "%-13.13s", ""); /* FILLER2 */
601         fprintf(f, "%-60.60s", ""); /* FILLER3 */
602         fprintf(f, "%013lld", 0); /* TODO: RRA */
603         fprintf(f, "%013lld", 0); /* TODO: RRA dependentes */
604         fprintf(f, "%013lld", 0); /* TODO: Juros capital próprio */
605         fprintf(f, "%013lld", totais_get(dec, "PLR"));
606 }
607
608 static void gera_exclusivos2(struct declaracao *dec, FILE *f, int codigo, char *nome)
609 {
610         long long total = totais_get(dec, nome);
611         if (total == 0)
612                 return;
613         fprintf(f, "24");
614         fprintf(f, "%-11.11s", dec->cpf);
615         fprintf(f, "%04d", codigo);
616         fprintf(f, "%013lld", total); /* TODO: retistuição imposto anos anteriores */
617 }
618
619 static void gera_24_decimoterceiro(struct declaracao *dec, FILE *f)
620 {
621         gera_exclusivos2(dec, f, 1, "DECIMOTERCEIRO");
622 }
623
624 static void gera_24_aplicacoes(struct declaracao *dec, FILE *f)
625 {
626         gera_exclusivos2(dec, f, 6, "APLICACOES");
627 }
628
629 static void gera_24_plr(struct declaracao *dec, FILE *f)
630 {
631         gera_exclusivos2(dec, f, 11, "PLR");
632 }
633
634 static void gera_conjuge(struct declaracao *dec, FILE *f)
635 {
636         fprintf(f, "29");
637         fprintf(f, "%-11.11s", dec->cpf);
638         fprintf(f, "%-11.11s", dec->conjuge.cpf);
639         fprintf(f, "%013lld", dec->conjuge.base);
640         fprintf(f, "%013lld", dec->conjuge.imposto);
641         fprintf(f, "%013lld", dec->conjuge.isento);
642         fprintf(f, "%013lld", dec->conjuge.exclusivo);
643         fprintf(f, "%013lld", dec->conjuge.rendpj_exigibilidade_suspensa);
644         fprintf(f, "%013lld", dec->conjuge.total);
645         fprintf(f, "%c", dec->conjuge.entregou ? 'S' : 'N');
646 }
647
648 static int is_trailler_filler(int ano, int i)
649 {
650         if (ano == 2018) {
651                 return i == 29 || i == 31 || i == 33 || i == 36 || i == 37 || i == 44 || i == 82;
652         }
653 #if 0
654         if (ano == 2019) {
655                 return i == 57 || (i >= 76 && i <= 79);
656         }
657 #endif
658         return (ano <= 2018 && i == 44);
659         /* Ano 2016, linha 29 é um FILLER, mas preenchida com múltiplos
660          * 0s. Como esta linha não é gerada na declaração de 2016, não
661          * deve constar aqui, e será contabilizada como 0. */
662         /* O mesmo vale para as linhas de 2019 comentadas acima. */
663         /* || (ano == 2016 && i == 29); */
664 }
665
666 static int is_trailler_spaces(int ano, int i)
667 {
668         return (ano == 2018 && i > 92);
669 }
670
671 static int is_trailler_empty(int ano, int i)
672 {
673         return
674                 (ano == 2015 && i == 49) ||
675                 (ano <= 2018 &&
676                         (i == 57 || i == 64 || i == 79));
677 }
678
679 static void gera_trailler(struct declaracao *dec, FILE *f)
680 {
681         int i;
682         fprintf(f, "T9");
683         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
684         fprintf(f, "%06d", dec->linhas[0]);
685         for (i = 16; i < 100; i++) {
686                 if (is_trailler_filler(dec->ano, i))
687                         fprintf(f, "%-5.5s", "0"); /* FILLER */
688                 else if (is_trailler_spaces(dec->ano, i))
689                         fprintf(f, "%-5.5s", "");
690                 else if (is_trailler_empty(dec->ano, i))
691                         ;
692                 else if (dec->ano == 2018 && i == 92)
693                         fprintf(f, "%-5s", "0");
694                 else
695                         fprintf(f, "%05d", dec->linhas[i]);
696         }
697 }
698
699 static void gera_reciboheader(struct declaracao *dec, FILE *f)
700 {
701         fprintf(f, "HR");
702         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
703         fprintf(f, "%-3.3s", ""); /* FILLER */
704 }
705
706 static void gera_recibodetalhe(struct declaracao *dec, FILE *f)
707 {
708         fprintf(f, "DR");
709         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
710         fprintf(f, "%-3.3s", ""); /* FILLER */
711         fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
712         fprintf(f, "%-60.60s", dec->nome);
713         fprintf(f, "%-15.15s", dec->contribuinte.tipo_logradouro);
714         fprintf(f, "%-40.40s", dec->contribuinte.logradouro);
715         fprintf(f, "%-6.6s", dec->contribuinte.numero);
716         fprintf(f, "%-21.21s", dec->contribuinte.complemento ?: "");
717         fprintf(f, "%-19.19s", dec->contribuinte.bairro);
718         fprintf(f, "%-9.9s", dec->contribuinte.cep);
719         fprintf(f, "%04d", dec->contribuinte.cd_municipio);
720         fprintf(f, "%-40.40s", dec->contribuinte.municipio);
721         fprintf(f, "%-2.2s", dec->contribuinte.uf);
722         fprintf(f, "%-100.100s", ""); /* FILLER */
723         fprintf(f, "%-4.4s", ""); /* FILLER */
724         fprintf(f, "%-8.8s", ""); /* FILLER */
725         if (dec->ano >= 2018) {
726                 fprintf(f, "%-13.13s", "");
727         } else {
728                 fprintf(f, "%-4.4s", dec->contribuinte.ddd ?: "");
729                 fprintf(f, "%-9.9s", dec->contribuinte.telefone ?: "");
730         }
731         fprintf(f, "%s", dec->retifica ? "S" : "N"); /* Retificadora */
732         fprintf(f, "%013lld", totais_get(dec, "RENDTRIB")); /* Total tributavel */
733         fprintf(f, "%013lld", dec->devido); /* Imposto devido */
734         fprintf(f, "%013lld", dec->restituicao); /* Imposto a restituir */
735         fprintf(f, "%013lld", dec->pagar); /* Imposto a pagar */
736         fprintf(f, "%d", dec->pagar ? 1 : 0); /* TODO/FIXME: quotas */
737         fprintf(f, "%013lld", dec->pagar); /* TODO: valor quota */
738         fprintf(f, "%-3.3s", dec->banco ? : "000"); /* numero banco */
739         fprintf(f, "%-4.4s", dec->agencia ? : "0000"); /* numero agencia */
740         fprintf(f, " "); /* FILLER */
741         fprintf(f, "%d", 0); /* TODO: debito primeira quota */
742         fprintf(f, "%013lld", 0); /* TODO: imposto pago ganho de capital */
743         fprintf(f, "%-13.13s", dec->contacorrente ? : ""); /* numero conta */
744         fprintf(f, "%-2.2s", dec->dvconta ? : ""); /* DV conta */
745         fprintf(f, "%013lld", 0); /* TODO: imposto alienacao moeda estrangeira em especie */
746         if (dec->ano >= 2018) {
747                 fprintf(f, "%-2.2s%-9.9s", dec->contribuinte.ddd ?: "", dec->contribuinte.telefone ?: "");
748         }
749 }
750
751 static void gera_recibotrailler(struct declaracao *dec, FILE *f)
752 {
753         fprintf(f, "R9");
754         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
755         fprintf(f, "%-3.3s", ""); /* FILLER */
756         fprintf(f, "%010u", dec->rhash);
757 }
758
759 static void gera_rendimento(struct declaracao *dec, FILE *f)
760 {
761         struct rendimento *r;
762         r = list_get(dec->rendimento, dec->linhas[21]);
763         fprintf(f, "21");
764         fprintf(f, "%s", dec->cpf);
765         fprintf(f, "%-14.14s", r->cnpj);
766         fprintf(f, "%-60.60s", r->nome);
767         fprintf(f, "%013lld", r->rendimento);
768         fprintf(f, "%013lld", r->previdencia);
769         fprintf(f, "%013lld", r->decimoterceiro);
770         fprintf(f, "%013lld", r->imposto);
771         fprintf(f, "%-8.8s", r->saida);
772         fprintf(f, "%013lld", r->imposto_13o);
773 }
774
775 static void gera_pagamento(struct declaracao *dec, FILE *f)
776 {
777         struct pagamento *p;
778         p = list_get(dec->pagamentos, dec->linhas[26]);
779         fprintf(f, "26");
780         fprintf(f, "%s", dec->cpf);
781         fprintf(f, "%02d", p->codigo);
782         fprintf(f, "%05d", p->dependente);
783         fprintf(f, "%-14.14s", p->cnpj);
784         fprintf(f, "%-60.60s", p->nome);
785         fprintf(f, "%-11.11s", ""); /* TODO: NIT */
786         fprintf(f, "%013lld", p->pagamento);
787         fprintf(f, "%013lld", p->reembolso);
788         if (dec->ano >= 2016) {
789                 /* TODO: contribuição do ente público patrocinador (FUNPRESP?) */
790                 fprintf(f, "%013lld", 0);
791         }
792         fprintf(f, "%d", strlen(p->cnpj) == 11 ? 1 : 2);
793         /* Titular (T), Dependente (D), Alimentando (A), FIXME Alimentando */
794         fprintf(f, "%c", p->dependente ? 'D' : 'T');
795 }
796
797 static void gera_isento(struct declaracao *dec, FILE *f, int codigo)
798 {
799         struct isento *i;
800         i = isento_get(dec, codigo, dec->linhas[codigo]);
801         fprintf(f, "%02d", codigo);
802         fprintf(f, "%-11.11s", dec->cpf); /* Titular */
803         fprintf(f, "%05d", dec->linhas[codigo] + 1); /* Chave */
804         /* Titular (T), Dependente (D), Alimentando (A), FIXME Alimentando */
805         fprintf(f, "%c", i->dependente ? 'D' : 'T');
806         fprintf(f, "%-14.14s", i->cnpj);
807         fprintf(f, "%-60.60s", i->nome);
808         fprintf(f, "%013lld", i->valor);
809         if (i->dependente) {
810                 struct dependente *d;
811                 d = list_get(dec->dependentes, i->dependente - 1);
812                 fprintf(f, "%-11.11s", d ? d->cpf : "");
813         } else {
814                 fprintf(f, "%-11.11s", dec->cpf);
815         }
816 }
817
818 static void gera_isento2(struct declaracao *dec, FILE *f, int codigo,
819                         int subcodigo, int codigoreal)
820 {
821         struct isento *i;
822         i = dec->ctx;
823         fprintf(f, "%02d", codigoreal);
824         fprintf(f, "%-11.11s", dec->cpf); /* Titular */
825         /* Titular (T), Dependente (D), Alimentando (A), FIXME Alimentando */
826         fprintf(f, "%c", i->dependente ? 'D' : 'T');
827         if (i->dependente) {
828                 struct dependente *d;
829                 d = list_get(dec->dependentes, i->dependente - 1);
830                 fprintf(f, "%-11.11s", d ? d->cpf : "");
831         } else {
832                 fprintf(f, "%-11.11s", dec->cpf);
833         }
834         fprintf(f, "%04d", subcodigo);
835         fprintf(f, "%-14.14s", i->cnpj);
836         fprintf(f, "%-60.60s", i->nome);
837         fprintf(f, "%013lld", i->valor);
838 }
839
840 static void gera_doacao(struct declaracao *dec, FILE *f)
841 {
842         gera_isento(dec, f, 82);
843 }
844
845 static void gera_indenizacoes(struct declaracao *dec, FILE *f)
846 {
847         gera_isento(dec, f, 93);
848 }
849
850 static void gera_plr(struct declaracao *dec, FILE *f)
851 {
852         gera_isento(dec, f, 96);
853 }
854
855 static void gera_plr2(struct declaracao *dec, FILE *f)
856 {
857         gera_isento2(dec, f, 11, 11, 88);
858 }
859
860 static void gera_lucrome2(struct declaracao *dec, FILE *f)
861 {
862         gera_isento2(dec, f, 13, 13, 84);
863 }
864
865 static void gera_outrosisentos(struct declaracao *dec, FILE *f)
866 {
867         struct isento *i;
868         int codigo = 97;
869         i = isento_get(dec, codigo, dec->linhas[codigo]);
870         gera_isento(dec, f, codigo);
871         fprintf(f, "%d", i->exclusivo == 0 ? 1 : 2);
872         fprintf(f, "%-60.60s", i->descricao);
873 }
874
875 static void gera_outrosisentos2(struct declaracao *dec, FILE *f)
876 {
877         struct isento *i;
878         i = dec->ctx;
879         gera_isento2(dec, f, 26, 26, 86);
880         fprintf(f, "%-60.60s", i->descricao);
881 }
882
883 static void gera_poupanca(struct declaracao *dec, FILE *f)
884 {
885         gera_isento(dec, f, 98);
886 }
887
888 static void gera_poupanca2(struct declaracao *dec, FILE *f)
889 {
890         gera_isento2(dec, f, 12, 12, 84);
891 }
892
893 static void gera_aplicacoes(struct declaracao *dec, FILE *f)
894 {
895         gera_isento(dec, f, 99);
896 }
897
898 static void gera_aplicacoes2(struct declaracao *dec, FILE *f)
899 {
900         gera_isento2(dec, f, 6, 6, 88);
901 }
902
903 static void gera_dependente(struct declaracao *dec, FILE *f)
904 {
905         struct dependente *d;
906         d = list_get(dec->dependentes, dec->linhas[25]);
907
908         fprintf(f, "25");
909         fprintf(f, "%s", dec->cpf);
910         fprintf(f, "%05d", dec->linhas[25] + 1);
911         fprintf(f, "%02d", d->codigo);
912         fprintf(f, "%-60.60s", d->nome);
913         fprintf(f, "%-8.8s", d->dn);
914         fprintf(f, "%-11.11s", d->cpf);
915         /* TODO: Indicador de saída */
916         fprintf(f, " ");
917         if (dec->ano >= 2016) {
918                 /* TODO: NIT/PIS/PASEP de Pessoa Física no exterior */
919                 fprintf(f, "%-11.11s", "");
920         }
921 }
922
923 static void gera_bem(struct declaracao *dec, FILE *f)
924 {
925         struct bem *b;
926         b = list_get(dec->bens, dec->linhas[27]);
927
928         fprintf(f, "27");
929         fprintf(f, "%s", dec->cpf);
930         fprintf(f, "%02d", b->codigo);
931
932         /* FIXME: exterior */
933         fprintf(f, "0");
934         fprintf(f, "105"); /* código Brasil */
935
936         fprintf(f, "%-512.512s", b->descricao);
937         fprintf(f, "%013lld", b->valor_anterior);
938         fprintf(f, "%013lld", b->valor);
939
940         /* Imóvel */
941         fprintf(f, "%-40.40s", b->logradouro ?: "");
942         fprintf(f, "%-6.6s", b->numero ?: "");
943         fprintf(f, "%-40.40s", b->complemento ?: "");
944         fprintf(f, "%-40.40s", b->bairro ?: "");
945         fprintf(f, "%-9.9s", b->cep ?: "");
946         fprintf(f, "%-2.2s", b->uf ?: "");
947         fprintf(f, "%04d", b->cd_municipio);
948         fprintf(f, "%-40.40s", b->municipio ?: "");
949         /* FIXME: Registro de imóveis, Nao (0), Sim (1), Vazio (2) */
950         fprintf(f, "%d", b->registro ? 1 : 2);
951         fprintf(f, "%-40.40s", b->matricula ?: "");
952         fprintf(f, "%-40.40s", b->registro ?: "");
953         fprintf(f, "%011lld", b->area);
954         /* FIXME: Area, M2 (0), Ha (1), Vazio (2) */
955         fprintf(f, "%d", (b->area == 0) ? 2 : 0);
956         fprintf(f, "%-60.60s", b->cartorio ?: "");
957
958         /* Número de chave */
959         fprintf(f, "%05d", dec->linhas[27] + 1);
960
961         /* Mudanças 2018 */
962         if (dec->ano >= 2018) {
963                 fprintf(f, "%-8.8s", "00000000"); /* TODO: Data de aquisição */
964                 fprintf(f, "%-20.20s", ""); /* TODO: IPTU, 2019, filler */
965                 fprintf(f, "%-8.8s", "00000000"); /* TODO: NIRF */
966                 fprintf(f, "%-30.30s", ""); /* TODO: RENAVAN */
967                 fprintf(f, "%-30.30s", ""); /* TODO: Registro aviação civil */
968                 fprintf(f, "%-30.30s", ""); /* TODO: Registro Capitania dos Portos */
969                 fprintf(f, "%04d", 0); /* TODO: Agência bancária */
970                 fprintf(f, "%-15.15s", ""); /* TODO: Conta bancária e dígito verificador */
971                 fprintf(f, "%-14.14s", ""); /* TODO: CPF ou CNPJ */
972         }
973
974         if (dec->ano >= 2019) {
975                 fprintf(f, "%-30.30s", ""); /* TODO: IPTU */
976         }
977 }
978
979 static void gera_carne(struct declaracao *dec, FILE *f)
980 {
981         struct carne *carne;
982         carne = list_get(dec->carne, dec->linhas[22]);
983         fprintf(f, "22");
984         fprintf(f, "%-11.11s", dec->cpf); /* Titular */
985         if (carne->dependente) {
986                 struct dependente *d;
987                 d = list_get(dec->dependentes, carne->dependente - 1);
988                 fprintf(f, "S%-11.11s", d ? d->cpf : ""); /* CPF dependente. */
989         } else {
990                 fprintf(f, "N%-11.11s", ""); /* Não é dependente. */
991         }
992         fprintf(f, "%02d", carne->mes);
993         fprintf(f, "%013lld", carne->rendimento);
994         fprintf(f, "%013lld", carne->alugueis); /* Aluguéis. */
995         fprintf(f, "%013lld", carne->outros); /* Outros. */
996         fprintf(f, "%013lld", carne->exterior); /* Exterior. */
997         fprintf(f, "%013lld", carne->caixa); /* Livro-caixa. */
998         fprintf(f, "%013lld", carne->alimentos); /* Pensão alimentícia. */
999         fprintf(f, "%013lld", carne->dependentes); /* Dedução com dependentes. */
1000         fprintf(f, "%013lld", carne->previdencia); /* Previdência. */
1001         fprintf(f, "%013lld", carne->base); /* Base cálculo. */
1002         fprintf(f, "%013lld", carne->imposto); /* Imposto pago. */
1003 }
1004
1005 typedef void (gera_linha)(struct declaracao *dec, FILE *f);
1006
1007 static void update_hash(struct declaracao *dec, char *buf, size_t len)
1008 {
1009         int r;
1010         int linha;
1011         r = sscanf(buf, "%2d", &linha);
1012         if (r == 1 || !strncmp(buf, "T9", 2)) {
1013                 dec->hash = crc32(dec->hash, buf, len - 2);
1014                 dec->rhash = crc32(dec->rhash, buf, len - 2);
1015                 return;
1016         } else if (strncmp(buf, "R9", 2) && strncmp(buf, "IRPF", 4)) {
1017                 dec->rhash = crc32(dec->rhash, buf, len - 2);
1018         }
1019 }
1020
1021 static int wrap(gera_linha fn, struct declaracao *dec, struct list *l)
1022 {
1023         FILE *m;
1024         char *buf = NULL;
1025         size_t bsize;
1026         int linha;
1027         int r;
1028         uLong c = crc32(0L, Z_NULL, 0);
1029         m = open_memstream(&buf, &bsize);
1030         if (!m) {
1031                 return -errno;
1032         }
1033         fn(dec, m);
1034         fflush(m);
1035         if (bsize == 0) {
1036                 fclose(m);
1037                 return 0;
1038         }
1039         dec->linhas[0]++;
1040
1041         /* Calcula CRC32 para campo de controle dos registros. */
1042         c = crc32(c, buf, bsize);
1043         fprintf(m, "%010ld\r\n", c);
1044
1045         fclose(m);
1046         r = sscanf(buf, "%2d", &linha);
1047         if (r == 1 && linha >= 0 && linha < 100) {
1048                 dec->linhas[linha]++;
1049         }
1050         update_hash(dec, buf, bsize);
1051         return list_add(&l, buf);
1052 }
1053
1054 static void insert_hash(struct declaracao *dec, char *irpf)
1055 {
1056         uLong c = crc32(0L, NULL, 0);
1057         char cpf[13];
1058         char crc[11];
1059         snprintf(cpf, 13, "%-8.8s.DEC", dec->cpf);
1060         c = crc32(c, cpf, 12);
1061         snprintf(crc, 11, "%010ld", dec->hash);
1062         memcpy(irpf + 101, crc, 10);
1063         c = crc32(c, irpf, strlen(irpf) - 12);
1064         snprintf(crc, 11, "%010ld", c);
1065         memcpy(irpf + strlen(irpf) - 12, crc, 10);
1066 }
1067
1068 static int gera(struct declaracao *dec, char *filename)
1069 {
1070         FILE *f;
1071         int r = 0;
1072         int i;
1073         struct rendimento *rendimento;
1074         struct carne *carne;
1075         struct isento *isento;
1076         struct pagamento *pagamento;
1077         struct bem *bem;
1078         struct dependente *dependente;
1079         struct list *linhas;
1080         char *buf;
1081
1082         linhas = list_new();
1083         if (!linhas)
1084                 return -ENOMEM;
1085
1086         dec->hash = crc32(0L, NULL, 0);
1087         dec->rhash = crc32(0L, NULL, 0);
1088
1089 #define W(fn) \
1090         do { \
1091                 r = wrap(fn, dec, linhas); \
1092                 if (r < 0) \
1093                         goto out; \
1094         } while (0);
1095
1096         f = fopen(filename, "w");
1097         if (!f) {
1098                 r = -errno;
1099                 dec_set_error(dec, "Não foi possível abrir arquivo %s: %s.",
1100                               filename, strerror(errno));
1101                 goto out_file;
1102         }
1103         memset(dec->linhas, 0, sizeof(dec->linhas));
1104         W(gera_header);
1105         W(gera_contribuinte);
1106         if (dec->tipo == COMPLETA) {
1107                 W(gera_completa);
1108                 W(gera_totais_completa);
1109         } else {
1110                 W(gera_simples);
1111                 W(gera_totais_simples);
1112         }
1113         for (i = 0; rendimento = list_get(dec->rendimento, i); i++) {
1114                 W(gera_rendimento);
1115         }
1116
1117         for (i = 0; (carne = list_get(dec->carne, i)); i++) {
1118                 W(gera_carne);
1119         }
1120
1121         if (dec->ano <= 2017) {
1122                 if (totais_get(dec, "ISENTOS"))
1123                         W(gera_isentos);
1124                 if (totais_get(dec, "EXCLUSIVOS"))
1125                         W(gera_exclusivos);
1126         } else {
1127                 W(gera_23_poupanca);
1128                 W(gera_23_lucrome);
1129                 W(gera_23_outrosisentos);
1130                 W(gera_24_decimoterceiro);
1131                 W(gera_24_aplicacoes);
1132                 W(gera_24_plr);
1133         }
1134
1135         for (i = 0; (dependente = list_get(dec->dependentes, i)); i++) {
1136                 W(gera_dependente);
1137         }
1138         for (i = 0; (pagamento = list_get(dec->pagamentos, i)); i++) {
1139                 W(gera_pagamento);
1140         }
1141         for (i = 0; (bem = list_get(dec->bens, i)); i++) {
1142                 W(gera_bem);
1143         }
1144
1145         if (dec->ano == 2015 && dec->conjuge.cpf)
1146                 W(gera_conjuge);
1147
1148         /* Rendimentos isentos e com tributação exclusiva */
1149         /* Registros 82 a 89, e 92 a 99 */
1150 #define IW(fn, codigo) \
1151         for (i = 0; ; i++) { \
1152                 isento = isento_get(dec, codigo, i); \
1153                 if (!isento) \
1154                         break; \
1155                 dec->ctx = isento; \
1156                 W(fn); \
1157         }
1158         if (dec->ano <= 2017) {
1159                 IW(gera_doacao, 82);
1160                 IW(gera_indenizacoes, 93);
1161                 IW(gera_plr, 96);
1162                 IW(gera_outrosisentos, 97);
1163                 IW(gera_poupanca, 98);
1164                 IW(gera_aplicacoes, 99);
1165         } else {
1166                 IW(gera_poupanca2, 12);
1167                 //dec->linhas[12] = 0;
1168                 IW(gera_lucrome2, 13);
1169                 IW(gera_outrosisentos2, 26);
1170                 IW(gera_aplicacoes2, 6);
1171                 //dec->linhas[99] = 0;
1172                 IW(gera_plr2, 11);
1173                 //dec->linhas[96] = 0;
1174         }
1175
1176         W(gera_trailler);
1177         W(gera_reciboheader);
1178         W(gera_recibodetalhe);
1179         W(gera_recibotrailler);
1180
1181         insert_hash(dec, list_get(linhas, 0));
1182         for (i = 0; (buf = list_get(linhas, i)); i++) {
1183                 fwrite(buf, strlen(buf), 1, f);
1184         }
1185
1186         fclose(f);
1187         list_free(linhas, free);
1188         return 0;
1189 out:
1190         fclose(f);
1191 out_file:
1192         list_free(linhas, free);
1193         return r;
1194 }
1195
1196 static int run_gera(struct declaracao *dec, char **args, int argc)
1197 {
1198         if (argc != 2) {
1199                 dec_set_error(dec, "Comando %s recebe um nome de arquivo como parâmetro.",
1200                               args[0]);
1201                 return -EINVAL;
1202         }
1203         if (!ANO_VALIDO(dec->ano)) {
1204                 dec_set_error(dec, "Comando %s não suporta ano %d.",
1205                               args[0], dec->ano);
1206                 return -EINVAL;
1207         }
1208         return gera(dec, args[1]);
1209 }
1210
1211 static struct cmd cmd_gera = {
1212         .name = "gera",
1213         .run = run_gera,
1214 };
1215
1216 int gera_cmd_init(void)
1217 {
1218         cmd_add(&cmd_gera);
1219         return 0;
1220 }