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