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