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