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