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