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