Suporte inicial a 2018.
[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 }
511
512 static void gera_isentos(struct declaracao *dec, FILE *f)
513 {
514         fprintf(f, "23");
515         fprintf(f, "%-11.11s", dec->cpf);
516         fprintf(f, "%013lld", 0); /* TODO: bolsa de estudo */
517         fprintf(f, "%013lld", 0); /* TODO: pecúlio de previdência privada */
518         fprintf(f, "%013lld", totais_get(dec, "INDENIZACOES")); /* FGTS, aviso prévio indenizado */
519         fprintf(f, "%013lld", 0); /* TODO: ganho de capital isento */
520         fprintf(f, "%013lld", 0); /* TODO: lucros e dividendos */
521         fprintf(f, "%013lld", 0); /* TODO: atividade rural */
522         fprintf(f, "%013lld", 0); /* TODO: contribuintes com 65 anos ou mais */
523         fprintf(f, "%013lld", 0); /* TODO: pensão por invalidez */
524         fprintf(f, "%013lld", totais_get(dec, "POUPANCA"));
525         fprintf(f, "%013lld", 0); /* TODO: sócio ou titular de empresa */
526         fprintf(f, "%013lld", totais_get(dec, "DOACOES")); /* herança, transferências patrimoniais */
527         fprintf(f, "%013lld", 0); /* TODO: outros rendimentos isentos */
528         fprintf(f, "%-60.60s", ""); /* FILLER1 */
529         fprintf(f, "%-13.13s", ""); /* FILLER2 */
530         fprintf(f, "%013lld", 0); /* TODO: alienação bens pequeno valor */
531         fprintf(f, "%013lld", 0); /* TODO: alienação único imóvel */
532         fprintf(f, "%013lld", 0); /* TODO: redução ganho capital */
533         fprintf(f, "%013lld", 0); /* TODO: total bens pequeno valor, transportado GC */
534         fprintf(f, "%013lld", 0); /* TODO: alienção único imóvel, transportado GC */
535         fprintf(f, "%013lld", 0); /* TODO: redução ganho capital, transportado GC */
536         fprintf(f, "%013lld", 0); /* TODO: ganho capital - moeda estrangeira */
537         fprintf(f, "%013lld", 0); /* TODO: ganho capital - moeda estrangeira, transportado */
538         fprintf(f, "%013lld", 0); /* TODO: GC total informado */
539         fprintf(f, "%013lld", 0); /* TODO: GC total transportado */
540         fprintf(f, "%013lld", 0); /* TODO: imposto renda anos anteriores */
541         fprintf(f, "%013lld", 0); /* TODO: rendimentos assalariados moeda estrangeira */
542         fprintf(f, "%013lld", 0); /* TODO: bonificações ações */
543         fprintf(f, "%013lld", 0); /* TODO: médicos residentes */
544         fprintf(f, "%013lld", 0); /* TODO: volutários da Copa */
545         fprintf(f, "%013lld", 0); /* TODO: meação e dissolução */
546         fprintf(f, "%013lld", 0); /* TODO: ganhos líquidos com ações */
547         fprintf(f, "%013lld", 0); /* TODO: ganhos de capital com ouro */
548         fprintf(f, "%013lld", 0); /* TODO: recuperação prejuízos na bolsa */
549         fprintf(f, "%013lld", 0); /* TODO: transportador de cargas */
550         fprintf(f, "%013lld", 0); /* TODO: transportador de passageiros */
551         fprintf(f, "%013lld", 0); /* TODO: retistuição imposto anos anteriores */
552 }
553
554 static void gera_exclusivos(struct declaracao *dec, FILE *f)
555 {
556         fprintf(f, "24");
557         fprintf(f, "%-11.11s", dec->cpf);
558         fprintf(f, "%013lld", totais_get(dec, "DECIMOTERCEIRO"));
559         fprintf(f, "%013lld", 0); /* TODO: ganho de capital */
560         fprintf(f, "%013lld", 0); /* TODO: ganho líquido renda variável */
561         fprintf(f, "%013lld", totais_get(dec, "APLICACOES")); /* TODO: aplicações financeiras */
562         fprintf(f, "%013lld", 0); /* TODO: outros */
563         fprintf(f, "%-60.60s", ""); /* FILLER1 */
564         fprintf(f, "%013lld", 0); /* TODO: ganhos de capital alienação de bens */
565         fprintf(f, "%013lld", 0); /* TODO: ganhos de capital moeda estrangeira */
566         fprintf(f, "%013lld", 0); /* TODO: décimo terceiro dependentes */
567         fprintf(f, "%-13.13s", ""); /* FILLER2 */
568         fprintf(f, "%-60.60s", ""); /* FILLER3 */
569         fprintf(f, "%013lld", 0); /* TODO: RRA */
570         fprintf(f, "%013lld", 0); /* TODO: RRA dependentes */
571         fprintf(f, "%013lld", 0); /* TODO: Juros capital próprio */
572         fprintf(f, "%013lld", totais_get(dec, "PLR"));
573 }
574
575 static void gera_conjuge(struct declaracao *dec, FILE *f)
576 {
577         fprintf(f, "29");
578         fprintf(f, "%-11.11s", dec->cpf);
579         fprintf(f, "%-11.11s", dec->conjuge.cpf);
580         fprintf(f, "%013lld", dec->conjuge.base);
581         fprintf(f, "%013lld", dec->conjuge.imposto);
582         fprintf(f, "%013lld", dec->conjuge.isento);
583         fprintf(f, "%013lld", dec->conjuge.exclusivo);
584         fprintf(f, "%013lld", dec->conjuge.rendpj_exigibilidade_suspensa);
585         fprintf(f, "%013lld", dec->conjuge.total);
586         fprintf(f, "%c", dec->conjuge.entregou ? 'S' : 'N');
587 }
588
589 static int is_trailler_filler(int ano, int i)
590 {
591         if (ano >= 2018) {
592                 return i == 29 || i == 31 || i == 33 || i == 36 || i == 37 || i == 44 || i == 82;
593         }
594         return i == 44;
595         /* Ano 2016, linha 29 é um FILLER, mas preenchida com múltiplos
596          * 0s. Como esta linha não é gerada na declaração de 2016, não
597          * deve constar aqui, e será contabilizada como 0. */
598         /* || (ano == 2016 && i == 29); */
599 }
600
601 static int is_trailler_spaces(int ano, int i)
602 {
603         return (ano == 2018 && i > 92);
604 }
605
606 static int is_trailler_empty(int ano, int i)
607 {
608         return (i == 57 || i == 64 || i == 79) ||
609                 (ano == 2015 && i == 49);
610 }
611
612 static void gera_trailler(struct declaracao *dec, FILE *f)
613 {
614         int i;
615         fprintf(f, "T9");
616         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
617         fprintf(f, "%06d", dec->linhas[0]);
618         for (i = 16; i < 100; i++) {
619                 if (is_trailler_filler(dec->ano, i))
620                         fprintf(f, "%-5.5s", "0"); /* FILLER */
621                 else if (is_trailler_spaces(dec->ano, i))
622                         fprintf(f, "%-5.5s", "");
623                 else if (is_trailler_empty(dec->ano, i))
624                         ;
625                 else if (dec->ano == 2018 && i == 92)
626                         fprintf(f, "%-5s", "0");
627                 else
628                         fprintf(f, "%05d", dec->linhas[i]);
629         }
630 }
631
632 static void gera_reciboheader(struct declaracao *dec, FILE *f)
633 {
634         fprintf(f, "HR");
635         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
636         fprintf(f, "%-3.3s", ""); /* FILLER */
637 }
638
639 static void gera_recibodetalhe(struct declaracao *dec, FILE *f)
640 {
641         fprintf(f, "DR");
642         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
643         fprintf(f, "%-3.3s", ""); /* FILLER */
644         fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
645         fprintf(f, "%-60.60s", dec->nome);
646         fprintf(f, "%-15.15s", dec->contribuinte.tipo_logradouro);
647         fprintf(f, "%-40.40s", dec->contribuinte.logradouro);
648         fprintf(f, "%-6.6s", dec->contribuinte.numero);
649         fprintf(f, "%-21.21s", dec->contribuinte.complemento ?: "");
650         fprintf(f, "%-19.19s", dec->contribuinte.bairro);
651         fprintf(f, "%-9.9s", dec->contribuinte.cep);
652         fprintf(f, "%04d", dec->contribuinte.cd_municipio);
653         fprintf(f, "%-40.40s", dec->contribuinte.municipio);
654         fprintf(f, "%-2.2s", dec->contribuinte.uf);
655         fprintf(f, "%-100.100s", ""); /* FILLER */
656         fprintf(f, "%-4.4s", ""); /* FILLER */
657         fprintf(f, "%-8.8s", ""); /* FILLER */
658         fprintf(f, "%-4.4s", dec->contribuinte.ddd ?: "");
659         fprintf(f, "%-9.9s", dec->contribuinte.telefone ?: "");
660         fprintf(f, "%s", dec->retifica ? "S" : "N"); /* Retificadora */
661         fprintf(f, "%013lld", totais_get(dec, "RENDTRIB")); /* Total tributavel */
662         fprintf(f, "%013lld", dec->devido); /* Imposto devido */
663         fprintf(f, "%013lld", dec->restituicao); /* Imposto a restituir */
664         fprintf(f, "%013lld", dec->pagar); /* Imposto a pagar */
665         fprintf(f, "%d", dec->pagar ? 1 : 0); /* TODO/FIXME: quotas */
666         fprintf(f, "%013lld", dec->pagar); /* TODO: valor quota */
667         fprintf(f, "%-3.3s", dec->banco ? : "000"); /* numero banco */
668         fprintf(f, "%-4.4s", dec->agencia ? : "0000"); /* numero agencia */
669         fprintf(f, " "); /* FILLER */
670         fprintf(f, "%d", 0); /* TODO: debito primeira quota */
671         fprintf(f, "%013lld", 0); /* TODO: imposto pago ganho de capital */
672         fprintf(f, "%-13.13s", dec->contacorrente ? : ""); /* numero conta */
673         fprintf(f, "%-2.2s", dec->dvconta ? : ""); /* DV conta */
674         fprintf(f, "%013lld", 0); /* TODO: imposto alienacao moeda estrangeira em especie */
675         if (dec->ano >= 2018) {
676                 fprintf(f, "%-2.2s%-9.9s", dec->contribuinte.ddd ?: "", dec->contribuinte.telefone ?: "");
677         }
678 }
679
680 static void gera_recibotrailler(struct declaracao *dec, FILE *f)
681 {
682         fprintf(f, "R9");
683         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
684         fprintf(f, "%-3.3s", ""); /* FILLER */
685         fprintf(f, "%010u", dec->rhash);
686 }
687
688 static void gera_rendimento(struct declaracao *dec, FILE *f)
689 {
690         struct rendimento *r;
691         r = list_get(dec->rendimento, dec->linhas[21]);
692         fprintf(f, "21");
693         fprintf(f, "%s", dec->cpf);
694         fprintf(f, "%-14.14s", r->cnpj);
695         fprintf(f, "%-60.60s", r->nome);
696         fprintf(f, "%013lld", r->rendimento);
697         fprintf(f, "%013lld", r->previdencia);
698         fprintf(f, "%013lld", r->decimoterceiro);
699         fprintf(f, "%013lld", r->imposto);
700         fprintf(f, "%-8.8s", r->saida);
701         fprintf(f, "%013lld", r->imposto_13o);
702 }
703
704 static void gera_pagamento(struct declaracao *dec, FILE *f)
705 {
706         struct pagamento *p;
707         p = list_get(dec->pagamentos, dec->linhas[26]);
708         fprintf(f, "26");
709         fprintf(f, "%s", dec->cpf);
710         fprintf(f, "%02d", p->codigo);
711         fprintf(f, "%05d", p->dependente);
712         fprintf(f, "%-14.14s", p->cnpj);
713         fprintf(f, "%-60.60s", p->nome);
714         fprintf(f, "%-11.11s", ""); /* TODO: NIT */
715         fprintf(f, "%013lld", p->pagamento);
716         fprintf(f, "%013lld", p->reembolso);
717         if (dec->ano >= 2016) {
718                 /* TODO: contribuição do ente público patrocinador (FUNPRESP?) */
719                 fprintf(f, "%013lld", 0);
720         }
721         fprintf(f, "%d", strlen(p->cnpj) == 11 ? 1 : 2);
722         /* Titular (T), Dependente (D), Alimentando (A), FIXME Alimentando */
723         fprintf(f, "%c", p->dependente ? 'D' : 'T');
724 }
725
726 static void gera_isento(struct declaracao *dec, FILE *f, int codigo)
727 {
728         struct isento *i;
729         i = isento_get(dec, codigo, dec->linhas[codigo]);
730         fprintf(f, "%02d", codigo);
731         fprintf(f, "%-11.11s", dec->cpf); /* Titular */
732         fprintf(f, "%05d", dec->linhas[codigo] + 1); /* Chave */
733         /* Titular (T), Dependente (D), Alimentando (A), FIXME Alimentando */
734         fprintf(f, "%c", i->dependente ? 'D' : 'T');
735         fprintf(f, "%-14.14s", i->cnpj);
736         fprintf(f, "%-60.60s", i->nome);
737         fprintf(f, "%013lld", i->valor);
738         if (i->dependente) {
739                 struct dependente *d;
740                 d = list_get(dec->dependentes, i->dependente - 1);
741                 fprintf(f, "%-11.11s", d ? d->cpf : "");
742         } else {
743                 fprintf(f, "%-11.11s", dec->cpf);
744         }
745 }
746
747 static void gera_doacao(struct declaracao *dec, FILE *f)
748 {
749         gera_isento(dec, f, 82);
750 }
751
752 static void gera_indenizacoes(struct declaracao *dec, FILE *f)
753 {
754         gera_isento(dec, f, 93);
755 }
756
757 static void gera_plr(struct declaracao *dec, FILE *f)
758 {
759         gera_isento(dec, f, 96);
760 }
761
762 static void gera_outrosisentos(struct declaracao *dec, FILE *f)
763 {
764         struct isento *i;
765         int codigo = 97;
766         i = isento_get(dec, codigo, dec->linhas[codigo]);
767         gera_isento(dec, f, codigo);
768         fprintf(f, "%d", i->exclusivo == 0 ? 1 : 2);
769         fprintf(f, "%-60.60s", i->descricao);
770 }
771
772 static void gera_poupanca(struct declaracao *dec, FILE *f)
773 {
774         gera_isento(dec, f, 98);
775 }
776
777 static void gera_aplicacoes(struct declaracao *dec, FILE *f)
778 {
779         gera_isento(dec, f, 99);
780 }
781
782 static void gera_dependente(struct declaracao *dec, FILE *f)
783 {
784         struct dependente *d;
785         d = list_get(dec->dependentes, dec->linhas[25]);
786
787         fprintf(f, "25");
788         fprintf(f, "%s", dec->cpf);
789         fprintf(f, "%05d", dec->linhas[25] + 1);
790         fprintf(f, "%02d", d->codigo);
791         fprintf(f, "%-60.60s", d->nome);
792         fprintf(f, "%-8.8s", d->dn);
793         fprintf(f, "%-11.11s", d->cpf);
794         /* TODO: Indicador de saída */
795         fprintf(f, " ");
796         if (dec->ano >= 2016) {
797                 /* TODO: NIT/PIS/PASEP de Pessoa Física no exterior */
798                 fprintf(f, "%-11.11s", "");
799         }
800 }
801
802 static void gera_bem(struct declaracao *dec, FILE *f)
803 {
804         struct bem *b;
805         b = list_get(dec->bens, dec->linhas[27]);
806
807         fprintf(f, "27");
808         fprintf(f, "%s", dec->cpf);
809         fprintf(f, "%02d", b->codigo);
810
811         /* FIXME: exterior */
812         fprintf(f, "0");
813         fprintf(f, "105"); /* código Brasil */
814
815         fprintf(f, "%-512.512s", b->descricao);
816         fprintf(f, "%013lld", b->valor_anterior);
817         fprintf(f, "%013lld", b->valor);
818
819         /* Imóvel */
820         fprintf(f, "%-40.40s", b->logradouro ?: "");
821         fprintf(f, "%-6.6s", b->numero ?: "");
822         fprintf(f, "%-40.40s", b->complemento ?: "");
823         fprintf(f, "%-40.40s", b->bairro ?: "");
824         fprintf(f, "%-9.9s", b->cep ?: "");
825         fprintf(f, "%-2.2s", b->uf ?: "");
826         fprintf(f, "%04d", b->cd_municipio);
827         fprintf(f, "%-40.40s", b->municipio ?: "");
828         /* FIXME: Registro de imóveis, Nao (0), Sim (1), Vazio (2) */
829         fprintf(f, "%d", b->registro ? 1 : 0);
830         fprintf(f, "%-40.40s", b->matricula ?: "");
831         fprintf(f, "%-40.40s", b->registro ?: "");
832         fprintf(f, "%011lld", b->area);
833         /* FIXME: Area, M2 (0), Ha (1), Vazio (2) */
834         fprintf(f, "%d", 0);
835         fprintf(f, "%-60.60s", b->cartorio ?: "");
836
837         /* Número de chave */
838         fprintf(f, "%05d", dec->linhas[27] + 1);
839 }
840
841 static void gera_carne(struct declaracao *dec, FILE *f)
842 {
843         struct carne *carne;
844         carne = list_get(dec->carne, dec->linhas[22]);
845         fprintf(f, "22");
846         fprintf(f, "%-11.11s", dec->cpf); /* Titular */
847         if (carne->dependente) {
848                 struct dependente *d;
849                 d = list_get(dec->dependentes, carne->dependente - 1);
850                 fprintf(f, "S%-11.11s", d ? d->cpf : ""); /* CPF dependente. */
851         } else {
852                 fprintf(f, "N%-11.11s", ""); /* Não é dependente. */
853         }
854         fprintf(f, "%02d", carne->mes);
855         fprintf(f, "%013lld", carne->rendimento);
856         fprintf(f, "%013lld", carne->alugueis); /* Aluguéis. */
857         fprintf(f, "%013lld", carne->outros); /* Outros. */
858         fprintf(f, "%013lld", carne->exterior); /* Exterior. */
859         fprintf(f, "%013lld", carne->caixa); /* Livro-caixa. */
860         fprintf(f, "%013lld", carne->alimentos); /* Pensão alimentícia. */
861         fprintf(f, "%013lld", carne->dependentes); /* Dedução com dependentes. */
862         fprintf(f, "%013lld", carne->previdencia); /* Previdência. */
863         fprintf(f, "%013lld", carne->base); /* Base cálculo. */
864         fprintf(f, "%013lld", carne->imposto); /* Imposto pago. */
865 }
866
867 typedef void (gera_linha)(struct declaracao *dec, FILE *f);
868
869 static void update_hash(struct declaracao *dec, char *buf, size_t len)
870 {
871         int r;
872         int linha;
873         r = sscanf(buf, "%2d", &linha);
874         if (r == 1 || !strncmp(buf, "T9", 2)) {
875                 dec->hash = crc32(dec->hash, buf, len - 2);
876                 dec->rhash = crc32(dec->rhash, buf, len - 2);
877                 return;
878         } else if (strncmp(buf, "R9", 2) && strncmp(buf, "IRPF", 4)) {
879                 dec->rhash = crc32(dec->rhash, buf, len - 2);
880         }
881 }
882
883 static int wrap(gera_linha fn, struct declaracao *dec, struct list *l)
884 {
885         FILE *m;
886         char *buf = NULL;
887         size_t bsize;
888         int linha;
889         int r;
890         uLong c = crc32(0L, Z_NULL, 0);
891         m = open_memstream(&buf, &bsize);
892         if (!m) {
893                 return -errno;
894         }
895         fn(dec, m);
896         dec->linhas[0]++;
897         fflush(m);
898
899         /* Calcula CRC32 para campo de controle dos registros. */
900         c = crc32(c, buf, bsize);
901         fprintf(m, "%010ld\r\n", c);
902
903         fclose(m);
904         r = sscanf(buf, "%2d", &linha);
905         if (r == 1 && linha >= 0 && linha < 100) {
906                 dec->linhas[linha]++;
907         }
908         update_hash(dec, buf, bsize);
909         return list_add(&l, buf);
910 }
911
912 static void insert_hash(struct declaracao *dec, char *irpf)
913 {
914         uLong c = crc32(0L, NULL, 0);
915         char cpf[13];
916         char crc[11];
917         snprintf(cpf, 13, "%-8.8s.DEC", dec->cpf);
918         c = crc32(c, cpf, 12);
919         snprintf(crc, 11, "%010ld", dec->hash);
920         memcpy(irpf + 101, crc, 10);
921         c = crc32(c, irpf, strlen(irpf) - 12);
922         snprintf(crc, 11, "%010ld", c);
923         memcpy(irpf + strlen(irpf) - 12, crc, 10);
924 }
925
926 static int gera(struct declaracao *dec, char *filename)
927 {
928         FILE *f;
929         int r = 0;
930         int i;
931         struct rendimento *rendimento;
932         struct carne *carne;
933         struct isento *isento;
934         struct pagamento *pagamento;
935         struct bem *bem;
936         struct dependente *dependente;
937         struct list *linhas;
938         char *buf;
939
940         linhas = list_new();
941         if (!linhas)
942                 return -ENOMEM;
943
944         dec->hash = crc32(0L, NULL, 0);
945         dec->rhash = crc32(0L, NULL, 0);
946
947 #define W(fn) \
948         do { \
949                 r = wrap(fn, dec, linhas); \
950                 if (r < 0) \
951                         goto out; \
952         } while (0);
953
954         f = fopen(filename, "w");
955         if (!f) {
956                 r = -errno;
957                 dec_set_error(dec, "Não foi possível abrir arquivo %s: %s.",
958                               filename, strerror(errno));
959                 goto out_file;
960         }
961         memset(dec->linhas, 0, sizeof(dec->linhas));
962         W(gera_header);
963         W(gera_contribuinte);
964         if (dec->tipo == COMPLETA) {
965                 W(gera_completa);
966                 W(gera_totais_completa);
967         } else {
968                 W(gera_simples);
969                 W(gera_totais_simples);
970         }
971         for (i = 0; rendimento = list_get(dec->rendimento, i); i++) {
972                 W(gera_rendimento);
973         }
974
975         for (i = 0; (carne = list_get(dec->carne, i)); i++) {
976                 W(gera_carne);
977         }
978
979         if (totais_get(dec, "ISENTOS"))
980                 W(gera_isentos);
981         if (totais_get(dec, "EXCLUSIVOS"))
982                 W(gera_exclusivos);
983
984         for (i = 0; (dependente = list_get(dec->dependentes, i)); i++) {
985                 W(gera_dependente);
986         }
987         for (i = 0; (pagamento = list_get(dec->pagamentos, i)); i++) {
988                 W(gera_pagamento);
989         }
990         for (i = 0; (bem = list_get(dec->bens, i)); i++) {
991                 W(gera_bem);
992         }
993
994         if (dec->ano == 2015 && dec->conjuge.cpf)
995                 W(gera_conjuge);
996
997         /* Rendimentos isentos e com tributação exclusiva */
998         /* Registros 82 a 89, e 92 a 99 */
999 #define IW(fn, codigo) \
1000         for (i = 0; ; i++) { \
1001                 isento = isento_get(dec, codigo, i); \
1002                 if (!isento) \
1003                         break; \
1004                 W(fn); \
1005         }
1006         IW(gera_doacao, 82);
1007         IW(gera_indenizacoes, 93);
1008         IW(gera_plr, 96);
1009         IW(gera_outrosisentos, 97);
1010         IW(gera_poupanca, 98);
1011         IW(gera_aplicacoes, 99);
1012
1013         W(gera_trailler);
1014         W(gera_reciboheader);
1015         W(gera_recibodetalhe);
1016         W(gera_recibotrailler);
1017
1018         insert_hash(dec, list_get(linhas, 0));
1019         for (i = 0; (buf = list_get(linhas, i)); i++) {
1020                 fwrite(buf, strlen(buf), 1, f);
1021         }
1022
1023         fclose(f);
1024         list_free(linhas, free);
1025         return 0;
1026 out:
1027         fclose(f);
1028 out_file:
1029         list_free(linhas, free);
1030         return r;
1031 }
1032
1033 static int run_gera(struct declaracao *dec, char **args, int argc)
1034 {
1035         if (argc != 2) {
1036                 dec_set_error(dec, "Comando %s recebe um nome de arquivo como parâmetro.",
1037                               args[0]);
1038                 return -EINVAL;
1039         }
1040         if (!ANO_VALIDO(dec->ano)) {
1041                 dec_set_error(dec, "Comando %s não suporta ano %d.",
1042                               args[0], dec->ano);
1043                 return -EINVAL;
1044         }
1045         return gera(dec, args[1]);
1046 }
1047
1048 static struct cmd cmd_gera = {
1049         .name = "gera",
1050         .run = run_gera,
1051 };
1052
1053 int gera_cmd_init(void)
1054 {
1055         cmd_add(&cmd_gera);
1056         return 0;
1057 }