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