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