Suporta bens móveis.
[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 "declaracao.h"
25 #include "cmd.h"
26 #include "rendimento.h"
27 #include "pagamento.h"
28 #include "bem.h"
29 #include "totais.h"
30
31 static void gera_header(struct declaracao *dec, FILE *f)
32 {
33         fprintf(f, "IRPF    ");
34         fprintf(f, "%04d", dec->ano); /* Exercício */
35         fprintf(f, "%04d", dec->ano - 1); /* Ano base */
36         fprintf(f, "2500"); /* Código */
37         fprintf(f, "%s", dec->retifica ? "1" : "0"); /* Retificadora */
38         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
39         fprintf(f, "   "); /* Filler */
40         fprintf(f, "1"); /* Tipo NI: Pessoa Física (1) */
41         fprintf(f, "100"); /* Versão IRPF */
42         fprintf(f, "%-60.60s", dec->nome);
43         fprintf(f, "%s", dec->contribuinte.uf);
44         fprintf(f, "%s", "0000000000"); /* FIXME: hash */
45         fprintf(f, "1"); /* TODO: certificavel */
46         fprintf(f, "%s", dec->contribuinte.dn);
47         fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
48         fprintf(f, "%s", dec->restituicao ? "2" : "0"); /* TODO: resultado imposto, 2 - restituicao */
49         fprintf(f, "S"); /* TODO: gerada? */
50         fprintf(f, "%-10.10s", dec->retifica ?: ""); /* recibo retificada ex. atual */
51         fprintf(f, "2"); /* TODO: PGD */
52         fprintf(f, "LINUX         "); /* TODO: SO */
53         fprintf(f, "3.16.0-"); /* TODO: versao SO */
54         fprintf(f, "1.7.0_75 "); /* TODO: versao JVM */
55         fprintf(f, "%-10.10s", ""); /* TODO: última declaração transmitida (pode ser vazio?) */
56         fprintf(f, "%04d", dec->contribuinte.cd_municipio);
57         fprintf(f, "           "); /* TODO: CPF conjuge */
58         fprintf(f, "%d", dec->obrigatoria ? 1 : 0); /* obrigatoria entrega */
59         fprintf(f, "%013lld", dec->devido); /* imposto devido, carne-leao, complementar dos dependentes */
60         fprintf(f, "%-10.10s", dec->recibo ?: ""); /* recibo ex. anterior */
61         /* Indicador de segurança: 0 se retificadora, 2 se recibo
62          * anterior, se não 1. */
63         fprintf(f, "%d", dec->retifica ? 0 : (dec->recibo ? 2 : 1));
64         /* Indicador imposto pago, TODO: carnê leão e Lei 11.033. */
65         fprintf(f, "%02d", dec->retido ? 1 : 0);
66         /* Indicador imposto antecipado, TODO: carnê leão, Lei 11.033,
67          * outros. */
68         fprintf(f, "%d", dec->retido ? 1 : 0);
69         fprintf(f, "0"); /* TODO: mudanca endereco */
70         fprintf(f, "%s", dec->contribuinte.cep);
71         fprintf(f, "0"); /* TODO: debito 1a quota */
72         fprintf(f, "%-3.3s", dec->banco); /* no banco */
73         fprintf(f, "%-4.4s", dec->agencia); /* agencia */
74         fprintf(f, " "); /* TODO: filler */
75         fprintf(f, "00000000"); /* transito julgado, gravado apenas se espolio */
76         fprintf(f, "%013lld", dec->pagar); /* imposto a pagar */
77         fprintf(f, " "); /* RRA1 */
78         fprintf(f, "%-11.11s", ""); /* CPF RRA1 */
79         fprintf(f, " "); /* RRA2 */
80         fprintf(f, "%-11.11s", ""); /* CPF RRA2 */
81         fprintf(f, " "); /* RRA3 */
82         fprintf(f, "%-11.11s", ""); /* CPF RRA3 */
83         fprintf(f, " "); /* RRA4 */
84         fprintf(f, "%-11.11s", ""); /* CPF RRA4 */
85         fprintf(f, "0000000000000"); /* TODO: Doacao ECA */
86         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0)); /* TODO: CNPJ maior */
87         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 1)); /* TODO: CNPJ maior 2 */
88         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 2)); /* TODO: CNPJ maior 3 */
89         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 3)); /* TODO: CNPJ maior 4 */
90         fprintf(f, "%-11.11s", ""); /* CPF Dependente 1 */
91         fprintf(f, "%-8.8s", ""); /* DN Dependente 1 */
92         fprintf(f, "%-11.11s", ""); /* CPF Dependente 2 */
93         fprintf(f, "%-8.8s", ""); /* DN Dependente 2 */
94         fprintf(f, "%-11.11s", ""); /* CPF Dependente 3 */
95         fprintf(f, "%-8.8s", ""); /* DN Dependente 3 */
96         fprintf(f, "%-11.11s", ""); /* CPF Dependente 4 */
97         fprintf(f, "%-8.8s", ""); /* DN Dependente 4 */
98         fprintf(f, "%-11.11s", ""); /* CPF Dependente 5 */
99         fprintf(f, "%-8.8s", ""); /* DN Dependente 5 */
100         fprintf(f, "%-11.11s", ""); /* CPF Dependente 6 */
101         fprintf(f, "%-8.8s", ""); /* DN Dependente 6 */
102         /* medico maior, TODO: outros códigos */
103         fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 26, 0));
104         /* medico maior 2, TODO: outros códigos */
105         fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 26, 1));
106         fprintf(f, "%-11.11s", ""); /* CPF pensao */
107         fprintf(f, "%-11.11s", ""); /* CPF inventariante */
108         fprintf(f, "%-40.40s", dec->contribuinte.municipio);
109         fprintf(f, "%-60.60s", dec->nome);
110         fprintf(f, "%-11.11s", ""); /* CPF empregada */
111         fprintf(f, "000000000000"); /* FIXME: MAC */
112         fprintf(f, "%08d", 0); /* Data saída */
113         fprintf(f, "%-11.11s", ""); /* CPF procurador */
114         fprintf(f, "%03d", dec->obrigatoria); /* criterio obrigatoriedade */
115         fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* Total tributavel */
116         /* CNPJ previdencia */
117         fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 36, 0));
118         /* CNPJ previdencia 2 */
119         fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 36, 1));
120         /* Total isentos */
121         fprintf(f, "%013lld", totais_get(dec, "ISENTOS"));
122         /* Total exclusivo */
123         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS"));
124         /* Total pagamentos */
125         fprintf(f, "%013lld", totais_get(dec, "PAGAMENTOS"));
126         fprintf(f, "%-13.13s", dec->contacorrente); /* numero conta */
127         fprintf(f, "%-2.2s", dec->dvconta); /* DV conta */
128         fprintf(f, "0"); /* TODO: revalidar DV conta */
129
130         /* Mudanças de 2015 */
131
132         fprintf(f, "%02d", dec->contribuinte.natureza_ocupacao); /* natureza ocupacao */
133         fprintf(f, "%-11.11s", ""); /* CPF domestica */
134         fprintf(f, "%-11.11s", ""); /* NI domestica */
135         fprintf(f, "%-11.11s", ""); /* CPF domestica 2 */
136         fprintf(f, "%-11.11s", ""); /* NI domestica 2 */
137         fprintf(f, "%-11.11s", ""); /* CPF domestica 3 */
138         fprintf(f, "%-11.11s", ""); /* NI domestica 3 */
139         fprintf(f, "1"); /* Declaracao iniciada */
140         fprintf(f, "1"); /* Utilizou PGD */
141         fprintf(f, "0"); /* Utilizou APP */
142         fprintf(f, "0"); /* Utilizou online */
143         fprintf(f, "0"); /* Utilizou rascunho */
144         fprintf(f, "0"); /* Utilizou pre preenchida */
145         fprintf(f, "0"); /* Utilizou fontes */
146         fprintf(f, "0"); /* Utilizou plano saude */
147         fprintf(f, "0"); /* Utilizou recuperar */
148         fprintf(f, "1"); /* Declaracao iniciada */
149
150         /* Fim das mudanças de 2015 */
151
152         fprintf(f, "   "); /* Teste PGD, FILLER2 */
153         fprintf(f, "0000000000"); /* FIXME: controle */
154         fprintf(f, "\r\n");
155 }
156
157 static void gera_contribuinte(struct declaracao *dec, FILE *f)
158 {
159         fprintf(f, "16");
160         fprintf(f, "%s", dec->cpf);
161         fprintf(f, "%-60.60s", dec->nome);
162         fprintf(f, "%-15.15s", dec->contribuinte.tipo_logradouro);
163         fprintf(f, "%-40.40s", dec->contribuinte.logradouro);
164         fprintf(f, "%-6.6s", dec->contribuinte.numero);
165         fprintf(f, "%-21.21s", dec->contribuinte.complemento);
166         fprintf(f, "%-19.19s", dec->contribuinte.bairro);
167         fprintf(f, "%-9.9s", dec->contribuinte.cep);
168         fprintf(f, "%04d", dec->contribuinte.cd_municipio);
169         fprintf(f, "%-40.40s", dec->contribuinte.municipio);
170         fprintf(f, "%-2.2s", dec->contribuinte.uf);
171         fprintf(f, "   "); /* TODO: código exterior */
172         fprintf(f, "105"); /* TODO: código país */
173         fprintf(f, "%-100.100s", ""); /* TODO: FILLER3 */
174         fprintf(f, "%-4.4s", ""); /* TODO: FILLER1 */
175         fprintf(f, "%-8.8s", ""); /* TODO: FILLER2 */
176         fprintf(f, "%-4.4s", dec->contribuinte.ddd);
177         fprintf(f, "%-9.9s", dec->contribuinte.telefone);
178         fprintf(f, "%-8.8s", dec->contribuinte.dn);
179         fprintf(f, "%-13.13s", dec->contribuinte.titulo_eleitor);
180         fprintf(f, "%03d", dec->contribuinte.ocupacao_principal);
181         fprintf(f, "%02d", dec->contribuinte.natureza_ocupacao);
182         fprintf(f, "0"); /* TODO: qnt quotas */
183         fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
184         fprintf(f, "%s", dec->retifica ? "S" : "N");
185         fprintf(f, "S"); /* GERADO */
186         fprintf(f, "N"); /* TODO: mudança de endereço */
187         fprintf(f, "%-12.12s", dec->retifica ? : ""); /* Recibo declaração original */
188         fprintf(f, "%-3.3s", dec->banco); /* banco */
189         fprintf(f, "%-4.4s", dec->agencia); /* agência */
190         fprintf(f, "N"); /* TODO: deficiência */
191         fprintf(f, "0"); /* FILLER: pré-preenchida */
192         fprintf(f, "%-13.13s", dec->contacorrente); /* conta */
193         fprintf(f, "%-2.2s", dec->dvconta); /* DV conta */
194         fprintf(f, "N"); /* TODO: débito automático */
195         fprintf(f, "0"); /* TODO: débito primeira quota */
196         /* CNPJ principal fonte */
197         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0));
198         fprintf(f, "%-10.10s", dec->recibo ?: ""); /* Recibo última declaração ano anterior */
199         fprintf(f, "A"); /* Declaração de Ajuste */
200         fprintf(f, "%-11.11s", ""); /* TODO: CPF procurador */
201         fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
202         fprintf(f, "\r\n");
203 }
204
205 static void gera_simples(struct declaracao *dec, FILE *f)
206 {
207         fprintf(f, "17");
208         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
209         fprintf(f, "%013lld", 0); /* TODO: carnê leão */
210         fprintf(f, "%013lld", 0); /* TODO: lucros e dividendos */
211         /* rendimentos isentos */
212         fprintf(f, "%013lld", totais_get(dec, "ISENTOS"));
213         /* rendimentos tributação exclusiva, exceto décimo terceiro */
214         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS_SEM_13o"));
215         /* 13o. */
216         fprintf(f, "%013lld", totais_get(dec, "DECIMOTERCEIRO"));
217         fprintf(f, "%013lld", 0); /* TODO: retido na fonte (Lei 11.033) */
218         fprintf(f, "%013lld", 0); /* TODO: 13o. dependentes */
219         fprintf(f, "%013lld", 0); /* TODO: lucros dependentes */
220         fprintf(f, "%013lld", 0); /* TODO: isentos dependentes */
221         fprintf(f, "%013lld", 0); /* TODO: exclusivos dependentes */
222         fprintf(f, "%-13.13s", ""); /* FILLER */
223         fprintf(f, "%-13.13s", ""); /* FILLER */
224         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF */
225         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF dependentes */
226         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior */
227         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF ext. depend. */
228         fprintf(f, "%013lld", 0); /* TODO: carnê-leão PF? */
229         fprintf(f, "%013lld", 0); /* TODO: carnê-leão dependentes */
230         fprintf(f, "%013lld", 0); /* TODO: dedução dependentes */
231         fprintf(f, "%013lld", 0); /* TODO: previdência RRA */
232         fprintf(f, "%013lld", 0); /* TODO: previdência RRA dependentes */
233         fprintf(f, "%013lld", 0); /* TODO: pensão RRA */
234         fprintf(f, "%013lld", 0); /* TODO: pensão RRA dependentes */
235         fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
236         fprintf(f, "%013lld", 0); /* TODO: imposto devido sem rendimento exterior */
237         fprintf(f, "%013lld", 0); /* TODO: limite imposto pago exterior */
238         fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
239         fprintf(f, "\r\n");
240 }
241
242 static void gera_totais_simples(struct declaracao *dec, FILE *f)
243 {
244         fprintf(f, "18");
245         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
246         fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* TODO: rendimentos tributáveis */
247         /* desconto simplificado */
248         fprintf(f, "%013lld", totais_get(dec, "DESCONTO"));
249          /* base de cálculo */
250         fprintf(f, "%013lld", totais_get(dec, "BASE"));
251         fprintf(f, "%013lld", dec->devido); /* imposto devido */
252         fprintf(f, "%013lld", dec->retido); /* imposto retido */
253         fprintf(f, "%013lld", 0); /* TODO: imposto complementar */
254         fprintf(f, "%013lld", 0); /* TODO: carnê-leão */
255         fprintf(f, "%013lld", 0); /* TODO: imposto retido Lei 11.033 */
256         fprintf(f, "%013lld", dec->restituicao); /* imposto a restituir */
257         fprintf(f, "%013lld", dec->pagar); /* imposto pagar */
258         fprintf(f, "%d", 0); /* TODO: quotas */
259         fprintf(f, "%013lld", 0); /* TODO: valor quota */
260         fprintf(f, "%013lld", totais_get(dec, "ISENTOS")); /* rendimentos isentos */
261         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS")); /* rendimentos tributação exclusiva */
262         fprintf(f, "%013lld", 0); /* TODO: conjuge */
263         fprintf(f, "%013lld", 0); /* TODO: rendimento PJ dependente */
264         fprintf(f, "%013lld", 0); /* TODO: imposto retido dependente */
265         fprintf(f, "%013lld", 0); /* TODO: imposto ganhos de capital */
266         fprintf(f, "%013lld", totais_get(dec, "RENDPJTIT")); /* rendimento tributável PJ titular */
267         fprintf(f, "%013lld", 0); /* TODO: total rural */
268         fprintf(f, "%013lld", dec->retido); /* imposto retido titular */
269         fprintf(f, "%013lld", totais_get(dec, "BENSANTERIOR")); /* total bens ano anterior */
270         fprintf(f, "%013lld", totais_get(dec, "BENS")); /* total bens ano base */
271         fprintf(f, "%013lld", totais_get(dec, "ISENTOSTIT")); /* rendimentos isentos titular */
272         fprintf(f, "%013lld", 0); /* TODO: rendimentos isentos dependentes */
273         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSTIT")); /* TODO: tributação exclusiva titular */
274         fprintf(f, "%013lld", 0); /* TODO: tributação exclusiva dependentes */
275         fprintf(f, "%013lld", 0); /* TODO: total não tributável */
276         fprintf(f, "%013lld", 0); /* TODO: total dívidas ano anterior */
277         fprintf(f, "%013lld", 0); /* TODO: total dívidas ano base */
278         fprintf(f, "%013lld", 0); /* TODO: retido fonte Lei 11.033 */
279         fprintf(f, "%013lld", 0); /* TODO: isentos e não tributáveis, transportado */
280         fprintf(f, "%013lld", 0); /* TODO: tributação exclusiva, transportado */
281         fprintf(f, "%013lld", 0); /* TODO: ganhos líquidos renda variável */
282         fprintf(f, "%013lld", 0); /* TODO: parcela isenta ganhos capital */
283         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior titular */
284         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior dependentes */
285         fprintf(f, "%013lld", 0); /* TODO: doações campanha */
286         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa titular */
287         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa dependentes */
288         fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa titular */
289         fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa dependentes */
290         fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA titular */
291         fprintf(f, "%013lld", 0); /* TODO: IRF RRA titular */
292         fprintf(f, "%013lld", 0); /* TODO: imposto RRA titular */
293         fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA dependentes */
294         fprintf(f, "%013lld", 0); /* TODO: IRF RRA dependentes */
295         fprintf(f, "%013lld", 0); /* TODO: imposto RRA dependentes */
296         fprintf(f, "%013lld", dec->devido); /* imposto devido */
297         fprintf(f, "%013lld", 0); /* TODO: imposto diferido ganho capital */
298         fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital */
299         fprintf(f, "%013lld", 0); /* TODO: imposto ganho líquido renda variável */
300         fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital moeda estrangeira */
301         fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
302         fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
303         fprintf(f, "\r\n");
304 }
305
306 static void gera_completa(struct declaracao *dec, FILE *f)
307 {
308         fprintf(f, "19");
309         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
310         fprintf(f, "%-14.14s", ""); /* TODO: CNPJ maior */
311         /* FIXME: completar campos */
312         fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
313         fprintf(f, "\r\n");
314 }
315
316 static void gera_totais_completa(struct declaracao *dec, FILE *f)
317 {
318         fprintf(f, "20");
319         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
320         /* FIXME: completar campos */
321         fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
322         fprintf(f, "\r\n");
323 }
324
325 static void gera_trailler(struct declaracao *dec, FILE *f)
326 {
327         int i;
328         fprintf(f, "T9");
329         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
330         fprintf(f, "%06d", dec->linhas[0]);
331         for (i = 16; i < 100; i++)
332                 if (i == 44)
333                         fprintf(f, "%-5.5s", "0"); /* FILLER */
334                 else if (i == 49 || i == 57 || i == 64 || i == 79)
335                         ;
336                 else
337                         fprintf(f, "%05d", dec->linhas[i]);
338         fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
339         fprintf(f, "\r\n");
340 }
341
342 static void gera_reciboheader(struct declaracao *dec, FILE *f)
343 {
344         fprintf(f, "HR");
345         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
346         fprintf(f, "%-3.3s", ""); /* FILLER */
347         fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
348         fprintf(f, "\r\n");
349 }
350
351 static void gera_recibodetalhe(struct declaracao *dec, FILE *f)
352 {
353         fprintf(f, "DR");
354         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
355         fprintf(f, "%-3.3s", ""); /* FILLER */
356         fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
357         fprintf(f, "%-60.60s", dec->nome);
358         fprintf(f, "%-15.15s", dec->contribuinte.tipo_logradouro);
359         fprintf(f, "%-40.40s", dec->contribuinte.logradouro);
360         fprintf(f, "%-6.6s", dec->contribuinte.numero);
361         fprintf(f, "%-21.21s", dec->contribuinte.complemento);
362         fprintf(f, "%-19.19s", dec->contribuinte.bairro);
363         fprintf(f, "%-9.9s", dec->contribuinte.cep);
364         fprintf(f, "%04d", dec->contribuinte.cd_municipio);
365         fprintf(f, "%-40.40s", dec->contribuinte.municipio);
366         fprintf(f, "%-2.2s", dec->contribuinte.uf);
367         fprintf(f, "%-100.100s", ""); /* FILLER */
368         fprintf(f, "%-4.4s", ""); /* FILLER */
369         fprintf(f, "%-8.8s", ""); /* FILLER */
370         fprintf(f, "%-4.4s", dec->contribuinte.ddd);
371         fprintf(f, "%-9.9s", dec->contribuinte.telefone);
372         fprintf(f, "%s", dec->retifica ? "S" : "N"); /* Retificadora */
373         fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* Total tributavel */
374         fprintf(f, "%013lld", dec->devido); /* Imposto devido */
375         fprintf(f, "%013lld", dec->restituicao); /* Imposto a restituir */
376         fprintf(f, "%013lld", dec->pagar); /* Imposto a pagar */
377         fprintf(f, "%d", 0); /* TODO: quotas */
378         fprintf(f, "%013lld", 0); /* TODO: valor quota */
379         fprintf(f, "%-3.3s", dec->banco); /* numero banco */
380         fprintf(f, "%-4.4s", dec->agencia); /* numero agencia */
381         fprintf(f, " "); /* FILLER */
382         fprintf(f, "%d", 0); /* TODO: debito primeira quota */
383         fprintf(f, "%013lld", 0); /* TODO: imposto pago ganho de capital */
384         fprintf(f, "%-13.13s", dec->contacorrente); /* numero conta */
385         fprintf(f, "%-2.2s", dec->dvconta); /* DV conta */
386         fprintf(f, "%013lld", 0); /* TODO: imposto alienacao moeda estrangeira em especie */
387         fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
388         fprintf(f, "\r\n");
389 }
390
391 static void gera_recibotrailler(struct declaracao *dec, FILE *f)
392 {
393         fprintf(f, "R9");
394         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
395         fprintf(f, "%-3.3s", ""); /* FILLER */
396         fprintf(f, "%-10.10s", "0000000000"); /* FIXME: hash */
397         fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
398         fprintf(f, "\r\n");
399 }
400
401 static void gera_rendimento(struct declaracao *dec, FILE *f)
402 {
403         struct rendimento *r;
404         r = list_get(dec->rendimento, dec->linhas[21]);
405         fprintf(f, "21");
406         fprintf(f, "%s", dec->cpf);
407         fprintf(f, "%-14.14s", r->cnpj);
408         fprintf(f, "%-60.60s", r->nome);
409         fprintf(f, "%013lld", r->rendimento);
410         fprintf(f, "%013lld", r->previdencia);
411         fprintf(f, "%013lld", r->decimoterceiro);
412         fprintf(f, "%013lld", r->imposto);
413         fprintf(f, "%-8.8s", r->saida);
414         fprintf(f, "%013lld", r->imposto_13o);
415         fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
416         fprintf(f, "\r\n");
417 }
418
419 static void gera_pagamento(struct declaracao *dec, FILE *f)
420 {
421         struct pagamento *p;
422         p = list_get(dec->pagamentos, dec->linhas[26]);
423         fprintf(f, "26");
424         fprintf(f, "%s", dec->cpf);
425         fprintf(f, "%02d", p->codigo);
426         fprintf(f, "%05d", 0); /* TODO: chave dependente */
427         fprintf(f, "%-14.14s", p->cnpj);
428         fprintf(f, "%-60.60s", p->nome);
429         fprintf(f, "%-11.11s", ""); /* TODO: NIT */
430         fprintf(f, "%013lld", p->pagamento);
431         fprintf(f, "%013lld", p->reembolso);
432         /* CPF (1?) ou CNPJ (2), FIXME */
433         fprintf(f, "2");
434         /* Titular (T), Dependente (D), Alimentando (A), FIXME */
435         fprintf(f, "T");
436         fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
437         fprintf(f, "\r\n");
438 }
439
440 static void gera_bem(struct declaracao *dec, FILE *f)
441 {
442         struct bem *b;
443         b = list_get(dec->bens, dec->linhas[27]);
444
445         fprintf(f, "27");
446         fprintf(f, "%s", dec->cpf);
447         fprintf(f, "%02d", b->codigo);
448
449         /* FIXME: exterior */
450         fprintf(f, "0");
451         fprintf(f, "105"); /* código Brasil */
452
453         fprintf(f, "%-512.512s", b->descricao);
454         fprintf(f, "%013lld", b->valor_anterior);
455         fprintf(f, "%013lld", b->valor);
456
457         /* Imóvel */
458         fprintf(f, "%-40.40s", b->logradouro ?: "");
459         fprintf(f, "%-6.6s", b->numero ?: "");
460         fprintf(f, "%-40.40s", b->complemento ?: "");
461         fprintf(f, "%-40.40s", b->bairro ?: "");
462         fprintf(f, "%-9.9s", b->cep ?: "");
463         fprintf(f, "%-2.2s", b->uf ?: "");
464         fprintf(f, "%04d", b->cd_municipio);
465         fprintf(f, "%-40.40s", b->municipio ?: "");
466         /* FIXME: Registro de imóveis, Nao (0), Sim (1), Vazio (2) */
467         fprintf(f, "%d", b->registro ? 1 : 0);
468         fprintf(f, "%-40.40s", b->matricula ?: "");
469         fprintf(f, "%-40.40s", b->registro ?: "");
470         fprintf(f, "%011lld", b->area);
471         /* FIXME: Area, M2 (0), Ha (1), Vazio (2) */
472         fprintf(f, "%d", 0);
473         fprintf(f, "%-60.60s", b->cartorio ?: "");
474
475         /* Número de chave */
476         fprintf(f, "%05d", dec->linhas[27] + 1);
477
478         fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
479         fprintf(f, "\r\n");
480 }
481
482
483
484 typedef void (gera_linha)(struct declaracao *dec, FILE *f);
485
486 static int wrap(gera_linha fn, struct declaracao *dec, FILE *f)
487 {
488         FILE *m;
489         char *buf = NULL;
490         size_t bsize;
491         int linha;
492         int r;
493         m = open_memstream(&buf, &bsize);
494         if (!m) {
495                 return -errno;
496         }
497         fn(dec, m);
498         dec->linhas[0]++;
499         fclose(m);
500         r = sscanf(buf, "%2d", &linha);
501         if (r == 1 && linha >= 0 && linha < 100) {
502                 dec->linhas[linha]++;
503         }
504         fwrite(buf, bsize, 1, f);
505         free(buf);
506         return 0;
507 }
508
509 static int gera(struct declaracao *dec, char *filename)
510 {
511         FILE *f;
512         int r;
513         int i;
514         struct rendimento *rendimento;
515         struct pagamento *pagamento;
516         struct bem *bem;
517
518 #define W(fn, dec, f) \
519         do { \
520                 r = wrap(fn, dec, f); \
521                 if (r < 0) \
522                         goto out; \
523         } while (0);
524
525         f = fopen(filename, "w");
526         if (!f)
527                 return -errno;
528         memset(dec->linhas, 0, sizeof(dec->linhas));
529         W(gera_header, dec, f);
530         W(gera_contribuinte, dec, f);
531         if (dec->tipo == COMPLETA) {
532                 W(gera_completa, dec, f);
533                 W(gera_totais_completa, dec, f);
534         } else {
535                 W(gera_simples, dec, f);
536                 W(gera_totais_simples, dec, f);
537         }
538         for (i = 0; rendimento = list_get(dec->rendimento, i); i++) {
539                 W(gera_rendimento, dec, f);
540         }
541         for (i = 0; (pagamento = list_get(dec->pagamentos, i)); i++) {
542                 W(gera_pagamento, dec, f);
543         }
544         for (i = 0; (bem = list_get(dec->bens, i)); i++) {
545                 W(gera_bem, dec, f);
546         }
547         W(gera_trailler, dec, f);
548         W(gera_reciboheader, dec, f);
549         W(gera_recibodetalhe, dec, f);
550         W(gera_recibotrailler, dec, f);
551         fclose(f);
552         return 0;
553 out:
554         fclose(f);
555         return r;
556 }
557
558 static int run_gera(struct declaracao *dec, char **args, int argc)
559 {
560         if (argc != 2)
561                 return -EINVAL;
562         return gera(dec, args[1]);
563 }
564
565 static struct cmd cmd_gera = {
566         .name = "gera",
567         .run = run_gera,
568 };
569
570 int gera_cmd_init(void)
571 {
572         cmd_add(&cmd_gera);
573         return 0;
574 }