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