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