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