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