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