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