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