· 8 years ago · Feb 22, 2018, 01:24 PM
1create or replace function fc_parcelamento(integer,date,date,integer,integer,float8,integer,integer,integer,integer,float8,float8,text,integer)
2returns varchar(100)
3as $$
4declare
5
6 v_cgmresp alias for $1; -- cgm do responsavel pelo parcelamento
7 v_privenc alias for $2; -- vencimento da entrada
8 v_segvenc alias for $3; -- vencimento da parcela 2
9 v_diaprox alias for $4; -- dia de vencimento da parcela 3 em diante
10 v_totparc alias for $5; -- total de parcelas
11 v_entrada alias for $6; -- valor da entrada
12 v_login alias for $7; -- login de quem fez o parcelamento
13 v_cadtipo alias for $8; -- tipo de debito dos registros selecionados
14 v_desconto alias for $9; -- regra de parcelamento utilizada
15 v_temdesconto alias for $10; -- se tem desconto (nao utilizada)
16 v_valorparcela alias for $11; -- valor de cada parcela
17 v_valultimaparcela alias for $12; -- valor da ultima parcela
18
19 sObservacao alias for $13; -- observacao do parcelamento
20 iProcesso alias for $14; -- codigo do processo (protprocesso)
21
22 v_ultparc integer default 2;
23 v_matric integer default 0;
24 v_inscr integer default 0;
25
26 iUltMatric integer;
27 iUltNumpre integer;
28 iUltNumpar integer;
29 iUltReceit integer;
30
31 iSeqArrecKey integer;
32 iSeqArrecadcompos integer;
33
34 v_anousu integer;
35 v_totpar integer;
36 v_cgmpri integer;
37 v_somar1 integer;
38 v_somar2 integer;
39 v_numpre integer;
40 v_receita integer;
41 v_termo integer;
42 v_termo_ori integer;
43 v_tipo integer;
44 v_tiponovo integer;
45 v_quantparcel integer;
46 v_var integer;
47 v_inicialmov integer;
48 v_totparcdestarec integer;
49 v_contador integer;
50 v_cadtipoparc integer;
51 v_recdestino integer;
52 v_dia integer;
53 v_ultdiafev integer;
54 v_maxrec integer;
55 v_anovenc integer;
56 v_mesvenc integer;
57 v_totalparcelas integer;
58 v_anovencprox integer;
59 v_mesvencprox integer;
60 v_recjurosultima integer;
61 v_recmultaultima integer;
62 v_histjuro integer;
63 v_proxmessegvenc integer;
64 iInstit integer;
65 iAnousu integer;
66 iQtdRegistrosMatricula integer;
67 iQtdRegistrosInscricao integer;
68 ultimaparcelareceita integer;
69
70 v_totaldivida numeric default 0;
71 v_somar numeric default 0;
72 v_totalliquido numeric default 0;
73 v_total_liquido numeric default 0;
74 v_totalzao numeric default 0;
75
76 v_calcula_valprop numeric(15,10);
77 v_calcula_valor float8 default 0;
78 v_calcula_his numeric(15,2);
79 v_calcula_cor numeric(15,2);
80 v_calcula_jur numeric(15,2);
81 v_calcula_mul numeric(15,2);
82 v_calcula_desccor numeric(15,2);
83 v_calcula_descjur numeric(15,2);
84 v_calcula_descmul numeric(15,2);
85 nValorMaximoReceita numeric(15,2);
86 nValorMaximoHistorico numeric(15,2);
87 nValorMaximoCorrecao numeric(15,2);
88 nValorMaximoJuro numeric(15,2);
89 nValorMaximoMulta numeric(15,2);
90 nValorMaximoDescontoCorrecao numeric(15,2);
91 nValorMaximoDescontoJuro numeric(15,2);
92 nValorMaximoDescontoMulta numeric(15,2);
93
94 nValidacaoPerc numeric(15,10);
95 nPercentualVirtualCgm numeric(15,10);
96 nDiferencaPercentualCGM numeric(15,10) default 0;
97 nDiferencaPercentualAjuste numeric(15,10);
98
99
100
101 v_descontocor float8 default 0;
102 v_tipodescontocor integer default 0;
103 v_descontojur float8 default 0;
104 v_descontomul float8 default 0;
105 v_total float8;
106 v_totalcomjuro float8;
107 v_valparc float8;
108 v_diferencanaultima float8;
109
110 v_valorinserir float8;
111 v_ent_prop float8;
112 v_vlrateagora float8;
113 v_totateagora float8;
114 v_resto float8 default 0;
115 v_teste float8;
116 v_saldo float8;
117 v_calcular float8;
118 v_valorparcelanew float8;
119 v_valultimaparcelanew float8;
120
121 v_valdesccor float8;
122 v_valdescjur float8;
123 v_valdescmul float8;
124
125 nValorTotalOrigem float8;
126 nPercCalc float8;
127 nSomaPercMatric float8;
128 nSomaPercInscr float8;
129 nTotArreMatric float8;
130 nTotArreInscr float8;
131
132 nVlrHis numeric default 0;
133 nVlrCor numeric default 0;
134 nVlrJur numeric default 0;
135 nVlrMul numeric default 0;
136 nVlrDes numeric default 0;
137 nPercMatric numeric default 0;
138 nPercInscr numeric default 0;
139 nPercCGM numeric default 0;
140 lIncluiEmParcelas boolean default false;
141
142 nVlrTotalHistorico numeric default 0;
143 nVlrTotalCorrecao numeric default 0;
144 nVlrTotalJuros numeric default 0;
145 nVlrTotalMulta numeric default 0;
146
147 v_historico_compos float8 default 0;
148 v_correcao_compos float8 default 0;
149 v_juros_compos float8 default 0;
150 v_multa_compos float8 default 0;
151
152 nVlrHistoricoComposicao numeric(15,2) default 0;
153 nVlrCorrecaoComposicao numeric(15,2) default 0;
154 nVlrJurosComposicao numeric(15,2) default 0;
155 nVlrMultaComposicao numeric(15,2) default 0;
156 nVlrTotalParcelamento numeric(15,2) default 0;
157 nVlrTotalComposicao numeric(15,2) default 0;
158 nVlrDiferencaComposicaoTotal numeric(15,2) default 0;
159
160 nVlrTotalParcelamentoHistorico numeric(15,2) default 0;
161 nVlrTotalParcelamentoCorrigido numeric(15,2) default 0;
162 nVlrTotalParcelamentoJuros numeric(15,2) default 0;
163 nVlrTotalParcelamentoMulta numeric(15,2) default 0;
164 nVlrTotalDescontoCorrigido numeric(15,2) default 0;
165 nVlrTotalDescontoJuros numeric(15,2) default 0;
166 nVlrTotalDescontoMulta numeric(15,2) default 0;
167
168 nVlrDiferencaComposicaoHistorico numeric(15,2) default 0;
169 nVlrDiferencaComposicaoCorrecao numeric(15,2) default 0;
170 nVlrDiferencaComposicaoJuros numeric(15,2) default 0;
171 nVlrDiferencaComposicaoMulta numeric(15,2) default 0;
172
173 v_ultdiafev_d date;
174 v_vcto date;
175 dDataUsu date;
176
177 sArreoldJuncao varchar default '';
178 v_proxmessegvenc_c varchar(2);
179 v_ultdiafev_c varchar(10);
180 sStringUpdate varchar;
181 sNumpreSemVinculoMatricInsc text;
182
183 v_comando text;
184 v_comando_cria text;
185
186 v_iniciais record;
187 v_record_perc record;
188 v_record_numpres record;
189 v_record_numpar record;
190 v_record_receitas record;
191 v_record_recpar record;
192 v_record_origem record;
193 v_record_desconto record;
194 rPercOrigem record;
195 rSeparaJurMul record;
196 rAjusteDiferencaPercentual record;
197
198 lTabelasCriadas boolean;
199 v_parcnormal boolean default false; -- se tem divida ativa selecionada
200 v_parcinicial boolean default false; -- se tem inicial selecionada
201 lParcDiversos boolean default false; -- se tem diversos selecionado
202 lParcContrib boolean default false; -- se tem contribuicao de melhoria selecionado
203 lParcParc boolean default false; -- se tem parcelamento selecionado (caso esteja efetuando um reparcelamento)
204 v_juronaultima boolean default false;
205 v_descontar boolean default false;
206 lSeparaJuroMulta integer default 2;
207 lGravaArrecad boolean default true;
208 lParcelaZerada boolean default false;
209 lValidaParcInicial boolean default false;
210
211 lRaise boolean default false;
212
213 v_record_parcelas_parcela integer default 0;
214 v_record_parcelas_receit integer default 0;
215 v_record_parcelas_receitaori integer default 0;
216 v_record_parcelas_hist integer default 0;
217 v_record_parcelas_valor double precision default 0;
218 v_record_parcelas_valprop double precision default 0;
219 v_record_parcelas_valhis double precision default 0;
220 v_record_parcelas_valcor double precision default 0;
221 v_record_parcelas_valjur double precision default 0;
222 v_record_parcelas_valmul double precision default 0;
223 v_record_parcelas_descor double precision default 0;
224 v_record_parcelas_descjur double precision default 0;
225 v_record_parcelas_descmul double precision default 0;
226
227 iCodcli integer default 0;
228 nFaixaInicial float8 default -0.01;
229 nFaixaFinal float8 default 3.00;
230
231 begin
232
233 -- valores retornados:
234 -- 1 = ok
235 -- 2 = tentando parcelar mais de um tipo (k03_tipo) de debito
236 -- 3 = tipo de debito nao configurado para parcelamento
237 -- 4 = parcelamento nao encontrado pelo numpre
238 -- 5 = tentando reparcelar mais de um parcelamento
239 -- 6 = tentando parcelar mais de um numpre (debito)
240
241 lRaise := ( case when fc_getsession('DB_debugon') is null or fc_getsession('DB_debugon') = '' then false else true end );
242
243 if lRaise is true then
244 perform fc_debug('Processando parcelamento dos débitos...',lRaise,true,false);
245 end if;
246
247 v_totalparcelas = v_totparc;
248 v_valorparcelanew = v_valorparcela;
249 v_valultimaparcelanew = v_valultimaparcela;
250
251 iInstit := cast(fc_getsession('DB_instit') as integer);
252 if iInstit is null then
253 raise exception 'Variavel de sessão [DB_instit] não encontrada.';
254 end if;
255
256 iAnousu := cast(fc_getsession('DB_anousu') as integer);
257 if iAnousu is null then
258 raise exception 'Variavel de sessão [DB_anousu] não encontrada.';
259 end if;
260
261 dDataUsu := cast(fc_getsession('DB_datausu') as date);
262 if dDataUsu is null then
263 raise exception 'Variavel de sessão [DB_datausu] não encontrada.';
264 end if;
265
266 select k03_separajurmulparc
267 into lSeparaJuroMulta
268 from numpref
269 where k03_instit = iInstit
270 and k03_anousu = iAnousu;
271
272 --lSeparaJuroMulta = false;
273
274 -- testa se existe algum tipo de parcelamento configurado
275 select count(*)
276 from tipoparc
277 where instit = iInstit
278 into v_contador;
279
280 if v_contador is null then
281 return '[0] - Sem configuracao na tabela tipoparc para instituicao %', iInstit;
282 end if;
283
284 if lRaise is true then
285 perform fc_debug('verificando se tem mais de um tipo de debito...',lRaise,false,false);
286 end if;
287
288 -- existe uma tabela temporaria chamada totalportipo, criada antes de chamar a funcao de parcelamento
289 -- que contem os valores a parcelar agrupada por tipo de debito
290 -- nessa tabela existe a informacao se o tipo de debito tem direito a desconto ou nao
291
292 -- a tabela numpres_parc contem os registros marcados na CGF pelo usuario
293 -- cria indice na tabela utilizada durante os parcelamentos
294 create index numpres_parc_in on numpres_parc using btree (k00_numpre, k00_numpar);
295
296 -- for buscando as origens de cada debito selecionado para parcelar(numpres_parc)
297 for v_record_origem in select arretipo.k03_tipo,
298 arrecad.k00_numpre,
299 count(*)
300 from numpres_parc
301 inner join arrecad on arrecad.k00_numpre = numpres_parc.k00_numpre
302 inner join arretipo on arretipo.k00_tipo = arrecad.k00_tipo
303 group by arretipo.k03_tipo,
304 arrecad.k00_numpre
305 loop
306
307 -- se origem(k03_tipo) for
308 if v_record_origem.k03_tipo = 5 then
309
310 -- 5 divida ativa
311 v_parcnormal = true;
312
313 elsif v_record_origem.k03_tipo = 18 then
314
315 -- inicial do foro
316 v_parcinicial = true;
317 lValidaParcInicial = true;
318
319 elsif v_record_origem.k03_tipo = 4 then
320
321 -- contribuicao de melhoria
322 lParcContrib = true;
323
324 elsif v_record_origem.k03_tipo = 7 then
325
326 -- diversos
327 lParcDiversos = true;
328
329 elsif v_record_origem.k03_tipo in (6,13,16,17) then
330
331 -- reparcelamentos
332 -- 6 parcelamento de divida
333 -- 13 parcelamento de inicial de divida
334 -- 16 parcelamento de diveros
335 -- 17 parcelamento de contribuicao de melhoria
336 lParcParc = true;
337
338 if v_record_origem.k03_tipo = 13 then
339 lValidaParcInicial = true;
340 end if;
341
342 end if;
343
344 if lRaise is true then
345 perform fc_debug('k00_tipo: '||v_record_origem.k03_tipo||'k00_numpre:'||v_record_origem.k00_numpre,lRaise,false,false);
346 end if;
347
348 end loop;
349
350 if v_parcnormal is true and v_parcinicial is true then
351 return '[1] - Nao pode ser parcela divida normal com ajuizada!';
352 end if;
353
354 -- se houver débitos do tipo Inicial verificamos se o parâmetro do Mód. Juridio PARTILHA está ativo 'SIM' e
355 -- caso exista mais de um processo para as iniciais bloqueamos o parcelamento.
356 if lValidaParcInicial is true then
357
358 perform v19_partilha
359 from parjuridico
360 where v19_anousu = iAnousu
361 and v19_instit = iInstit
362 and v19_partilha is true;
363 if found then
364
365 perform count( distinct case
366 when processoinicial.v71_processoforo is null
367 then processoparcel.v71_processoforo
368 else processoinicial.v71_processoforo end )
369 from NUMPRES_PARC
370 left join inicialnumpre on inicialnumpre.v59_numpre = NUMPRES_PARC.k00_numpre
371 left join processoforoinicial as processoinicial on processoinicial.v71_inicial = inicialnumpre.v59_inicial
372 left join termo on termo.v07_numpre = NUMPRES_PARC.k00_numpre
373 left join termoini on termoini.parcel = termo.v07_parcel
374 left join processoforoinicial as processoparcel on processoparcel.v71_inicial = termoini.inicial
375 having count(distinct case
376 when processoinicial.v71_processoforo is null
377 then processoparcel.v71_processoforo
378 else processoinicial.v71_processoforo end) > 1;
379 if found then
380 return '[2] - Não é possÃvel parcelar iniciais com processos do foro diferentes para um mesmo parcelamento! [Utilização de Partilha Ativada]';
381 end if;
382
383 end if;
384
385 end if;
386
387 if lRaise is true then
388 perform fc_debug('guardando o tipo de debito...',lRaise,false,false);
389 end if;
390
391 v_tipo = v_cadtipo;
392
393 if lRaise is true then
394 perform fc_debug('guardando o tipo de debito...',lRaise,false,false);
395 end if;
396
397 -- select na termoconfigo para descobrir qual o tipo de debito
398 -- que vai ser gerado com o debito do novo parcelamento
399 -- tabela termotipoconfig tem o tipo de debito dos grupos de debitos
400 -- que e possivel parcelar
401
402 if lRaise is true then
403 perform fc_debug('instit -- '||iInstit,lRaise,false,false);
404 end if;
405
406 select k42_tiponovo
407 into v_tiponovo
408 from termotipoconfig
409 where k42_cadtipo = v_tipo
410 and k42_instit = iInstit;
411 if not found then
412 return '[3] - Este tipo de debito nao esta configurado para parcelamento';
413 end if;
414
415 if lRaise is true then
416 perform fc_debug('tipo novo:'||v_tiponovo,lRaise,false,false);
417 end if;
418
419 -- cria tabela temporarias para utilizacao durante o calculo
420 if lRaise is true then
421 perform fc_debug('',lRaise,false,false);
422 perform fc_debug('+--------------------------------------------------------------------------------------------------',lRaise,false,false);
423 perform fc_debug('| ',lRaise,false,false);
424 perform fc_debug('| CRIANDO TABELAS TEMPORARIAS PARA O PROCESSAMENTO DO PARCELAMENTO ',lRaise,false,false);
425 perform fc_debug('| ',lRaise,false,false);
426 perform fc_debug('+--------------------------------------------------------------------------------------------------',lRaise,false,false);
427 perform fc_debug('',lRaise,false,false);
428 end if;
429 select fc_parc_criatemptable(lRaise)
430 into lTabelasCriadas;
431 if lTabelasCriadas is false then
432 return '[4] - Problema ao criar as tabelas temporarias. ';
433 end if;
434
435
436 -- Desativado parâmetro para que não seja gerado registros na incorporação tributária
437 perform fc_putsession('DB_utiliza_incorporacao','false');
438
439 -- funcao que corrige o arrecad no caso de encontrar registros duplicados(numpre,numpar,receit)
440 perform fc_corrigeparcelamento();
441
442 -- Ativado parâmetro para que continue sendo gerado registros na incorporação tributária
443 perform fc_putsession('DB_utiliza_incorporacao','true');
444
445 -- testa se todas as parcelas do parcelamento foram marcadas,
446 -- senao nao permite parcelar apenas algumas parcelas do parcelamento
447 -- ou seja, ou parcela todas as parcelas do parcelamento, ou nada
448 for v_record_origem in select distinct
449 termo.v07_parcel
450 from numpres_parc
451 inner join termo on termo.v07_numpre = numpres_parc.k00_numpre
452 where k03_tipodebito <> 18
453 loop
454
455 -- soma a quantidade de parcelas do parcelamento
456 select count(distinct arrecad.k00_numpar)
457 into v_somar1
458 from arrecad
459 inner join termo on termo.v07_parcel = v_record_origem.v07_parcel
460 where arrecad.k00_numpre = termo.v07_numpre;
461
462 if lRaise is true then
463 perform fc_debug('v_record_origem.v07_parcel: '||v_record_origem.v07_parcel,lRaise,false,false);
464 end if;
465
466 -- testa a quantidade de parcelas marcadas
467 select count(distinct numpres_parc.k00_numpar)
468 into v_somar2
469 from numpres_parc
470 inner join termo on termo.v07_parcel = v_record_origem.v07_parcel
471 where numpres_parc.k00_numpre = termo.v07_numpre;
472
473 if lRaise is true then
474 perform fc_debug('Verificando quantidades de parcelaas marcadas com a quantidade de parcelas do débito: v_somar1: '||v_somar1||' - v_somar2: '||v_somar2,lRaise,false,false);
475 end if;
476
477 -- compara
478 if v_somar1 <> v_somar2 then
479 return '[5] - Todas as parcelas do parcelamento ' || v_record_origem.v07_parcel || ' devem ser marcadas!';
480 end if;
481
482 end loop;
483
484 if lRaise is true then
485 perform fc_debug('entrada'||v_entrada,lRaise,false,false);
486 perform fc_debug('valor das parcelas:'||v_valorparcelanew,lRaise,false,false);
487 perform fc_debug('valor da ultima parcela:'||v_valultimaparcelanew,lRaise,false,false);
488 perform fc_debug('pegando cgm do(s) numpre(s) com arrecad...',lRaise,false,false);
489 end if;
490
491 -- busca cgm principal para gravar no arrecad posteriormente
492 if v_parcinicial is true then
493
494 select k00_numcgm
495 into v_cgmpri
496 from arrecad
497 inner join numpres_parc on arrecad.k00_numpre = numpres_parc.k00_numpre
498 limit 1;
499
500 else
501
502 select k00_numcgm
503 into v_cgmpri
504 from arrecad
505 inner join numpres_parc on arrecad.k00_numpre = numpres_parc.k00_numpre
506 and arrecad.k00_numpar = numpres_parc.k00_numpar
507 limit 1;
508
509 end if;
510
511 if lRaise is true then
512 perform fc_debug('Pegando cgm de acordo com matricula ou inscricao...',lRaise,false,false);
513 end if;
514
515 v_anousu := iAnousu;
516
517 -- se for parcelamento de inicial
518 if v_parcinicial is true then
519
520 if lRaise is true then
521 perform fc_debug('t i p o: 18',lRaise,false,false);
522 end if;
523
524 -- procura cgm principal por matricula ou inscricao
525 for v_record_origem in select distinct
526 arrematric.k00_matric,
527 arreinscr.k00_inscr
528 from numpres_parc
529 left join arrematric on arrematric.k00_numpre = numpres_parc.k00_numpre
530 left join arreinscr on arreinscr.k00_numpre = numpres_parc.k00_numpre
531 inner join arrecad on arrecad.k00_numpre = numpres_parc.k00_numpre
532 loop
533
534 if lRaise is true then
535 perform fc_debug('processando... matricula: '||v_record_origem.k00_matric||' inscricao: '||v_record_origem.k00_inscr,lRaise,false,false);
536 end if;
537
538 if v_record_origem.k00_matric is not null then
539 select j01_numcgm
540 from iptubase
541 into v_cgmpri
542 where j01_matric = v_record_origem.k00_matric;
543 end if;
544
545 if v_record_origem.k00_inscr is not null then
546 select q02_numcgm
547 from issbase
548 into v_cgmpri
549 where q02_inscr = v_record_origem.k00_inscr;
550 end if;
551
552 end loop;
553
554 -- senao for inicial do foro
555 else
556
557 if lRaise is true then
558 perform fc_debug(' ',lRaise,false,false);
559 perform fc_debug(' ',lRaise,false,false);
560 perform fc_debug('Buscando CGM princial por matricula ou inscrição',lRaise,false,false);
561 perform fc_debug(' ',lRaise,false,false);
562 end if;
563
564 -- procura cgm principal por matricula ou inscricao
565 for v_record_origem in select distinct
566 arrematric.k00_matric,
567 arreinscr.k00_inscr
568 from numpres_parc
569 left join arrematric on arrematric.k00_numpre = numpres_parc.k00_numpre
570 left join arreinscr on arreinscr.k00_numpre = numpres_parc.k00_numpre
571 inner join arrecad on arrecad.k00_numpre = numpres_parc.k00_numpre
572 and arrecad.k00_numpar = numpres_parc.k00_numpar
573 loop
574
575 if lRaise is true then
576 perform fc_debug('Processando... matricula: '||v_record_origem.k00_matric||' inscricao: '||v_record_origem.k00_inscr, lRaise, false, false);
577 end if;
578
579 if v_record_origem.k00_matric is not null then
580 select j01_numcgm
581 from iptubase
582 into v_cgmpri
583 where j01_matric = v_record_origem.k00_matric;
584 end if;
585
586 if v_record_origem.k00_inscr is not null then
587 select q02_numcgm
588 from issbase
589 into v_cgmpri
590 where q02_inscr = v_record_origem.k00_inscr;
591 end if;
592
593 end loop;
594
595 if lRaise is true then
596 perform fc_debug('',lRaise,false,false);
597 perform fc_debug('',lRaise,false,false);
598 perform fc_debug('Fim da busca do CGM principal',lRaise,false,false);
599 perform fc_debug('',lRaise,false,false);
600 end if;
601
602 end if;
603
604 if lRaise is true then
605 perform fc_debug('agora vai processar correcao e tal...',lRaise,false,false);
606 end if;
607
608 -- se for inicial, traz apenas os numpres envolvidos, ja que no caso de parcelamento de inicial
609 -- o usuario nao tem opcao de marcar as parcelas, tendo que parcelar toda a inicial
610 -- se nao for inicial, traz os numpres com suas respectivas parcelas marcadas
611 if v_parcinicial is true then
612 v_comando = 'select distinct k00_numpre from numpres_parc';
613 else
614 v_comando = 'select distinct k00_numpre, k00_numpar from numpres_parc';
615 end if;
616
617 -- varre a lista de numpres/parcelas marcados pelo usuario
618 for v_record_numpres in execute v_comando
619 loop
620
621 if lRaise is true then
622 if v_parcinicial is false then
623 perform fc_debug(' numpre '||v_record_numpres.k00_numpre||' - numpar: '||v_record_numpres.k00_numpar,lRaise, false, false);
624 else
625 perform fc_debug(' numpre '||v_record_numpres.k00_numpre||' - numpar: 0',lRaise, false, false);
626 end if;
627 end if;
628
629 v_matric = 0;
630 v_inscr = 0;
631
632 -- busca a matricula do numpre que esta sendo processado
633 select k00_matric
634 into v_var
635 from arrematric
636 where k00_numpre = v_record_numpres.k00_numpre;
637
638 if v_var is not null then
639 v_matric = v_var;
640
641 if lRaise is true then
642 perform fc_debug(' origem: matricula '||v_matric,lRaise,false,false);
643 end if;
644 end if;
645
646 -- busca a inscricao do numpre que esta sendo processado
647 select k00_inscr
648 into v_var
649 from arreinscr
650 where k00_numpre = v_record_numpres.k00_numpre;
651
652 if v_var is not null then
653 v_inscr = v_var;
654
655 if lRaise is true then
656 perform fc_debug(' origem: inscricao '||v_inscr,lRaise,false,false);
657 end if;
658 end if;
659
660 -- processa cada registro acumulando por numpre, parcela, receita e tipo de debito
661 -- armazenando as informacoes de valor historico, corrigido, juros e multa
662 -- na tabela arrecad_parc_rec para utilizacao em processamento futuro
663 -- independente se for inicial ou nao
664
665 -- se for inicial
666 if v_parcinicial is true then
667
668 if lRaise is true then
669 perform fc_debug(' entrando tipo 18...',lRaise,false,false);
670 end if;
671
672 for v_record_numpar in select k00_numpre,
673 k00_numpar,
674 k00_receit,
675 k03_tipo,
676 substr(fc_calcula,2,13)::float8 as vlrhis,
677 substr(fc_calcula,15,13)::float8 as vlrcor,
678 substr(fc_calcula,28,13)::float8 as vlrjuros,
679 substr(fc_calcula,41,13)::float8 as vlrmulta,
680 substr(fc_calcula,54,13)::float8 as vlrdesc,
681 (substr(fc_calcula,15,13)::float8+substr(fc_calcula,28,13)::float8+substr(fc_calcula,41,13)::float8-substr(fc_calcula,54,13)::float8) as total
682 from ( select k00_numpre,
683 k00_numpar,
684 k00_receit,
685 k03_tipo,
686 fc_calcula(k00_numpre,k00_numpar,k00_receit,dDataUsu,dDataUsu,v_anousu) as fc_calcula
687 from ( select distinct
688 arrecad.k00_numpre,
689 arrecad.k00_numpar,
690 arrecad.k00_receit,
691 arretipo.k03_tipo
692 from arrecad
693 inner join arretipo on arrecad.k00_tipo = arretipo.k00_tipo
694 where arrecad.k00_numpre = v_record_numpres.k00_numpre
695 ) as x
696 ) as y
697 loop
698
699 select receit
700 from arrecad_parc_rec
701 into v_receita
702 where numpre = v_record_numpar.k00_numpre
703 and numpar = v_record_numpar.k00_numpar
704 and receit = v_record_numpar.k00_receit;
705
706 if lRaise is true then
707 perform fc_debug('1 - numpre: '||v_record_numpar.k00_numpre||', numpar: '||v_record_numpar.k00_numpar||', receit: '||v_record_numpar.k00_receit||', v_receita: '||v_receita,lRaise,false,false);
708 end if;
709
710 -- se nao existe registro insere
711 if v_receita is null then
712
713 if lRaise is true then
714 perform fc_debug(' ',lRaise,false,false);
715 perform fc_debug('inserindo registro na arrecad_parc_rec',lRaise,false,false);
716 end if;
717
718 execute 'insert into arrecad_parc_rec values (' || v_record_numpar.k00_numpre || ','
719 || v_record_numpar.k00_numpar || ','
720 || v_record_numpar.k00_receit || ','
721 || v_record_numpar.k03_tipo || ','
722 || v_record_numpar.vlrhis || ','
723 || v_record_numpar.vlrcor || ','
724 || v_record_numpar.vlrjuros || ','
725 || v_record_numpar.vlrmulta || ','
726 || v_record_numpar.vlrdesc || ','
727 || v_record_numpar.total || ','
728 || v_matric || ','
729 || v_inscr || ','
730 || 0 || ','
731 || 0 || ','
732 || 0 || ','
733 || 'false' || ');';
734 -- se ja existe, soma
735 else
736
737 execute 'update arrecad_parc_rec set valor = valor + ' || v_record_numpar.total || ','
738 || 'vlrhis = vlrhis + ' || v_record_numpar.vlrhis || ','
739 || 'vlrcor = vlrcor + ' || v_record_numpar.vlrcor || ','
740 || 'vlrjur = vlrjur + ' || v_record_numpar.vlrjuros || ','
741 || 'vlrmul = vlrmul + ' || v_record_numpar.vlrmulta || ','
742 || 'vlrdes = vlrdes + ' || v_record_numpar.vlrdesc
743 || ' where numpre = ' || v_record_numpar.k00_numpre
744 || ' and numpar = ' || v_record_numpar.k00_numpar
745 || ' and receit = ' || v_record_numpar.k00_receit ||';';
746 end if;
747
748 end loop;
749
750 if lRaise is true then
751 perform fc_debug(' saindo do tipo 18...',lRaise,false,false);
752 end if;
753
754 else -- se nao for inicial foro
755
756
757 if lRaise is true then
758 perform fc_debug(' tipo diferente de 18 ',lRaise,false,false);
759 end if;
760
761 if lRaise is true then
762 perform fc_debug('numpre: '||v_record_numpres.k00_numpre||' - numpar: '||v_record_numpres.k00_numpar,lRaise,false,false);
763 end if;
764
765 for v_record_numpar in select k00_numpre,
766 k00_numpar,
767 k00_receit,
768 k03_tipo,
769 substr(fc_calcula,2, 13)::float8 as vlrhis,
770 substr(fc_calcula,15,13)::float8 as vlrcor,
771 substr(fc_calcula,28,13)::float8 as vlrjuros,
772 substr(fc_calcula,41,13)::float8 as vlrmulta,
773 substr(fc_calcula,54,13)::float8 as vlrdesc,
774 (substr(fc_calcula,15,13)::float8+
775 substr(fc_calcula,28,13)::float8+
776 substr(fc_calcula,41,13)::float8-
777 substr(fc_calcula,54,13)::float8) as total
778 from ( select distinct
779 k00_numpre,
780 k00_numpar,
781 k00_receit,
782 k03_tipo,
783 fc_calcula(k00_numpre,k00_numpar,k00_receit,dDataUsu,dDataUsu,v_anousu) as fc_calcula
784 from ( select distinct
785 arrecad.k00_numpre,
786 arrecad.k00_numpar,
787 arrecad.k00_receit,
788 arretipo.k03_tipo
789 from arrecad
790 inner join arretipo on arrecad.k00_tipo = arretipo.k00_tipo
791 where arrecad.k00_numpre = v_record_numpres.k00_numpre
792 and arrecad.k00_numpar = v_record_numpres.k00_numpar
793 ) as x
794 ) as y
795 loop
796
797 if lRaise is true then
798 perform fc_debug(' dentro do for...',lRaise,false,false);
799 end if;
800
801 select receit
802 from arrecad_parc_rec
803 into v_receita
804 where numpre = v_record_numpar.k00_numpre
805 and numpar = v_record_numpar.k00_numpar
806 and receit = v_record_numpar.k00_receit;
807
808 if lRaise is true then
809 perform fc_debug('2 - numpre: '||v_record_numpar.k00_numpre||' numpar: '||v_record_numpar.k00_numpar||' receit: '||v_record_numpar.k00_receit||' v_receita: '||v_receita||' - valor: '||v_record_numpar.total,lRaise,false,false);
810 end if;
811
812 -- se nao existe registro insere
813 if v_receita is null then
814
815 if lRaise is true then
816 perform fc_debug(' inserindo no arrecad_parc_rec... numpre: '||v_record_numpar.k00_numpre,lRaise,false,false);
817 end if;
818
819 execute 'insert into arrecad_parc_rec values (' || v_record_numpar.k00_numpre || ',' ||
820 v_record_numpar.k00_numpar || ',' ||
821 v_record_numpar.k00_receit || ',' ||
822 v_record_numpar.k03_tipo || ',' ||
823 v_record_numpar.vlrhis || ',' ||
824 v_record_numpar.vlrcor || ',' ||
825 v_record_numpar.vlrjuros || ',' ||
826 v_record_numpar.vlrmulta || ',' ||
827 v_record_numpar.vlrdesc || ',' ||
828 v_record_numpar.total || ',' ||
829 v_matric || ',' ||
830 v_inscr || ');';
831
832 else
833
834 execute 'update arrecad_parc_rec set valor = valor + ' || v_record_numpar.total
835 || ',vlrhis = vlrhis + ' || v_record_numpar.vlrhis
836 || ',vlrcor = vlrcor + ' || v_record_numpar.vlrcor
837 || ',vlrjur = vlrjur + ' || v_record_numpar.vlrjuros
838 || ',vlrmul = vlrmul + ' || v_record_numpar.vlrmulta
839 || ',vlrdes = vlrdes + ' || v_record_numpar.vlrdesc
840 || ' where numpre = ' || v_record_numpar.k00_numpre || ' and '
841 || ' numpar = ' || v_record_numpar.k00_numpar || ' and '
842 || ' receit = ' || v_record_numpar.k00_receit || ';';
843 end if;
844
845 if lRaise is true then
846 perform fc_debug(' fim do for...',lRaise,false,false);
847 end if;
848
849 end loop;
850
851 end if;
852
853 end loop;
854
855 if lRaise is true then
856 perform fc_debug('gravando na tabela parcelas... tipo: '||v_tipo,lRaise,false,false);
857 perform fc_debug('v_temdesconto: '||v_temdesconto,lRaise,false,false);
858 end if;
859
860 -- busca regra de parcelamento
861 select cadtipoparc.k40_codigo
862 into v_cadtipoparc
863 from tipoparc
864 inner join cadtipoparc on cadtipoparc = k40_codigo
865 where maxparc > 1
866 and dDataUsu >= k40_dtini
867 and dDataUsu <= k40_dtfim
868 and k40_codigo = v_desconto
869 and k40_aplicacao = 1 -- Aplicar Antes do Lancamento
870 order by maxparc
871 limit 1;
872
873 if lRaise is true then
874 perform fc_debug('v_cadtipoparc: '||v_cadtipoparc,lRaise,false,false);
875 end if;
876
877 -- varre as regras de parcelamento para descobrir o percentual de desconto nos juros e multa de acordo com
878 -- a quantidade de parcelas selecionadas pelo usuario
879 for v_record_desconto in select *
880 from tipoparc
881 where maxparc > 1
882 and cadtipoparc = v_cadtipoparc
883 and cadtipoparc = v_desconto
884 order by maxparc
885 loop
886
887 if v_totalparcelas >= v_ultparc and v_totalparcelas <= v_record_desconto.maxparc then
888 v_tipodescontocor = v_record_desconto.tipovlr;
889 v_descontocor = v_record_desconto.descvlr;
890 v_descontomul = v_record_desconto.descmul;
891 v_descontojur = v_record_desconto.descjur;
892
893 exit;
894
895 end if;
896
897 end loop;
898
899 if lRaise is true then
900 perform fc_debug('total do desconto na multa : '||v_descontomul,lRaise,false,false);
901 perform fc_debug('total do desconto nos juros: '||v_descontojur,lRaise,false,false);
902 perform fc_debug('antes do for do arrecad_parc_rec...',lRaise,false,false);
903 end if;
904
905 -- soma o valor corrigido + juros + multa antes de efetuar o desconto
906 -- valor apenas para conferencia em possivel debug
907 select sum(valor),
908 sum(vlrcor+vlrjur+vlrmul-vlrdesccor-vlrdescjur-vlrdescmul)
909 into v_somar,
910 v_totalliquido
911 from arrecad_parc_rec;
912
913 if lRaise is true then
914 perform fc_debug('v_somar: '||v_somar||' - v_totalliquido: '||v_totalliquido,lRaise,false,false);
915 end if;
916
917 -- varre tabela dos registros a parcelar para aplicar desconto nos juros e multa
918 for v_record_recpar in select *
919 from arrecad_parc_rec
920 loop
921
922 -- testa se o tipo de debito desse registro tem direito a desconto
923 select case
924 when k00_cadtipoparc > 0
925 then true
926 else false
927 end
928 into v_descontar
929 from totalportipo
930 where k03_tipodebito = v_record_recpar.tipo;
931
932 if lRaise is true then
933 perform fc_debug('tipo: '||v_record_recpar.tipo||' - descontar: '||v_descontar,lRaise,false,false);
934 end if;
935
936 -- se tem direito a desconto, aplica o desconto e da update nos valores do registro atual da arrecad_parc_rec
937 if v_descontar is true then
938
939 v_valdesccor = 0;
940
941 if v_tipodescontocor = 1 then
942
943 if lRaise is true then
944 perform fc_debug('vlrcor: '||v_record_recpar.vlrcor||' - vlrhis: '||v_record_recpar.vlrhis||' - v_descontocor: '||v_descontocor,lRaise,false,false);
945 end if;
946 v_valdesccor = (v_record_recpar.vlrcor - v_record_recpar.vlrhis) * v_descontocor / 100;
947
948 elsif v_tipodescontocor = 2 then
949 v_valdesccor = v_record_recpar.vlrcor * v_descontocor / 100;
950 end if;
951
952 if lRaise is true then
953 perform fc_debug('v_valdesccor: '||v_valdesccor,lRaise,false,false);
954 end if;
955
956 v_valdescjur = v_record_recpar.vlrjur * v_descontojur / 100;
957
958 if lRaise is true then
959 perform fc_debug('v_valdescjur: '||v_valdescjur||' - v_descontojur: '||v_descontojur,lRaise,false, false);
960 end if;
961
962 v_valdescmul = v_record_recpar.vlrmul * v_descontomul / 100;
963
964 if lRaise is true then
965 perform fc_debug('v_valdescmul: '||v_valdescmul||' - v_descontomul: '||v_descontomul,lRaise,false,false);
966 end if;
967
968 execute 'update arrecad_parc_rec set vlrjur = ' || v_record_recpar.vlrjur
969 || ', vlrmul = ' || v_record_recpar.vlrmul
970 || ', valor = valor - ' || v_valdescjur || ' - ' || v_valdescmul || ' - ' || v_valdesccor
971 || ', vlrdesccor = ' || v_valdesccor
972 || ', vlrdescjur = ' || v_record_recpar.vlrjur * v_descontojur / 100
973 || ', vlrdescmul = ' || v_record_recpar.vlrmul * v_descontomul / 100
974 || ' where numpre = ' || v_record_recpar.numpre || ' and '
975 || ' numpar = ' || v_record_recpar.numpar || ' and '
976 || ' receit = ' || v_record_recpar.receit || ';';
977
978 end if;
979
980 if lRaise is true then
981 perform fc_debug(' numpre: '||v_record_recpar.numpre||' - numpar: '||v_record_recpar.numpar||' - receita: '||v_record_recpar.receit,lRaise,false,false);
982 end if;
983
984 end loop;
985
986 -- passa o conteudo do campo juro para false em todos os registros
987 execute 'update arrecad_parc_rec set juro = false';
988
989 if lRaise is true then
990 perform fc_debug('v_desconto: '||v_desconto,lRaise,false,false);
991 end if;
992
993 -- se a forma na regra de parcelamento for 2 (juros na ultima)
994 select case
995 when k40_forma = 2
996 then true
997 else false
998 end
999 into v_juronaultima
1000 from cadtipoparc
1001 where k40_codigo = v_desconto;
1002
1003 if v_juronaultima is null then
1004 v_juronaultima = false;
1005 end if;
1006
1007 if lRaise is true then
1008 perform fc_debug('desconto na ultima: '||v_juronaultima,lRaise,false,false);
1009 end if;
1010
1011 for v_record_recpar in select *
1012 from arrecad_parc_rec
1013 loop
1014
1015 -- se for para colocar juros na ultima
1016 -- insere mais dois registros: um para juros e outro para multa
1017 -- e update no campo valor deixando apenas o valor corrigido
1018 if v_juronaultima is true then
1019
1020 select k02_recjur,
1021 k02_recmul
1022 from tabrec
1023 into v_recjurosultima,
1024 v_recmultaultima
1025 where k02_codigo = v_record_recpar.receit;
1026
1027 if lRaise is true then
1028 perform fc_debug('jur: '||v_recjurosultima||' - mul: '||v_recmultaultima,lRaise,false,false);
1029 perform fc_debug('numpre: '||v_record_recpar.numpre||' - numpar: '||v_record_recpar.numpar||' - jurosnaultima: '||v_recjurosultima,lRaise,false,false);
1030 perform fc_debug('tipo: '||v_record_recpar.tipo||' - juros: '||v_record_recpar.vlrjur||' - matric: '||v_record_recpar.matric||' - inscr: '||v_record_recpar.inscr||' - descjur: '||v_record_recpar.vlrdescjur||' - descmul: '||v_record_recpar.vlrdescmul,lRaise,false,false);
1031 end if;
1032
1033 execute 'insert into arrecad_parc_rec values (' || v_record_recpar.numpre || ',' ||
1034 v_record_recpar.numpar || ',' ||
1035 v_recjurosultima || ',' ||
1036 v_record_recpar.tipo || ',' ||
1037 v_record_recpar.vlrjur || ',' ||
1038 v_record_recpar.vlrjur || ',' ||
1039 0 || ',' ||
1040 0 || ',' ||
1041 0 || ',' ||
1042 v_record_recpar.vlrjur || ',' ||
1043 v_record_recpar.matric || ',' ||
1044 v_record_recpar.inscr || ',' ||
1045 0 || ',' ||
1046 v_record_recpar.vlrdescjur || ',' ||
1047 v_record_recpar.vlrdescmul || ',' ||
1048 'true' || ');';
1049
1050 if lRaise is true then
1051 perform fc_debug('1',lRaise,false,false);
1052 end if;
1053
1054 -- inserindo multa
1055 execute 'insert into arrecad_parc_rec values (' || v_record_recpar.numpre || ',' ||
1056 v_record_recpar.numpar || ',' ||
1057 v_recmultaultima || ',' ||
1058 v_record_recpar.tipo || ',' ||
1059 v_record_recpar.vlrmul || ',' ||
1060 v_record_recpar.vlrmul || ',' ||
1061 0 || ',' ||
1062 0 || ',' ||
1063 0 || ',' ||
1064 v_record_recpar.vlrmul || ',' ||
1065 v_record_recpar.matric || ',' ||
1066 v_record_recpar.inscr || ',' ||
1067 0 || ',' ||
1068 v_record_recpar.vlrdescjur || ',' ||
1069 v_record_recpar.vlrdescmul || ',' ||
1070 'true' || ');';
1071
1072 if lRaise is true then
1073 perform fc_debug('2',lRaise,false,false);
1074 end if;
1075
1076 execute 'update arrecad_parc_rec set valor = ' || v_record_recpar.vlrcor ||
1077 ' where numpre = ' || v_record_recpar.numpre ||
1078 ' and numpar = ' || v_record_recpar.numpar ||
1079 ' and receit = ' || v_record_recpar.receit || ';';
1080
1081 if lRaise is true then
1082 perform fc_debug('3',lRaise,false,false);
1083 end if;
1084
1085 end if;
1086
1087 end loop;
1088
1089 if lRaise is true then
1090 perform fc_debug(' ',lRaise,false,false);
1091 perform fc_debug(' ',lRaise,false,false);
1092 perform fc_debug(' ',lRaise,false,false);
1093 perform fc_debug(' ',lRaise,false,false);
1094 perform fc_debug(' ',lRaise,false,false);
1095 perform fc_debug(' ',lRaise,false,false);
1096 end if;
1097
1098 -- apenas mostra os registros atuais para possivel conferencia
1099 for v_record_recpar in select *
1100 from arrecad_parc_rec loop
1101
1102 if lRaise is true then
1103 perform fc_debug('numpre: '||v_record_recpar.numpre||' - par: '||v_record_recpar.numpar||' - rec: '||v_record_recpar.receit||' - cor: '||v_record_recpar.vlrcor||' - jur: '||v_record_recpar.vlrjur||' - tot: '||v_record_recpar.valor||' - juro: '||v_record_recpar.juro,lRaise, false,false);
1104 end if;
1105
1106 end loop;
1107
1108 if lRaise is true then
1109 perform fc_debug(' ',lRaise,false,false);
1110 perform fc_debug(' ',lRaise,false,false);
1111 perform fc_debug(' ',lRaise,false,false);
1112 perform fc_debug(' ',lRaise,false,false);
1113 perform fc_debug(' ',lRaise,false,false);
1114 perform fc_debug(' ',lRaise,false,false);
1115 end if;
1116
1117 if lRaise is true then
1118 perform fc_debug('depois do for do arrecad_parc_rec...',lRaise,false,false);
1119 end if;
1120
1121 -- calcula valor total com juro
1122 select sum(valor)
1123 from arrecad_parc_rec
1124 into v_totalcomjuro;
1125
1126 -- se for juros na ultima, o campo valor ja esta sem juros e multa
1127 -- entao a variavel v_total recebe sem juros e a regra for de colocar os juros na ultima parcela
1128 -- note que o campo juro da tabela recebe false apenas nos registros que nao sao dos juros para incluir na ultima
1129 if v_juronaultima is false then
1130 -- select sum(round(valor, 2))
1131 -- from (
1132 select sum(valor) as valor
1133 from arrecad_parc_rec
1134 -- group by receit
1135 -- ) as dados
1136 into v_total;
1137 else
1138 -- select sum(round(valor, 2))
1139 -- from (
1140 select sum(valor) as valor
1141 from arrecad_parc_rec
1142 where juro is false
1143 -- group by receit
1144 -- ) as dados
1145 into v_total;
1146 end if;
1147
1148 -- diferente entre variavel com e sem juros
1149 -- utilizada na regra de juros na ultima
1150 v_diferencanaultima = v_totalcomjuro - v_total;
1151
1152 if lRaise is true then
1153 perform fc_debug(' ',lRaise,false,false);
1154 perform fc_debug('total (primeira versao do script): '||v_total||' - v_totalparcelas: '||v_totalparcelas,lRaise,false,false);
1155 perform fc_debug(' ',lRaise,false,false);
1156 perform fc_debug('v_tipo: '||v_tipo,lRaise,false,false);
1157 end if;
1158
1159 v_somar = 0;
1160
1161 if lRaise is true then
1162 perform fc_debug('antes do tipo 5...',lRaise,false,false);
1163 end if;
1164
1165 -- cria variavel para select agrupando os valores por
1166 -- tipo de origem, receita nova e receita original
1167 -- note que o sistema tem 3 niveis de origem
1168 -- 1 = de divida ativa
1169 -- 2 = parcelamento de divida, parcelamento de inicial, parcelamento de contribuicao, inicial do foro e contribuicao
1170 -- 3 = diversos
1171
1172 v_comando = ' select tipo_origem,
1173';
1174 v_comando = v_comando || ' receita,
1175';
1176 v_comando = v_comando || ' receitaori,
1177';
1178 v_comando = v_comando || ' min(k00_hist) as k00_hist,
1179';
1180 v_comando = v_comando || ' round(sum(valor),2) as valor,
1181';
1182 v_comando = v_comando || ' round(sum(total_his),2) as total_his,
1183';
1184 v_comando = v_comando || ' round(sum(total_cor),2) as total_cor,
1185';
1186 v_comando = v_comando || ' round(sum(total_jur),2) as total_jur,
1187';
1188 v_comando = v_comando || ' round(sum(total_mul),2) as total_mul,
1189';
1190 v_comando = v_comando || ' round(sum(total_desccor),2) as total_desccor,
1191';
1192 v_comando = v_comando || ' round(sum(total_descjur),2) as total_descjur,
1193';
1194 v_comando = v_comando || ' round(sum(total_descmul),2) as total_descmul
1195';
1196 v_comando = v_comando || ' from ( select 1 as tipo_origem,
1197';
1198 v_comando = v_comando || ' receit as receita,
1199';
1200 v_comando = v_comando || ' receitaori,
1201';
1202 v_comando = v_comando || ' min(k00_hist) as k00_hist,
1203';
1204 v_comando = v_comando || ' sum(valor) as valor,
1205';
1206 v_comando = v_comando || ' sum(total_his) as total_his,
1207';
1208 v_comando = v_comando || ' sum(total_cor) as total_cor,
1209';
1210 v_comando = v_comando || ' sum(total_jur) as total_jur,
1211';
1212 v_comando = v_comando || ' sum(total_mul) as total_mul,
1213';
1214 v_comando = v_comando || ' sum(total_desccor) as total_desccor,
1215';
1216 v_comando = v_comando || ' sum(total_descjur) as total_descjur,
1217';
1218 v_comando = v_comando || ' sum(total_descmul) as total_descmul
1219';
1220 v_comando = v_comando || ' from ( select a.numpre,
1221';
1222 v_comando = v_comando || ' a.numpar,
1223';
1224 v_comando = v_comando || ' a.receita as receit,
1225';
1226 v_comando = v_comando || ' a.receitaori as receitaori,
1227';
1228 v_comando = v_comando || ' min(k00_hist) as k00_hist,
1229';
1230 v_comando = v_comando || ' sum(a.valor) as valor,
1231';
1232 v_comando = v_comando || ' sum(total_his) as total_his,
1233';
1234 v_comando = v_comando || ' sum(total_cor) as total_cor,
1235';
1236 v_comando = v_comando || ' sum(total_jur) as total_jur,
1237';
1238 v_comando = v_comando || ' sum(total_mul) as total_mul,
1239';
1240 v_comando = v_comando || ' sum(total_desccor) as total_desccor,
1241';
1242 v_comando = v_comando || ' sum(total_descjur) as total_descjur,
1243';
1244 v_comando = v_comando || ' sum(total_descmul) as total_descmul
1245';
1246 v_comando = v_comando || ' from ( select arrecad_parc_rec.numpre,
1247';
1248 v_comando = v_comando || ' arrecad_parc_rec.numpar,
1249';
1250 v_comando = v_comando || ' arrecad_parc_rec.receit as receitaori,
1251';
1252 v_comando = v_comando || ' recparproc.receita as receita,
1253';
1254 v_comando = v_comando || ' min(proced.k00_hist) as k00_hist,
1255';
1256 v_comando = v_comando || ' round(sum(arrecad_parc_rec.valor),2) as valor,
1257';
1258 v_comando = v_comando || ' round(sum(vlrhis),2) as total_his,
1259';
1260 v_comando = v_comando || ' round(sum(vlrcor),2) as total_cor,
1261';
1262 v_comando = v_comando || ' round(sum(vlrjur),2) as total_jur,
1263';
1264 v_comando = v_comando || ' round(sum(vlrmul),2) as total_mul,
1265';
1266 v_comando = v_comando || ' round(sum(vlrdesccor),2) as total_desccor,
1267';
1268 v_comando = v_comando || ' round(sum(vlrdescjur),2) as total_descjur,
1269';
1270 v_comando = v_comando || ' round(sum(vlrdescmul),2) as total_descmul
1271';
1272 v_comando = v_comando || ' from arrecad_parc_rec
1273';
1274 v_comando = v_comando || ' inner join arrecad on arrecad.k00_numpre = arrecad_parc_rec.numpre
1275';
1276 v_comando = v_comando || ' and arrecad.k00_numpar = arrecad_parc_rec.numpar
1277';
1278 v_comando = v_comando || ' and arrecad.k00_receit = arrecad_parc_rec.receit
1279';
1280 v_comando = v_comando || ' and arrecad.k00_valor > 0
1281';
1282 v_comando = v_comando || ' inner join arretipo on arretipo.k00_tipo = arrecad.k00_tipo
1283';
1284 v_comando = v_comando || ' left join divida on divida.v01_numpre = arrecad.k00_numpre
1285';
1286 v_comando = v_comando || ' and divida.v01_numpar = arrecad.k00_numpar
1287';
1288 v_comando = v_comando || ' left join recparproc on recparproc.v03_codigo = divida.v01_proced
1289';
1290 v_comando = v_comando || ' inner join proced on proced.v03_codigo = divida.v01_proced
1291';
1292 v_comando = v_comando || ' where k03_tipo = 5
1293';
1294 if v_juronaultima is true then
1295 v_comando = v_comando || ' and juro is false
1296';
1297 end if;
1298 v_comando = v_comando || ' group by arrecad_parc_rec.numpre,
1299';
1300 v_comando = v_comando || ' arrecad_parc_rec.numpar,
1301';
1302 v_comando = v_comando || ' arrecad_parc_rec.receit,
1303';
1304 v_comando = v_comando || ' recparproc.receita
1305';
1306 v_comando = v_comando || ' ) as a
1307';
1308 v_comando = v_comando || ' group by a.numpre,
1309';
1310 v_comando = v_comando || ' a.numpar,
1311';
1312 v_comando = v_comando || ' a.receita,
1313';
1314 v_comando = v_comando || ' a.receitaori
1315';
1316 v_comando = v_comando || ' ) as x
1317';
1318 v_comando = v_comando || ' group by receit,
1319';
1320 v_comando = v_comando || ' receitaori
1321';
1322
1323 v_comando = v_comando || ' union
1324';
1325
1326 v_comando = v_comando || ' select 2 as tipo_origem,
1327';
1328 v_comando = v_comando || ' case when recparproc.receita is null then
1329';
1330 v_comando = v_comando || ' arrecad_parc_rec.receit
1331';
1332 v_comando = v_comando || ' else
1333';
1334 v_comando = v_comando || ' recparproc.receita
1335';
1336 v_comando = v_comando || ' end as receit,
1337';
1338 v_comando = v_comando || ' arrecad_parc_rec.receit as receitaori,
1339';
1340 v_comando = v_comando || ' min(arrecad.k00_hist) as k00_hist,
1341';
1342 v_comando = v_comando || ' round(sum(arrecad_parc_rec.valor),2) as valor,
1343';
1344 v_comando = v_comando || ' round(sum(vlrhis),2) as total_his,
1345';
1346 v_comando = v_comando || ' round(sum(vlrcor),2) as total_cor,
1347';
1348 v_comando = v_comando || ' round(sum(vlrjur),2) as total_jur,
1349';
1350 v_comando = v_comando || ' round(sum(vlrmul),2) as total_mul,
1351';
1352 v_comando = v_comando || ' round(sum(vlrdesccor),2) as total_desccor,
1353';
1354 v_comando = v_comando || ' round(sum(vlrdescjur),2) as total_descjur,
1355';
1356 v_comando = v_comando || ' round(sum(vlrdescmul),2) as total_descmul
1357';
1358 v_comando = v_comando || ' from arrecad_parc_rec
1359';
1360 v_comando = v_comando || ' inner join arrecad on arrecad.k00_numpre = arrecad_parc_rec.numpre
1361';
1362 v_comando = v_comando || ' and arrecad.k00_numpar = arrecad_parc_rec.numpar
1363';
1364 v_comando = v_comando || ' and arrecad.k00_receit = arrecad_parc_rec.receit
1365';
1366 v_comando = v_comando || ' and arrecad.k00_valor > 0
1367';
1368 v_comando = v_comando || ' inner join arretipo on arretipo.k00_tipo = arrecad.k00_tipo
1369';
1370 v_comando = v_comando || ' left join divida on divida.v01_numpre = arrecad.k00_numpre
1371';
1372 v_comando = v_comando || ' and divida.v01_numpar = arrecad.k00_numpar
1373';
1374 v_comando = v_comando || ' left join recparproc on recparproc.v03_codigo = divida.v01_proced
1375';
1376 v_comando = v_comando || ' left join proced on proced.v03_codigo = divida.v01_proced
1377';
1378 v_comando = v_comando || ' where ( k03_tipo in (6, 13, 18, 17, 4)
1379';
1380 v_comando = v_comando || ' or ( k03_tipo in (7,16)
1381';
1382 v_comando = v_comando || ' and exists (select 1
1383';
1384 v_comando = v_comando || ' from termo
1385';
1386 v_comando = v_comando || ' inner join termoreparc on termoreparc.v08_parcel = termo.v07_parcel
1387';
1388 v_comando = v_comando || ' where v07_numpre = arrecad_parc_rec.numpre) )
1389';
1390 v_comando = v_comando || ' )
1391';
1392 v_comando = v_comando || ' and not exists (select 1
1393';
1394 v_comando = v_comando || ' from termo
1395';
1396 v_comando = v_comando || ' inner join termodiver on termo.v07_parcel = termodiver.dv10_parcel
1397';
1398 v_comando = v_comando || ' where termo.v07_numpre = arrecad_parc_rec.numpre )
1399';
1400 if v_juronaultima is true then
1401 v_comando = v_comando || ' and juro is false
1402';
1403 end if;
1404 v_comando = v_comando || ' group by recparproc.receita,
1405';
1406 v_comando = v_comando || ' arrecad_parc_rec.receit
1407';
1408
1409 v_comando = v_comando || ' union
1410';
1411
1412 v_comando = v_comando || ' select 3 as tipo_origem,
1413';
1414 v_comando = v_comando || ' recparprocdiver.receita,
1415';
1416 v_comando = v_comando || ' arrecad_parc_rec.receit as receitaori,
1417';
1418 v_comando = v_comando || ' procdiver.dv09_hist,
1419';
1420 v_comando = v_comando || ' round(sum(valor),2) as valor,
1421';
1422 v_comando = v_comando || ' round(sum(vlrhis),2) as total_his,
1423';
1424 v_comando = v_comando || ' round(sum(vlrcor),2) as total_cor,
1425';
1426 v_comando = v_comando || ' round(sum(vlrjur),2) as total_jur,
1427';
1428 v_comando = v_comando || ' round(sum(vlrmul),2) as total_mul,
1429';
1430 v_comando = v_comando || ' round(sum(vlrdesccor),2) as total_desccor,
1431';
1432 v_comando = v_comando || ' round(sum(vlrdescjur),2) as total_descjur,
1433';
1434 v_comando = v_comando || ' round(sum(vlrdescmul),2) as total_descmul
1435';
1436 v_comando = v_comando || ' from diversos
1437';
1438 v_comando = v_comando || ' left join (select termodiver.*
1439';
1440 v_comando = v_comando || ' from termodiver
1441';
1442 v_comando = v_comando || ' inner join termo on dv10_parcel = v07_parcel
1443';
1444 v_comando = v_comando || ' and v07_situacao = 1) as termodiver on dv05_coddiver = dv10_coddiver
1445';
1446 v_comando = v_comando || ' left join recparprocdiver on recparprocdiver.procdiver = diversos.dv05_procdiver
1447';
1448 v_comando = v_comando || ' inner join procdiver on procdiver.dv09_procdiver = diversos.dv05_procdiver
1449';
1450 v_comando = v_comando || ' inner join arrecad_parc_rec on diversos.dv05_numpre = arrecad_parc_rec.numpre
1451';
1452 v_comando = v_comando || ' where dv10_coddiver is null
1453';
1454 v_comando = v_comando || ' group by recparprocdiver.receita,
1455';
1456 v_comando = v_comando || ' arrecad_parc_rec.receit,
1457';
1458 v_comando = v_comando || ' procdiver.dv09_hist
1459';
1460
1461 v_comando = v_comando || ' union
1462';
1463
1464 v_comando = v_comando || ' select tipo_origem,
1465';
1466 v_comando = v_comando || ' receita,
1467';
1468 v_comando = v_comando || ' receitaori,
1469';
1470 v_comando = v_comando || ' dv09_hist,
1471';
1472 v_comando = v_comando || ' round(sum(valor),2) as valor,
1473';
1474 v_comando = v_comando || ' round(sum(vlrhis),2) as total_his,
1475';
1476 v_comando = v_comando || ' round(sum(vlrcor),2) as total_cor,
1477';
1478 v_comando = v_comando || ' round(sum(vlrjur),2) as total_jur,
1479';
1480 v_comando = v_comando || ' round(sum(vlrmul),2) as total_mul,
1481';
1482 v_comando = v_comando || ' round(sum(vlrdesccor),2) as total_desccor,
1483';
1484 v_comando = v_comando || ' round(sum(vlrdescjur),2) as total_descjur,
1485';
1486 v_comando = v_comando || ' round(sum(vlrdescmul),2) as total_descmul
1487';
1488 v_comando = v_comando || ' from ( select 4 as tipo_origem,
1489';
1490 v_comando = v_comando || ' (select min(recparprocdiver.receita)
1491';
1492 v_comando = v_comando || ' from termodiver
1493';
1494 v_comando = v_comando || ' inner join diversos on termodiver.dv10_coddiver = dv05_coddiver
1495';
1496 v_comando = v_comando || ' inner join recparprocdiver on recparprocdiver.procdiver = diversos.dv05_procdiver
1497';
1498 v_comando = v_comando || ' inner join procdiver on procdiver.dv09_procdiver = diversos.dv05_procdiver
1499';
1500 v_comando = v_comando || ' where termodiver.dv10_parcel = v07_parcel ) as receita,
1501';
1502 v_comando = v_comando || ' arrecad_parc_rec.receit as receitaori,
1503';
1504 v_comando = v_comando || ' (select min(procdiver.dv09_hist)
1505';
1506 v_comando = v_comando || ' from termodiver
1507';
1508 v_comando = v_comando || ' inner join diversos on termodiver.dv10_coddiver = dv05_coddiver
1509';
1510 v_comando = v_comando || ' inner join recparprocdiver on recparprocdiver.procdiver = diversos.dv05_procdiver
1511';
1512 v_comando = v_comando || ' inner join procdiver on procdiver.dv09_procdiver = diversos.dv05_procdiver
1513';
1514 v_comando = v_comando || ' where termodiver.dv10_parcel = v07_parcel ) as dv09_hist,
1515';
1516 v_comando = v_comando || ' valor,
1517';
1518 v_comando = v_comando || ' vlrhis,
1519';
1520 v_comando = v_comando || ' vlrcor,
1521';
1522 v_comando = v_comando || ' vlrjur,
1523';
1524 v_comando = v_comando || ' vlrmul,
1525';
1526 v_comando = v_comando || ' vlrdesccor,
1527';
1528 v_comando = v_comando || ' vlrdescjur,
1529';
1530 v_comando = v_comando || ' vlrdescmul
1531';
1532 v_comando = v_comando || ' from arrecad_parc_rec
1533';
1534 v_comando = v_comando || ' inner join termo on v07_numpre = arrecad_parc_rec.numpre
1535';
1536 v_comando = v_comando || ' inner join ( select distinct
1537';
1538 v_comando = v_comando || ' dv10_parcel
1539';
1540 v_comando = v_comando || ' from termodiver ) as parcdiver on parcdiver.dv10_parcel = termo.v07_parcel
1541';
1542 v_comando = v_comando || ' ) as diver
1543';
1544 v_comando = v_comando || ' group by tipo_origem,
1545';
1546 v_comando = v_comando || ' receita,receitaori,
1547';
1548 v_comando = v_comando || ' dv09_hist
1549';
1550 v_comando = v_comando || ' ) as xxx
1551';
1552 v_comando = v_comando || 'group by tipo_origem,
1553';
1554 v_comando = v_comando || ' receita,
1555';
1556 v_comando = v_comando || ' receitaori
1557';
1558
1559 if lRaise then
1560 perform fc_debug('sql : '||v_comando,lRaise,false,false);
1561 end if;
1562
1563 if lRaise then
1564 perform fc_debug('v_total: '||v_total,lRaise,false,false);
1565 end if;
1566
1567 v_comando_cria = 'create temp table w_testando as ' || v_comando;
1568 execute v_comando_cria;
1569
1570 -- tipo 3 = parcelamento de diversos
1571 -- tipo 4 = reparcelamento de diversos
1572
1573 -- se regra for de juros na ultima, diminui o total de parcelas em 1
1574 if v_juronaultima is true then
1575 v_totalparcelas = v_totalparcelas - 1;
1576
1577 if lRaise is true then
1578 perform fc_debug('mudando - v_total: '||v_total,lRaise,false,false);
1579 end if;
1580 end if;
1581
1582 -- processa receita por receita para gerar os registros na tabela parcelas
1583 -- que sera utilizada posteriormente para gerar os registros na tabela arrecad
1584 for v_record_recpar in execute v_comando
1585 loop
1586
1587 if v_record_recpar.tipo_origem is null then
1588 return '[6] - Não encontrados registros na tabela Divida para um dos debitos que esta sendo parcelado.';
1589 end if;
1590
1591 if v_record_recpar.receita is null then
1592 return '[7] - Receita de parcelamento nao configurada para a procedencia';
1593 end if;
1594
1595 -- se origem for divida ativa, soma na variavel v_totaldivida
1596 if v_record_recpar.tipo_origem = 1 then
1597 v_totaldivida = v_totaldivida + v_record_recpar.valor;
1598 end if;
1599
1600 if lRaise is true then
1601 perform fc_debug('tipo_origem: '||v_record_recpar.tipo_origem||' - receita: '||v_record_recpar.receita||' - receitaoriginal: '||v_record_recpar.receitaori||' - hist: '||v_record_recpar.k00_hist||' - valor: '||v_record_recpar.valor||' - total_cor: '||v_record_recpar.total_cor,lRaise,false,false);
1602 end if;
1603
1604 -- calcula entrada proporcional ao valor desta receita
1605 -- regra de tres normal em relacao percentual da entrada do registro atual em relacao ao total do parcelamento
1606 -- se for o caso de ter apenas uma receita em processamento, essa variavel vai ser igual ao valor da entrada
1607 v_ent_prop = v_record_recpar.valor * (v_entrada / v_total);
1608 v_total_liquido = v_record_recpar.total_cor + v_record_recpar.total_jur + v_record_recpar.total_mul - v_record_recpar.total_desccor - v_record_recpar.total_descjur - v_record_recpar.total_descmul;
1609
1610 if lRaise is true then
1611 perform fc_debug('xxxxxxxxxxxxx: receita: '||v_record_recpar.receita||' - valor: '||v_record_recpar.valor||' - entrada proporcional: '||v_ent_prop||' - valor: '||v_record_recpar.valor||' - total: '||v_total_liquido,lRaise,false,false);
1612 perform fc_debug(' ',lRaise,false,false);
1613 perform fc_debug('========== receita: '||v_record_recpar.receita,lRaise,false,false);
1614 perform fc_debug(' ',lRaise,false,false);
1615 end if;
1616
1617 -- processa parcela por parcela
1618
1619
1620 for v_parcela in 1..v_totalparcelas
1621 loop
1622
1623 -- variavel do valor da parcela recebe o valor da receita deste registro / valor total do parcelamento
1624 -- que na pratica seria a proporcionalidade deste registro em relacao ao total do parcelamento
1625 v_valparc = v_record_recpar.valor / v_total;
1626
1627 if lRaise is true then
1628 perform fc_debug(' v_valparc: '||v_valparc||' - v_total: '||v_total||' - valor: '||v_record_recpar.valor||' - receit: '||v_record_recpar.receita||' - entrada: '||v_entrada,lRaise,false,false);
1629 end if;
1630
1631 if v_parcela = 1 then
1632 -- se parcela igual a 1, entao valor parcela e igual ao valor da entrada * valor da proporcionalidade
1633 -- deste registro em relacao ao total do parcelamento
1634 v_valparc = v_entrada * v_valparc;
1635 else
1636 -- se nao for a parcela 1 entao
1637 -- valor da parcela recebe o valor da parcela definido pelo usuario na CGF * valor da proporcionalidade
1638 -- deste registro em relacao ao total do parcelamento
1639 v_valparc = v_valorparcelanew * v_valparc;
1640 end if;
1641
1642 --v_valparc = round(v_valparc,2);
1643
1644 if lRaise is true then
1645 perform fc_debug(' 000 = parcela: '||v_parcela||' - receita: '||v_record_recpar.receita||' - valor: '||v_valparc||' - v_valorparcelanew: '||v_valorparcelanew||' - receitaori: '||v_record_recpar.receitaori,lRaise,false,false);
1646 end if;
1647
1648 v_calcula_valprop = v_record_recpar.valor / v_total;
1649 v_teste = v_record_recpar.valor / v_total;
1650
1651 if v_teste <= 0 then
1652
1653 if lRaise is true then
1654 perform fc_debug('valor: '||v_record_recpar.valor||' - v_total: '||v_total||' - v_teste: '||v_teste||' - parcela: '||v_parcela||' - receita: '||v_record_recpar.receita||' - v_calcula_valprop: '||v_calcula_valprop,lRaise,false,false);
1655 end if;
1656 end if;
1657
1658 if lRaise is true then
1659 perform fc_debug('v_valparc: '||v_valparc||' - valor: '||v_record_recpar.valor||' - total_his: '||v_record_recpar.total_his||' - total: '||v_total,lRaise,false,false);
1660 end if;
1661
1662 --Adicionado arredondamento e função para retornar o mÃnimo monetário
1663 v_calcula_valor = (v_record_recpar.valor);
1664 v_calcula_his = fc_arredondaminimomonetario(v_valparc / v_record_recpar.valor * v_record_recpar.total_his);
1665 v_calcula_cor = fc_arredondaminimomonetario(v_valparc / v_record_recpar.valor * v_record_recpar.total_cor);
1666 v_calcula_jur = fc_arredondaminimomonetario(v_valparc / v_record_recpar.valor * v_record_recpar.total_jur);
1667 v_calcula_mul = fc_arredondaminimomonetario(v_valparc / v_record_recpar.valor * v_record_recpar.total_mul);
1668 v_calcula_desccor = v_valparc / v_calcula_valor * v_record_recpar.total_desccor;
1669 v_calcula_descjur = fc_arredondaminimomonetario(v_valparc / v_calcula_valor * v_record_recpar.total_descjur);
1670 v_calcula_descmul = fc_arredondaminimomonetario(v_valparc / v_calcula_valor * v_record_recpar.total_descmul);
1671
1672 --Arredonda o valor da parcela para inserir na tabela parcelas já arrendado, local onde servirá de base para inserir os valores na arrecad
1673 v_valparc = round((fc_arredondaminimomonetario(v_valparc)),2);
1674
1675 if lRaise then
1676 perform fc_debug('v_calcula_his: '||v_calcula_his||' - v_valparc: '||v_valparc||' - v_calcula_valor: '||v_calcula_valor||' - total_desccor: '||v_record_recpar.total_desccor,lRaise,false,false);
1677 end if;
1678
1679 -- Calcula a soma do valor por receita antes do parcelamento.
1680 select
1681 sum(valor) as valor_maximo,
1682 sum(vlrhis) as valor_historico,
1683 sum(vlrcor) as valor_correcao,
1684 sum(vlrjur) as valor_juro,
1685 sum(vlrmul) as valor_multa,
1686 sum(vlrdescjur) as valor_descontoJuro,
1687 sum(vlrdescmul) as valor_descontoMulta
1688 into nValorMaximoReceita,
1689 nValorMaximoHistorico,
1690 nValorMaximoCorrecao,
1691 nValorMaximoJuro,
1692 nValorMaximoMulta,
1693 nValorMaximoDescontoJuro,
1694 nValorMaximoDescontoMulta
1695 from arrecad_parc_rec
1696 where receit = v_record_recpar.receitaori
1697 group by receit;
1698
1699 select receit,
1700 receitaori,
1701 sum(valor),
1702 sum(valhis),
1703 sum(valcor),
1704 sum(valjur),
1705 sum(valmul),
1706 sum(descjur),
1707 sum(descmul)
1708 into v_record_parcelas_receit,
1709 v_record_parcelas_receitaori,
1710 v_record_parcelas_valor,
1711 v_record_parcelas_valhis,
1712 v_record_parcelas_valcor,
1713 v_record_parcelas_valjur,
1714 v_record_parcelas_valmul,
1715 v_record_parcelas_descjur,
1716 v_record_parcelas_descmul
1717 from parcelas
1718 where receitaori = v_record_recpar.receitaori
1719 group by receit, receitaori;
1720
1721 -- Se alguma das colunas atingiu o máximo então zera este valor para que não lance valores errados
1722 if v_record_parcelas_valor >= nValorMaximoReceita then
1723 v_valparc = 0;
1724 end if;
1725
1726 if v_record_parcelas_valhis >= nValorMaximoHistorico then
1727 v_calcula_his = 0;
1728 end if;
1729
1730 if v_record_parcelas_valcor >= nValorMaximoCorrecao then
1731 v_calcula_cor = 0;
1732 end if;
1733
1734 if v_record_parcelas_valjur >= nValorMaximoJuro then
1735 v_calcula_jur = 0;
1736 end if;
1737
1738 if v_record_parcelas_valmul >= nValorMaximoMulta then
1739 v_calcula_mul = 0;
1740 end if;
1741
1742 if v_record_parcelas_descjur >= nValorMaximoDescontoJuro then
1743 v_calcula_descjur = 0;
1744 end if;
1745
1746 if v_record_parcelas_descmul >= nValorMaximoDescontoMulta then
1747 v_calcula_descmul = 0;
1748 end if;
1749
1750 --Verifica se o valor da tabela parcelas já atingiu o máximo para a receita
1751 if v_record_parcelas_valor >= nValorMaximoReceita
1752 AND v_record_parcelas_valhis >= nValorMaximoHistorico
1753 AND v_record_parcelas_valcor >= nValorMaximoCorrecao
1754 AND v_record_parcelas_valjur >= nValorMaximoJuro
1755 AND v_record_parcelas_valmul >= nValorMaximoMulta
1756 AND v_record_parcelas_descjur >= nValorMaximoDescontoJuro
1757 AND v_record_parcelas_descmul >= nValorMaximoDescontoMulta
1758 then
1759 continue;
1760 end if;
1761
1762 if v_valparc > 0 then
1763
1764 if round(v_valparc,2) > 0 then
1765
1766 lIncluiEmParcelas = true;
1767
1768 else
1769
1770 perform * from parcelas where receit = v_record_recpar.receita;
1771
1772 if found then
1773 lIncluiEmParcelas = false;
1774 else
1775 lIncluiEmParcelas = true;
1776 end if;
1777
1778 end if;
1779
1780 if lIncluiEmParcelas is true then
1781
1782 -- insere valores calculados na tabela parcelas
1783 execute 'insert into parcelas values (' || v_parcela || ',' ||
1784 v_record_recpar.receita || ',' ||
1785 v_record_recpar.receitaori || ',' ||
1786 v_record_recpar.k00_hist || ',' ||
1787 v_valparc || ',' ||
1788 v_calcula_valprop || ',' ||
1789 v_calcula_his || ',' ||
1790 v_calcula_cor || ',' ||
1791 v_calcula_jur || ',' ||
1792 v_calcula_mul || ',' ||
1793 v_calcula_desccor || ',' ||
1794 v_calcula_descjur || ',' ||
1795 v_calcula_descmul ||
1796 ');';
1797
1798 else
1799
1800 execute 'update parcelas set ' ||
1801 ' valor = valor + ' || v_valparc ||
1802 ', valprop = valprop + ' || v_calcula_valprop ||
1803 ', valhis = valhis + ' || v_calcula_his ||
1804 ', valcor = valcor + ' || v_calcula_cor ||
1805 ', valjur = valjur + ' || v_calcula_jur ||
1806 ', valmul = valmul + ' || v_calcula_mul ||
1807 ', descor = descor + ' || v_calcula_desccor ||
1808 ', descjur = descjur + ' || v_calcula_descjur ||
1809 ', descmul = descmul + ' || v_calcula_descmul ||
1810 ' where receit = ' || v_record_recpar.receita;
1811
1812 end if;
1813
1814 end if;
1815
1816 end loop;
1817
1818 end loop;
1819
1820 -- se regra for de juros na ultima
1821 if v_juronaultima is true then
1822
1823 if lRaise is true then
1824 perform fc_debug('processando ultima... diferenca: '||(v_totalcomjuro - v_total),lRaise,false,false);
1825 end if;
1826
1827 -- soma 1 na variavel do total de parcelas
1828 v_totalparcelas = v_totalparcelas + 1;
1829
1830 -- gera comando para agrupar receita por receita somando o valor
1831 v_comando = ' select arrecad_parc_rec. ';
1832 v_comando = v_comando || ' receit as receita, ';
1833 v_comando = v_comando || ' sum(arrecad_parc_rec.valor) as valor ';
1834 v_comando = v_comando || ' from arrecad_parc_rec ';
1835 v_comando = v_comando || ' where juro is true ';
1836 v_comando = v_comando || ' group by arrecad_parc_rec.receit ';
1837
1838 select v04_histjuros
1839 from pardiv
1840 into v_histjuro;
1841 if v_histjuro is null then
1842 v_histjuro = 1;
1843 end if;
1844
1845 for v_record_recpar in execute v_comando
1846 loop
1847
1848 v_valorinserir = round(v_record_recpar.valor,2);
1849
1850 if lRaise is true then
1851 perform fc_debug('111 = inserindo diferenca: '||v_valorinserir||' - receita: '||v_record_recpar.receita||' - valor: '||v_record_recpar.valor.lRaise,false,false);
1852 end if;
1853
1854 execute 'insert into parcelas values (' || v_totalparcelas || ',' ||
1855 v_record_recpar.receita || ',' ||
1856 v_record_recpar.receita || ',' ||
1857 v_histjuro || ',' ||
1858 v_valorinserir || ',' ||
1859 (v_valorinserir) / v_totalcomjuro ||
1860 ');';
1861
1862 end loop;
1863
1864 v_total = v_totalcomjuro;
1865
1866 end if;
1867
1868 if lRaise is true then
1869 perform fc_debug('saindo do tipo 5...',lRaise,false,false);
1870 end if;
1871
1872 if lRaise is true then
1873 perform fc_debug(' ',lRaise,false,false);
1874 perform fc_debug('-',lRaise,false,false);
1875 perform fc_debug(' ',lRaise,false,false);
1876 perform fc_debug('terminou de gravar na tabela parcelas...',lRaise,false,false);
1877 end if;
1878
1879 update parcelas set valor = w_testando.valor,
1880 valhis = w_testando.total_his,
1881 valcor = w_testando.total_cor,
1882 valjur = w_testando.total_jur,
1883 valmul = w_testando.total_mul,
1884 descor = w_testando.total_desccor,
1885 descjur = w_testando.total_descjur,
1886 descmul = w_testando.total_descmul
1887 from w_testando
1888 where receit = w_testando.receita
1889 and parcelas.valor = 0;
1890
1891 -- calcula a maior parcela e a soma do valor dos registros da tabela parcelas
1892 select max(parcela),
1893 sum(valor)
1894 from parcelas
1895 into v_totpar, v_somar;
1896
1897 if lRaise is true then
1898 perform fc_debug('total de parcelas: '||v_totpar||' - v_somar: '||v_somar,lRaise,true,true);
1899 end if;
1900
1901 -- testa se ocorreu alguma inconsistencia
1902 if v_totpar = 0 or v_totpar is null then
1903 return '[8] - Erro ao gerar parcelas... provavelmente falta recparproc...';
1904 end if;
1905
1906 select sum(valor)
1907 into v_totalliquido
1908 from parcelas;
1909
1910 if lRaise is true then
1911 perform fc_debug('v_totalliquido: '||v_totalliquido,lRaise,true,true);
1912 end if;
1913
1914 --raise notice 'trocando total (%) por total_liquido (%)', v_total, v_totalliquido;
1915 --v_total = v_totalliquido;
1916
1917 -- se for
1918 -- 6 = parcelamento de divida
1919 -- 16 = parcelamento de inicial
1920 -- 17 = parcelamento de melhorias
1921 -- 13 = inicial do foro
1922 if v_tipo in (6,16,17,13) then
1923
1924 -- conta a quantidade de parcelamentos
1925 select count(v07_parcel)
1926 into v_quantparcel
1927 from (select distinct
1928 v07_parcel
1929 from termo
1930 inner join numpres_parc on termo.v07_numpre = numpres_parc.k00_numpre) as x;
1931 if v_quantparcel is null then
1932 return '[9] - Parcelamento nao encontrado pelo numpre';
1933 end if;
1934
1935 -- registra o codigo do parcelamento
1936 select v07_parcel
1937 into v_termo_ori
1938 from termo
1939 inner join numpres_parc on termo.v07_numpre = numpres_parc.k00_numpre
1940 limit 1;
1941
1942 end if;
1943
1944 -- recebe o codigo do novo parcelamento
1945 select nextval('termo_v07_parcel_seq') into v_termo;
1946
1947 -- recebe o numpre do novo parcelamento
1948 select nextval('numpref_k03_numpre_seq') into v_numpre;
1949
1950 if lRaise is true then
1951 perform fc_debug('termo '||v_termo,lRaise,false,false);
1952 perform fc_debug('numpre '||v_numpre,lRaise,false,false);
1953 end if;
1954
1955 -- se for reparelamento pega todos os parcelamentos atuais e troca a situacao para 3(inativo)
1956 if lParcParc then
1957
1958 for v_record_origem in
1959 select distinct v07_parcel
1960 from termo
1961 inner join numpres_parc on termo.v07_numpre = numpres_parc.k00_numpre
1962 loop
1963 -- inativa o parcelamento
1964 update termo
1965 set v07_situacao = 3
1966 where v07_parcel = v_record_origem.v07_parcel;
1967
1968 end loop;
1969 end if;
1970
1971 --if lSeparaJuroMulta and 1=2 then
1972 /**
1973 * Funcao fc_SeparaJuroMulta()
1974 *
1975 * Esta funcao separa o valor do juros e da multa
1976 * em registros separados, lancando valor na receita de juro e multa
1977 * configurada na tabrec.
1978 */
1979 --select * from fc_SeparaJuroMulta() into rSeparaJurMul;
1980
1981 --end if;
1982
1983 -- registra o ano do vencimento da segunda parcela
1984 select extract (year from v_segvenc) into v_anovenc;
1985
1986 -- registra o mes do vencimento da segunda parcela
1987 select extract (month from v_segvenc) into v_mesvenc;
1988
1989 if lRaise is true then
1990 perform fc_debug('v_anovenc: '||v_anovenc||' - v_mesvenc: '||v_mesvenc,lRaise,false,false);
1991 end if;
1992
1993 v_somar = 0;
1994
1995 -- soma o valor total da tabela parcelas, apenas para conferencia
1996 for v_record_recpar in select parcela,
1997 receit,
1998 valor
1999 from parcelas
2000 loop
2001 v_somar = v_somar + v_record_recpar.valor;
2002 if lRaise is true then
2003 perform fc_debug('parcela: '||v_record_recpar.parcela||' - receita: '||v_record_recpar.receit||' - valor: '||v_record_recpar.valor,lRaise,false,false);
2004 end if;
2005 end loop;
2006
2007 if lRaise is true then
2008 perform fc_debug('v_somar: '||v_somar,lRaise,false,false);
2009 end if;
2010
2011 -- exibe os valores da tabela parcelas agrupado por receita, apenas para conferencia
2012 for v_record_recpar in select receit,
2013 sum(valor) as valor,
2014 sum(valhis+valcor+valjur+valmul-descor-descjur-descmul) as sum
2015 from parcelas
2016 group by receit
2017 loop
2018 if lRaise is true then
2019 perform fc_debug('valor da receita: '||v_record_recpar.receit||' - liquido: '||v_record_recpar.sum||' - valor: '||v_record_recpar.valor,lRaise,false,false);
2020 end if;
2021 end loop;
2022
2023 -- varre a tabela parcelas por receita para gravar os registros no arrecad
2024 -- existe uma tabela chamada totrec que recebe os valores ja processados e armazena por receita
2025
2026 -- verifica se tem registro na tabela de configuracao da receita forcada como receita de destino
2027
2028 for v_record_recpar in select distinct
2029 receitaori
2030 from parcelas
2031 loop
2032
2033 select case
2034 when coalesce( (select count(*)
2035 from recreparcori a
2036 inner join recreparcarretipo on k72_codigo = a.k70_codigo
2037 where a.k70_recori = recreparcori.k70_recori ),0) = 0
2038 then k71_recdest
2039 else case
2040 when coalesce( ( select count(*)
2041 from recreparcarretipo
2042 where k72_codigo = recreparcori.k70_codigo
2043 and k72_arretipo = v_tiponovo ),0) = 0
2044 then null
2045 else k71_recdest
2046 end
2047 end as destino
2048 into v_recdestino
2049 from recreparcori
2050 inner join recreparcdest on k70_codigo = k71_codigo
2051 where k70_recori = v_record_recpar.receitaori
2052 and v_totparc >= k70_vezesini
2053 and v_totparc <= k70_vezesfim
2054 and
2055 (
2056 ( ( select count(*)
2057 from recreparcori a
2058 inner join recreparcarretipo on k72_codigo = a.k70_codigo
2059 where a.k70_recori = recreparcori.k70_recori) = 0
2060 and ( select count(*)
2061 from recreparcarretipo
2062 where k72_codigo = recreparcori.k70_codigo
2063 and k72_arretipo = v_tiponovo) = 0
2064 )
2065 or
2066 ( select count(*)
2067 from recreparcori a
2068 inner join recreparcarretipo on k72_codigo = a.k70_codigo
2069 where a.k70_recori = recreparcori.k70_recori) > 0
2070 and (select count(*)
2071 from recreparcarretipo
2072 where k72_codigo = recreparcori.k70_codigo
2073 and k72_arretipo = v_tiponovo) > 0
2074 );
2075
2076
2077 if lRaise is true or 1 = 1 then
2078 perform fc_debug('v_recdestino: '||v_recdestino||' - receitaori: '||v_record_recpar.receitaori||' - v_totparc: '||v_totparc||' - v_tiponovo: '||v_tiponovo,lRaise,false,false);
2079 end if;
2080
2081 if v_recdestino is not null or v_recdestino <> 0 then
2082 execute ' update parcelas set receit = ' || v_recdestino || ' where ' ||
2083 ' receitaori = ' || v_record_recpar.receitaori || ';';
2084 end if;
2085
2086 end loop;
2087
2088 create temp table w_base_parcelas as
2089 select parcela,
2090 receit,
2091 array_accum(distinct receitaori) as receitaori,
2092 min(hist) as hist,
2093 sum(valor) as valor,
2094 sum(valprop) as valprop,
2095 sum(valhis) as valhis,
2096 sum(valcor) as valcor,
2097 sum(valjur) as valjur,
2098 sum(valmul) as valmul,
2099 sum(descor) as descor,
2100 sum(descjur) as descjur,
2101 sum(descmul) as descmul
2102 from parcelas
2103 group by parcela, receit
2104 order by receit, parcela;
2105
2106 if lRaise is true then
2107 perform fc_debug('total de parcelas: '||v_totpar||' - v_somar: '||v_somar,lRaise,false,false);
2108 end if;
2109
2110 if lRaise is true then
2111 perform fc_debug(' ',lRaise,false,false);
2112 perform fc_debug(' ',lRaise,false,false);
2113 perform fc_debug(' ',lRaise,false,false);
2114 perform fc_debug(' ',lRaise,false,false);
2115 perform fc_debug(' ',lRaise,false,false);
2116 end if;
2117
2118 for v_record_recpar in select *
2119 from w_base_parcelas
2120 order by parcela, receit
2121 loop
2122
2123 select count(parcela) into ultimaparcelareceita
2124 from parcelas
2125 where receit = v_record_recpar.receit;
2126
2127 if lRaise is true then
2128 perform fc_debug(' inicio do loop... parcela: '||v_record_recpar.parcela||' - receita: '||v_record_recpar.receit||' - v_totalparcelas: '||v_totalparcelas||' - valor: '||v_record_recpar.valor||' - valprop: '||v_record_recpar.valprop,lRaise,false,false);
2129 end if;
2130
2131 lParcelaZerada = false;
2132
2133 -- conta o total de parcelas desta receita
2134 select max(parcela)
2135 into v_totparcdestarec
2136 from parcelas
2137 where receit = v_record_recpar.receit;
2138
2139 -- soma o que ja foi inserido na tabela totrec da receita do registro atual
2140 select coalesce(sum(valor),0) into v_totateagora from totrec where receit = v_record_recpar.receit;
2141
2142 -- soma o total do valor da tabela parcelas da receita do registro atual
2143 -- V E R I F I C A R
2144 select round(sum(valor+valcor+valjur+valmul),2) into v_calcular from parcelas where receit = v_record_recpar.receit;
2145
2146 if lRaise is true then
2147 perform fc_debug('v_calcular: '||v_calcular,lRaise,false,false);
2148 end if;
2149
2150 if lRaise is true then
2151 perform fc_debug(' ',lRaise,false,false);
2152 perform fc_debug('total desta receita: '||v_record_recpar.receit||' - ate agora: '||v_totateagora,lRaise,false,false);
2153 perform fc_debug(' ',lRaise,false,false);
2154 end if;
2155
2156 -- registra o valor da receita do registro atual
2157 v_valparc = v_record_recpar.valor;
2158
2159 -- se for a ultima parcela
2160 if v_record_recpar.parcela = v_totalparcelas or v_record_recpar.parcela = ultimaparcelareceita then
2161
2162 -- se for juros na ultima
2163 if v_juronaultima is true then
2164
2165 -- valor da parcela recebe exatamente o valor registrado na receita do registro atual
2166 v_valparc = v_valparc;
2167 else
2168
2169 if lRaise is true then
2170 perform fc_debug('U L T I M A... - RECEITA: '||v_record_recpar.receit,lRaise,false,false);
2171 perform fc_debug('v_totalparcelas: '||v_totalparcelas||' - v_valparc: '||v_valparc||' - v_entrada: '||v_entrada||' - v_total: '||v_total||' - valprop: '||v_record_recpar.valprop,lRaise,false,false);
2172 end if;
2173
2174 if lRaise is true then
2175 perform fc_debug('total desta receita: '||v_record_recpar.receit||' - ate agora: '||v_totateagora,lRaise,false,false);
2176 end if;
2177
2178 -- saldo e calculado com
2179 -- (o total de parcelas - 2) * valor registrado na receita do registro atual
2180 --v_saldo = round((v_totalparcelas - 2) * ( v_valparc + v_record_recpar.valcor + v_record_recpar.valjur + v_record_recpar.valmul),2);
2181 v_saldo = (v_totalparcelas - 2) * v_valparc;
2182
2183 if lRaise is true then
2184 perform fc_debug('Saldo Atual: '||v_saldo,lRaise,false,false);
2185 end if;
2186
2187 -- saldo eh calculado com
2188 -- saldo calculado + ( entrada * valor proporcional dessa receita em relacao ao total do parcelamento )
2189 v_saldo = v_saldo + (v_entrada * v_record_recpar.valprop);
2190
2191 if lRaise is true then
2192 perform fc_debug('111 - v_saldo: '||v_saldo||' - v_totateagora: '||v_totateagora||' - v_calcular: '||v_calcular,lRaise,false,false);
2193 end if;
2194
2195 if lRaise is true then
2196 perform fc_debug('totateagora: '||v_totateagora||' - total: '||v_total||' - valprop: '||v_record_recpar.valprop||' - saldo: '||v_saldo||' - rec: '||v_record_recpar.receit||' - parc: '||v_record_recpar.parcela||' - hist: '||v_record_recpar.hist,lRaise,false,false);
2197 end if;
2198
2199 -- se total ate agora for maior ou igual ao total do parcelamento * valor proporcional dessa receita em relacao ao total do parcelamento
2200 if round(v_totateagora, 2) >= round(v_total * v_record_recpar.valprop, 2) then
2201 if lRaise is true then
2202 perform fc_debug('v_totateagora: '||v_totateagora||' - v_total: '||v_total||' - valprop: '||v_record_recpar.valprop, lRaise,false,false);
2203 perform fc_debug('passou na ultima...',lRaise,false,false);
2204 end if;
2205 -- valor da parcela recebe zero
2206 v_valparc = 0;
2207 lParcelaZerada=true;
2208 continue;
2209
2210 -- se total ate agora for menor ao total do parcelamento * valor proporcional dessa receita em relacao ao total do parcelamento
2211 else
2212
2213 if lRaise is true then
2214 perform fc_debug('nao passou na ultima... v_total: '||v_total||' - v_saldo: '||v_saldo||' - prop: '||v_record_recpar.valprop,lRaise,false,false);
2215 end if;
2216
2217 nValorMaximoReceita = 0;
2218
2219 -- total que deve ser gerado para a receita de destino
2220 select sum(valor)
2221 into nValorMaximoReceita
2222 from w_testando
2223 where receita = v_record_recpar.receit;
2224
2225 -- valor da ultima parcela da receita é composta por ((x) - (y))
2226 -- ((x) - (y))
2227 -- (total que deve ser gerado para a receita) - (total que já foi gerado para a receita)
2228 -- (sum de valor em w_base_parcelas da receita) - (sum de valor em totrec da receita)
2229 v_valparc = nValorMaximoReceita - v_totateagora;
2230
2231 if lRaise is true then
2232 perform fc_debug('v_valparc: '||v_valparc,lRaise,false,false);
2233 end if;
2234
2235 -- se valor da parcela for menor que zero
2236 if v_valparc < 0 then
2237
2238 -- valor da parcela recebe
2239 -- (total do parcelamento * valor proporcional dessa receita em relacao ao total do parcelamento) - saldo - valor da parcela
2240 v_valparc = (v_total * v_record_recpar.valprop) - v_saldo - v_valparc;
2241 if lRaise is true then
2242 perform fc_debug(' ',lRaise,false,false);
2243 perform fc_debug('t e s t e: '||v_valparc,lRaise,false,false);
2244 perform fc_debug(' ',lRaise,false,false);
2245 end if;
2246 end if;
2247
2248 --v_valparc := ( v_valparc - ( v_record_recpar.valcor + v_record_recpar.valjur + v_record_recpar.valmul ) );
2249
2250 end if;
2251
2252 if lRaise is true then
2253 perform fc_debug('Valor ultima parcela : '||v_valparc,lRaise,false,false);
2254 end if;
2255
2256 -- resto recebe valor da parcela + total ate agora
2257 v_resto = v_valparc + v_totateagora;
2258
2259 if lRaise is true then
2260 perform fc_debug('222 - v_saldo: '||v_saldo||' - totateagora: '||v_resto||' - v_valparc: '||v_valparc||' - v_calcular: '||v_calcular,lRaise,false,false);
2261 end if;
2262
2263 end if;
2264
2265 -- se nao for a ultima parcela
2266 else
2267
2268 if lRaise is true then
2269 perform fc_debug(' ',lRaise,false,false);
2270 perform fc_debug(' n a o e a u l t i m a ',lRaise,false,false);
2271 perform fc_debug(' ',lRaise,false,false);
2272 end if;
2273
2274 -- se for juros na ultima
2275 if v_juronaultima is true then
2276
2277 -- se eh a penultima parcela
2278 if v_record_recpar.parcela = (v_totalparcelas - 1) then
2279
2280 if lRaise is true then
2281 perform fc_debug('nessa',lRaise,false,false);
2282 end if;
2283
2284 end if;
2285
2286 end if;
2287
2288 if lRaise is true then
2289 perform fc_debug('v_totalparcelas: '||v_totalparcelas||' - v_valparc: '||v_valparc||' - v_entrada: '||v_entrada||' - valprop: '||v_record_recpar.valprop||' - v_total: '||v_total,lRaise,false,false);
2290 end if;
2291
2292 -- saldo recebe (total de parcelas - 2) * valor da parcela
2293 -- V E R I F I C A R
2294 v_saldo = (v_totalparcelas - 2) * ( v_valparc + v_record_recpar.valcor + v_record_recpar.valjur + v_record_recpar.valmul );
2295
2296 -- saldo recebe: saldo + (entrada * valor proporcional dessa receita em relacao ao total do parcelamento) - saldo - valor da parcela)
2297 v_saldo = v_saldo + (v_entrada * v_record_recpar.valprop);
2298
2299 if lRaise is true then
2300 perform fc_debug('v_valparc: '||v_valparc,lRaise,false,false);
2301 perform fc_debug('parcela: '||v_record_recpar.parcela||' - v_valparc: '||v_valparc||' - saldo: '||v_saldo||' - resto: '||v_resto,lRaise,false,false);
2302 end if;
2303
2304 -- se total ate agora for maior que total da receita do registro atual
2305 if round(v_totateagora,2) > round(v_calcular,2) then
2306
2307 -- (desativado) v_valparc = round(v_saldo - round((v_record_recpar.parcela - 1) * v_valparc,2)::float8,2);
2308 -- valor da parcela recebe zero
2309 v_valparc = 0;
2310 if lRaise is true then
2311 perform fc_debug('Valor da parcela recebendo ZERO valparc : '||v_valparc,lRaise,false,false);
2312 perform fc_debug('111111111111111111111',lRaise,false,false);
2313 end if;
2314
2315 -- se total ate agora for menor ou igual que total da receita do registro atual
2316 else
2317
2318 -- valor ate agora recebe: parcela * valor da parcela
2319 -- V E R I F I C A R
2320 v_vlrateagora = v_record_recpar.parcela * (v_valparc + v_record_recpar.valcor + v_record_recpar.valjur + v_record_recpar.valmul);
2321
2322 if lRaise is true then
2323 perform fc_debug('v_vlrateagora: '||v_vlrateagora||' - v_valparc: '||v_valparc,lRaise,false,false);
2324 end if;
2325
2326 -- resto recebe: (valor total do parcelamento * valor proporcional dessa receita em relacao ao total do parcelamento) - saldo
2327 v_resto = v_total * v_record_recpar.valprop - v_saldo;
2328
2329 if lRaise is true then
2330 perform fc_debug('parcela: '||v_record_recpar.parcela||' - v_valparc: '||v_valparc||' - saldo: '||v_saldo||' - resto: '||v_resto,lRaise,false,false);
2331 end if;
2332
2333 if lRaise is true then
2334 perform fc_debug('v_totateagora: '||v_totateagora||' - v_valparc: '||v_valparc||' - v_calcular: '||v_calcular,lRaise,false,false);
2335 end if;
2336
2337 -- se (total ate agora + valor da parcela) for maior que total da receita do registro atual
2338 if (v_totateagora + v_valparc) > v_calcular then
2339
2340 -- valor da parcela recebe: total da receita do registro atual - total ate agora
2341 v_valparc = v_calcular - v_totateagora;
2342 if lRaise is true then
2343 perform fc_debug('22222222222',lRaise,false,false);
2344 end if;
2345 end if;
2346
2347 end if;
2348
2349 end if;
2350
2351 if lRaise is true then
2352 perform fc_debug(' ...',lRaise,false,false);
2353 end if;
2354
2355 -- se parcela = 1
2356 if v_record_recpar.parcela = 1 then
2357 -- vencimento igual ao vencimento da entrada especificada na CGF
2358 v_vcto = v_privenc;
2359 -- valor da parcela = entrada * proporcionalidade
2360 if lRaise is true then
2361 perform fc_debug('v_entrada: '||v_entrada||' - valprop: '||v_record_recpar.valprop||' - valcor: '||v_record_recpar.valcor||' - valju: '||v_record_recpar.valjur||' - valmul: '||v_record_recpar.valmul,lRaise,false,false);
2362 end if;
2363
2364 if lRaise is true then
2365 perform fc_debug(' 1 === v_valparc: '||v_valparc||' - v_entrada: '||v_entrada||' - valprop: '||v_record_recpar.valprop, lRaise, false,false);
2366 end if;
2367
2368 v_valparc = fc_arredondaminimomonetario((v_entrada) * v_record_recpar.valprop);
2369
2370 if lRaise is true then
2371 perform fc_debug(' 2 === v_valparc: '||v_valparc,lRaise, false,false);
2372 end if;
2373
2374 elsif v_record_recpar.parcela = 2 then
2375 -- vencimento = vencimento da segunda parcela especificada na CGF
2376 v_vcto = v_segvenc;
2377 else
2378
2379 -- soma meses para calcular vencimento baseado na data de vencimento da parcela 2
2380 execute 'truncate vcto';
2381 v_comando = 'insert into vcto select ' || '''' || to_char(v_segvenc,'yyyy') || '-' || trim(to_char(v_segvenc, 'mm')) || '-' || trim(to_char(v_segvenc, 'dd')) || '''' || '::date' || '+' || '''' || v_record_recpar.parcela - 3 || ' months' || '''' || '::interval';
2382 execute v_comando;
2383
2384 select extract (month from data),
2385 extract (year from data)
2386 from vcto
2387 into v_mesvenc,
2388 v_anovenc;
2389
2390 if lRaise is true then
2391 perform fc_debug('',lRaise,false,false);
2392 perform fc_debug('v_mesvenc: '||v_mesvenc||' - parcela: '||v_record_recpar.parcela,lRaise,false,false);
2393 perform fc_debug('',lRaise,false,false);
2394 end if;
2395
2396 -- se mes for 12 (dezembro)
2397 if to_number(to_char(v_segvenc,'mm'), '999') = 12 then
2398 -- proximo mes = 1 (janeiro)
2399 v_proxmessegvenc = 1;
2400 else
2401 -- soma mes
2402 v_proxmessegvenc = to_number(to_char(v_segvenc,'mm'), '999') + 1;
2403 end if;
2404
2405 -- faz o mes ficar sempre com 2 digitos
2406 if v_proxmessegvenc < 10 then
2407 v_proxmessegvenc_c = '0' || trim(to_char(v_proxmessegvenc, '99'));
2408 else
2409 v_proxmessegvenc_c = trim(to_char(v_proxmessegvenc, '999'));
2410 end if;
2411
2412 -- registra o dia do proximo vencimento especifidada na CGF
2413 v_dia = v_diaprox;
2414
2415 -- soma 1 no mes de vencimento
2416 v_mesvenc = v_mesvenc + 1;
2417 if lRaise is true then
2418 perform fc_debug(' executando vcto... v_segvenc: '||v_segvenc||' - v_diaprox: '||v_diaprox||' - v_dia: '||v_dia||' - v_mesvenc: '||v_mesvenc||' - parc: '||v_record_recpar.parcela,lRaise,false,false);
2419 end if;
2420
2421 -- se ultrapassar dezembro, passa para janeiro do ano seguinte
2422 if v_mesvenc = 13 then
2423 v_mesvenc = 1;
2424 v_anovenc = v_anovenc + 1;
2425 end if;
2426
2427 v_mesvencprox = v_mesvenc + 1;
2428 v_anovencprox = v_anovenc;
2429
2430 -- se ultrapassar dezembro, passa para janeiro do ano seguinte
2431 if v_mesvencprox = 13 then
2432 v_mesvencprox = 1;
2433 v_anovencprox = v_anovencprox + 1;
2434 end if;
2435
2436 if lRaise is true then
2437 perform fc_debug('quase... v_mesvencprox: '||v_mesvencprox||' - v_anovencprox: '||v_anovencprox,lRaise,false,false);
2438 end if;
2439 -- calcula ultimo dia de fevereiro
2440 v_ultdiafev_c = trim(to_char(v_anovencprox,'99999')) || '-' || trim(to_char(v_mesvencprox, '999')) || '-01';
2441 if lRaise is true then
2442 perform fc_debug(' 1 - v_ultdiafev_c: '||v_ultdiafev_c,lRaise,false,false);
2443 end if;
2444 -- calcula ultimo dia de fevereiro
2445 v_ultdiafev_d = trim(v_ultdiafev_c)::date - 1;
2446
2447 if lRaise is true then
2448 perform fc_debug(' 2 - v_ultdiafev_d: '||v_ultdiafev_d,lRaise,false,false);
2449 end if;
2450 -- calcula ultimo dia de fevereiro
2451 v_ultdiafev = to_number(to_char(v_ultdiafev_d, 'dd'), '999');
2452
2453 -- testa se dia e valido nos meses
2454 if v_dia = 31 and v_mesvenc in (4, 6, 9, 11) then
2455 v_dia = 30;
2456 if lRaise is true then
2457 perform fc_debug('mudando 1',lRaise,false,false);
2458 end if;
2459 elsif v_dia >= 30 and v_mesvenc in (2) then
2460 v_dia = 28;
2461 if lRaise is true then
2462 perform fc_debug('mudando 2',lRaise,false,false);
2463 end if;
2464 end if;
2465
2466 if lRaise is true then
2467 perform fc_debug('mesvenc: '||v_mesvenc||' - dia: '||v_dia,lRaise,false,false);
2468 end if;
2469
2470 -- calcula se vencimento e correto
2471 if v_mesvenc = 2 and v_dia >= 28 then
2472 if lRaise is true then
2473 perform fc_debug('fevereiro...',lRaise,false,false);
2474 end if;
2475 v_dia = v_ultdiafev;
2476 end if;
2477
2478 -- calcula vencimento
2479 execute 'truncate vcto';
2480 v_comando = 'insert into vcto select ' || '''' || to_char(v_anovenc,'99999') || '-' || trim(trim(to_char(v_mesvenc, '999'))) || '-' || trim(to_char(v_dia, '999')) || '''' || '::date';
2481 execute v_comando;
2482 select data from vcto into v_vcto;
2483 if lRaise is true then
2484 perform fc_debug(' fim vcto... '||v_vcto,lRaise,false,false);
2485 end if;
2486
2487 end if;
2488
2489 if lRaise is true then
2490 perform fc_debug(' inserindo em totrec a parcela '||v_record_recpar.parcela||' no valor de '||v_valparc,lRaise,false,false);
2491 end if;
2492
2493 -- insere na tabela totrec o registro atual com o valor da parcela
2494 execute 'insert into totrec values (' || v_record_recpar.receit || ', ' || v_record_recpar.parcela || ', ' || v_valparc || ')';
2495
2496 if lRaise is true then
2497 perform fc_debug('1 - parcela: '||v_record_recpar.parcela||' - valor: '||v_valparc,lRaise,false,false);
2498 end if;
2499
2500 if lRaise is true then
2501 perform fc_debug('k00_numcgm: '||v_cgmpri||' - k00_receit: '||v_record_recpar.receit||' - k00_hist: '||v_record_recpar.hist||' - k00_valor: '||v_valparc||' - k00_dtvenc: '||v_vcto||' - k00_numpre: '||v_numpre||' - k00_numpar: '||v_record_recpar.parcela||' - k00_numtot: '||v_totalparcelas||' - k00_tipo: '||v_tiponovo,lRaise,false,false);
2502 end if;
2503
2504 v_recdestino = v_record_recpar.receit;
2505
2506 if lRaise is true then
2507 perform fc_debug(' no arrecad... val: '||v_valparc||' - recdest: '||v_recdestino||' - vcto: '||v_vcto||' - parcela: '||v_record_recpar.parcela,lRaise,false,false);
2508 end if;
2509
2510 if v_valparc < 0 then
2511 return '[10] - valor da parcela ' || v_record_recpar.parcela || ' menor que zero: ' || v_valparc;
2512 elsif v_valparc = 0 then
2513 return '[11] - valor da parcela ' || v_record_recpar.parcela || ' zerada: ' || v_valparc;
2514 end if;
2515
2516 -- se valor da parcela maior que zero
2517 -- insere no arrecad
2518
2519 if lRaise is true then
2520 perform fc_debug('k00_numpre : '||v_numpre||' k00_numpar : '||v_record_recpar.parcela||' k00_receit : '||v_recdestino||' k00_valor : '||v_valparc,lRaise,false,false);
2521 end if;
2522
2523 lGravaArrecad = true;
2524
2525 if v_valparc > 0 then
2526
2527 if lSeparaJuroMulta = 1 then
2528
2529 if lRaise is true then
2530
2531 perform fc_debug('',lRaise,false,false);
2532 perform fc_debug('+--------------------------------------------------------------------------------------------',lRaise,false,false);
2533 perform fc_debug('| ',lRaise,false,false);
2534 perform fc_debug('| Processando dados da composicao do Numpre: '||v_numpre||' Parcela: '||v_record_recpar.parcela||' Receita: '||v_recdestino,lRaise,false,false);
2535 perform fc_debug('| ',lRaise,false,false);
2536 perform fc_debug('+--------------------------------------------------------------------------------------------',lRaise,false,false);
2537 perform fc_debug('',lRaise,false,false);
2538
2539 end if;
2540
2541
2542 iSeqArrecKey := nextval('arreckey_k00_sequencial_seq');
2543
2544 if lRaise is true then
2545 perform fc_debug(' ',lRaise,false,false);
2546 perform fc_debug(' 1. G E R A N D O D A D O S N A T A B E L A ARRECKEY P A R A A P A R C E L A: '||v_record_recpar.parcela,lRaise,false,false);
2547 perform fc_debug(' Sequencial: '||iSeqArrecKey||' Numpre: '||v_numpre||' Numpar: '||v_record_recpar.parcela||' Receita: '||v_recdestino||' Historico: '||v_record_recpar.hist||' Tipo: '||v_tiponovo,lRaise,false,false);
2548 perform fc_debug('',lRaise,false,false);
2549 end if;
2550
2551 insert into arreckey ( k00_sequencial,
2552 k00_numpre,
2553 k00_numpar,
2554 k00_receit,
2555 k00_hist,
2556 k00_tipo )
2557 values ( iSeqArrecKey,
2558 v_numpre,
2559 v_record_recpar.parcela,
2560 v_recdestino,
2561 v_record_recpar.hist,
2562 v_tiponovo
2563 );
2564
2565
2566 select round(sum(valhis),2),
2567 round(sum(valcor-descor-valhis),2),
2568 round(sum(valjur-descjur),2),
2569 round(sum(valmul-descmul),2)
2570 into nVlrTotalHistorico,
2571 nVlrTotalCorrecao,
2572 nVlrTotalJuros,
2573 nVlrTotalMulta
2574 from w_base_parcelas
2575 where receit = v_record_recpar.receit;
2576
2577 select round(sum(vlrdesccor),2),
2578 round(sum(vlrdescjur),2),
2579 round(sum(vlrdescmul),2)
2580 into nVlrTotalDescontoCorrigido,
2581 nVlrTotalDescontoJuros,
2582 nVlrTotalDescontoMulta
2583 from arrecad_parc_rec;
2584
2585 if lRaise is true then
2586 perform fc_debug(' ',lRaise,false,false);
2587 perform fc_debug(' 2. C A L C U L A N D O V A L O R E S D A C O M P O S I C A O D A P A R C E L A',lRaise,false,false);
2588 perform fc_debug(' ',lRaise,false,false);
2589 perform fc_debug(' Valores Totais do Debito: ',lRaise,false,false);
2590 perform fc_debug(' Total Historico(nVlrTotalHistorico) ..: '||nVlrTotalHistorico,lRaise,false,false);
2591 perform fc_debug(' Total Correcao(nVlrTotalCorrecao) ....: '||nVlrTotalCorrecao,lRaise,false,false);
2592 perform fc_debug(' Total Juros(nVlrTotalJuros) ..........: '||nVlrTotalJuros,lRaise,false,false);
2593 perform fc_debug(' Total Multa(nVlrTotalMulta) ..........: '||nVlrTotalMulta,lRaise,false,false);
2594 perform fc_debug(' v_somar(???): '||v_somar,lRaise,false,false);
2595 perform fc_debug(' ',lRaise,false,false);
2596 end if;
2597
2598 v_historico_compos = v_record_recpar.valhis;
2599 v_correcao_compos = ( v_record_recpar.valcor - v_record_recpar.descor - v_record_recpar.valhis );
2600 v_juros_compos = ( v_record_recpar.valjur - v_record_recpar.descjur );
2601 v_multa_compos = ( v_record_recpar.valmul - v_record_recpar.descmul );
2602
2603 if lRaise is true then
2604 perform fc_debug(' Parcela: '||v_record_recpar.parcela||' - Receita: '||v_record_recpar.receit,lRaise,false,false);
2605 perform fc_debug(' Valor da Parcela(v_valparc) ........................: '||v_valparc,lRaise,false,false);
2606 perform fc_debug(' Valor historico da Composicao(v_historico_compos) ..: '||v_historico_compos,lRaise,false,false);
2607 perform fc_debug(' Valor corrigido da Composicao(v_correcao_compos) ...: '||v_correcao_compos,lRaise,false,false);
2608 perform fc_debug(' Valor juros da Composicao(v_juros_compos) ..........: '||v_juros_compos,lRaise,false,false);
2609 perform fc_debug(' Valor multa da Composicao(v_multa_compos) ..........: '||v_multa_compos,lRaise,false,false);
2610 end if;
2611
2612 --
2613 --
2614 -- Caso seja a ultima parcela do parcelamento realizamos a verificação nos valores gerados para a composição das parcelas
2615 -- Se encontrar alguma diferenca é realizado o processamento do ajuste da composicao
2616 --
2617 if v_record_recpar.parcela = v_totparcdestarec then
2618
2619 if lRaise is true then
2620 perform fc_debug(' ',lRaise,false,false);
2621 perform fc_debug(' >> U L T I M A P A R C E L A D O P A R C E L A M E N T O <<',lRaise,false,false);
2622 perform fc_debug(' 2.1 VERIFICANDO E PROCESSANDO CORRECAO NAS DIFERENCAS DE VALORES(ARREDONDAMENTO) ',lRaise,false,false);
2623 perform fc_debug(' ',lRaise,false,false);
2624 end if;
2625
2626 --
2627 -- Verificamos os valores já gerados para a composicao do débito somando com o valor que será gerado para esta parcela e receita
2628 --
2629 select sum(k00_vlrhist)+v_historico_compos,
2630 sum(k00_correcao)+v_correcao_compos,
2631 sum(k00_juros)+v_juros_compos,
2632 sum(k00_multa)+v_multa_compos
2633 into nVlrHistoricoComposicao,
2634 nVlrCorrecaoComposicao,
2635 nVlrJurosComposicao,
2636 nVlrMultaComposicao
2637 from arrecadcompos
2638 inner join arreckey on arreckey.k00_sequencial = arrecadcompos.k00_arreckey
2639 where k00_numpre = v_numpre;
2640
2641 --
2642 -- Verificamos o total do valor de origem do parcelamento sem alterações e aplicações de regra.
2643 --
2644 select sum(k00_vlrhis),
2645 sum(k00_vlrcor-k00_vlrhis),
2646 sum(k00_juros),
2647 sum(k00_multa),
2648 sum(k00_desconto),
2649 sum(k00_total)
2650 into nVlrTotalParcelamentoHistorico,
2651 nVlrTotalParcelamentoCorrigido,
2652 nVlrTotalParcelamentoJuros,
2653 nVlrTotalParcelamentoMulta,
2654 nVlrTotalParcelamento
2655 from totalportipo;
2656
2657 --
2658 -- Calculamos os valores de composicao Total e Diferencas
2659 --
2660 nVlrTotalComposicao := (nVlrHistoricoComposicao+nVlrCorrecaoComposicao+nVlrJurosComposicao+nVlrMultaComposicao);
2661
2662 nVlrDiferencaComposicaoHistorico := nVlrTotalParcelamentoHistorico - nVlrHistoricoComposicao;
2663 nVlrDiferencaComposicaoCorrecao := nVlrTotalParcelamentoCorrigido - nVlrCorrecaoComposicao - nVlrTotalDescontoCorrigido;
2664 nVlrDiferencaComposicaoJuros := nVlrTotalParcelamentoJuros - nVlrJurosComposicao - nVlrTotalDescontoJuros;
2665 nVlrDiferencaComposicaoMulta := nVlrTotalParcelamentoMulta - nVlrMultaComposicao - nVlrTotalDescontoMulta;
2666
2667 nVlrDiferencaComposicaoTotal := round(abs(nVlrDiferencaComposicaoHistorico)+abs(nVlrDiferencaComposicaoCorrecao)+abs(nVlrDiferencaComposicaoJuros)+abs(nVlrDiferencaComposicaoMulta),2);
2668
2669 if lRaise is true then
2670 perform fc_debug(' Valores gerados no processamento da composicao: ',lRaise,false,false);
2671 perform fc_debug(' nVlrTotalHistorico ............: '||nVlrHistoricoComposicao,lRaise,false,false);
2672 perform fc_debug(' nVlrTotalCorrecao .............: '||nVlrCorrecaoComposicao,lRaise,false,false);
2673 perform fc_debug(' nVlrTotalJuros ................: '||nVlrJurosComposicao,lRaise,false,false);
2674 perform fc_debug(' nVlrTotalMulta ................: '||nVlrMultaComposicao,lRaise,false,false);
2675 perform fc_debug(' ---------------------------------------',lRaise,false,false);
2676 perform fc_debug(' Total da Composicao ..........: '||nVlrTotalComposicao,lRaise,false,false);
2677 perform fc_debug(' Total do Parcelamento ........: '||nVlrTotalParcelamento,lRaise,false,false);
2678 perform fc_debug(' ',lRaise,false,false);
2679 perform fc_debug(' Valores das diferencas encontradas: ',lRaise,false,false);
2680 perform fc_debug(' Diferenca no Vlr. Historico ..: '||nVlrDiferencaComposicaoHistorico,lRaise,false,false);
2681 perform fc_debug(' Diferenca no Vlr. Corrigido ..: '||nVlrDiferencaComposicaoCorrecao,lRaise,false,false);
2682 perform fc_debug(' Diferenca no Vlr. dos Juros ..: '||nVlrDiferencaComposicaoJuros,lRaise,false,false);
2683 perform fc_debug(' Diferenca no Vlr. da Multa ...: '||nVlrDiferencaComposicaoMulta,lRaise,false,false);
2684 perform fc_debug(' ---------------------------------------',lRaise,false,false);
2685 perform fc_debug(' Total da Diferenca (abs) .....: '||nVlrDiferencaComposicaoTotal,lRaise,false,false);
2686 end if;
2687
2688 --
2689 -- Caso seja encontrada diferenca na composicao do débito com o total parcelado
2690 -- Realizamos os ajustes necessarios nos valores onde existem diferenca, se o valor da diferenca existir e não for maior que 1.
2691 --
2692 if abs(nVlrDiferencaComposicaoTotal) between 0.01 and 1.00 then
2693
2694 if lRaise is true then
2695 perform fc_debug('',lRaise,false,false);
2696 perform fc_debug(' >> Processando acerto da diferenca da composicao <<',lRaise,false,false);
2697 end if;
2698
2699 if abs(nVlrDiferencaComposicaoHistorico) <> 0 then
2700
2701 if lRaise is true then
2702 perform fc_debug(' - Corrigindo diferenca no valor Historico de '||nVlrDiferencaComposicaoHistorico,lRaise,false,false);
2703 end if;
2704 v_historico_compos := v_historico_compos+nVlrDiferencaComposicaoHistorico;
2705 end if;
2706
2707 if abs(nVlrDiferencaComposicaoCorrecao) <> 0 then
2708
2709 if lRaise is true then
2710 perform fc_debug(' - Corrigindo diferenca no valor Corrigido de '||nVlrDiferencaComposicaoCorrecao,lRaise,false,false);
2711 end if;
2712 v_correcao_compos := v_correcao_compos+nVlrDiferencaComposicaoCorrecao;
2713 end if;
2714
2715 if abs(nVlrDiferencaComposicaoJuros) <> 0 then
2716
2717 if lRaise is true then
2718 perform fc_debug(' - Corrigindo diferenca no valor dos Juros de '||nVlrDiferencaComposicaoJuros,lRaise,false,false);
2719 end if;
2720 v_juros_compos := v_juros_compos+nVlrDiferencaComposicaoJuros;
2721
2722 end if;
2723
2724 if abs(nVlrDiferencaComposicaoMulta) <> 0 then
2725
2726 if lRaise is true then
2727 perform fc_debug(' - Corrigindo diferenca no valor da Multa de '||nVlrDiferencaComposicaoMulta,lRaise,false,false);
2728 end if;
2729 v_multa_compos := v_multa_compos+nVlrDiferencaComposicaoMulta;
2730
2731 end if;
2732
2733 --
2734 --
2735 -- Se a variável de sessão db_debugon estiver setada, verificamos os valores finais gerados para a composição do débito
2736 -- Essa verificação é realizada buscando os valores já gerados somando com o valor da receita que será cadastrado já com
2737 -- os ajustes de valores.
2738 --
2739 if lRaise is true then
2740
2741 select sum(k00_vlrhist) + v_historico_compos,
2742 sum(k00_correcao) + v_correcao_compos,
2743 sum(k00_juros) + v_juros_compos,
2744 sum(k00_multa) + v_multa_compos
2745 into nVlrHistoricoComposicao,
2746 nVlrCorrecaoComposicao,
2747 nVlrJurosComposicao,
2748 nVlrMultaComposicao
2749 from arrecadcompos
2750 inner join arreckey on arreckey.k00_sequencial = arrecadcompos.k00_arreckey
2751 where k00_numpre = v_numpre;
2752
2753 nVlrTotalComposicao := (nVlrHistoricoComposicao+nVlrCorrecaoComposicao+nVlrJurosComposicao+nVlrMultaComposicao);
2754
2755 nVlrDiferencaComposicaoHistorico := nVlrTotalParcelamentoHistorico - nVlrHistoricoComposicao;
2756 nVlrDiferencaComposicaoCorrecao := nVlrTotalParcelamentoCorrigido - nVlrCorrecaoComposicao - nVlrTotalDescontoCorrigido;
2757 nVlrDiferencaComposicaoJuros := nVlrTotalParcelamentoJuros - nVlrJurosComposicao - nVlrTotalDescontoJuros;
2758 nVlrDiferencaComposicaoMulta := nVlrTotalParcelamentoMulta - nVlrMultaComposicao - nVlrTotalDescontoMulta;
2759
2760 nVlrDiferencaComposicaoTotal := round(abs(nVlrDiferencaComposicaoHistorico)+abs(nVlrDiferencaComposicaoCorrecao)+abs(nVlrDiferencaComposicaoJuros)+abs(nVlrDiferencaComposicaoMulta),2);
2761
2762 perform fc_debug(' Valores gerados no processamento da composicao apos o acerto das diferencas: ',lRaise,false,false);
2763 perform fc_debug(' nVlrTotalHistorico ............: '||nVlrHistoricoComposicao,lRaise,false,false);
2764 perform fc_debug(' nVlrTotalCorrecao .............: '||nVlrCorrecaoComposicao,lRaise,false,false);
2765 perform fc_debug(' nVlrTotalJuros ................: '||nVlrJurosComposicao,lRaise,false,false);
2766 perform fc_debug(' nVlrTotalMulta ................: '||nVlrMultaComposicao,lRaise,false,false);
2767 perform fc_debug(' ---------------------------------------',lRaise,false,false);
2768 perform fc_debug(' Total da Composicao ..........: '||nVlrTotalComposicao,lRaise,false,false);
2769 perform fc_debug(' Total do Parcelamento ........: '||nVlrTotalParcelamento,lRaise,false,false);
2770 perform fc_debug(' ',lRaise,false,false);
2771 perform fc_debug(' Valores das diferencas encontradas: ',lRaise,false,false);
2772 perform fc_debug(' Diferenca no Vlr. Historico ..: '||nVlrDiferencaComposicaoHistorico,lRaise,false,false);
2773 perform fc_debug(' Diferenca no Vlr. Corrigido ..: '||nVlrDiferencaComposicaoCorrecao,lRaise,false,false);
2774 perform fc_debug(' Diferenca no Vlr. dos Juros ..: '||nVlrDiferencaComposicaoJuros,lRaise,false,false);
2775 perform fc_debug(' Diferenca no Vlr. da Multa ...: '||nVlrDiferencaComposicaoMulta,lRaise,false,false);
2776 perform fc_debug(' ---------------------------------------',lRaise,false,false);
2777 perform fc_debug(' Total da Diferenca (abs) .....: '||nVlrDiferencaComposicaoTotal,lRaise,false,false);
2778
2779 end if;
2780
2781 end if;
2782
2783 end if;
2784
2785 iSeqArrecadcompos := nextval('arrecadcompos_k00_sequencial_seq');
2786 insert into arrecadcompos ( k00_sequencial,
2787 k00_arreckey,
2788 k00_vlrhist,
2789 k00_correcao,
2790 k00_juros,
2791 k00_multa )
2792 values ( iSeqArrecadcompos,
2793 iSeqArrecKey,
2794 v_historico_compos,
2795 v_correcao_compos,
2796 v_juros_compos,
2797 v_multa_compos );
2798
2799 if lRaise is true then
2800
2801 perform fc_debug('',lRaise,false,false);
2802 perform fc_debug(' 3. I N S E R I N D O R E G I S T R O S D E C O M P O S I C A O (ArrecadCompos)',lRaise,false,false);
2803 perform fc_debug(' Cod. Arreckey(k00_arreckey): '||iSeqArrecKey||' Numpre: '||v_numpre||' Parcela: '||v_record_recpar.parcela||' Receita: '||v_recdestino,lRaise,false,false);
2804 perform fc_debug('',lRaise,false,false);
2805
2806 end if;
2807
2808 if v_historico_compos = 0 and v_correcao_compos = 0 and v_juros_compos = 0 and v_multa_compos = 0 then
2809 v_valparc = 0;
2810 lGravaArrecad = false;
2811 else
2812 v_valparc = round(v_historico_compos,2);
2813 end if;
2814
2815 if lRaise is true then
2816
2817 perform fc_debug('',lRaise,false,false);
2818 perform fc_debug('+--------------------------------------------------------------------------------------------',lRaise,false,false);
2819 perform fc_debug('| ',lRaise,false,false);
2820 perform fc_debug('| Fim do processamento da composicao do Numpre: '||v_numpre||' Parcela: '||v_record_recpar.parcela||' Receita: '||v_recdestino,lRaise,false,false);
2821 perform fc_debug('| ',lRaise,false,false);
2822 perform fc_debug('+--------------------------------------------------------------------------------------------',lRaise,false,false);
2823 perform fc_debug('',lRaise,false,false);
2824
2825 end if;
2826
2827 end if;
2828
2829 if lRaise is true then
2830 perform fc_debug(' ',lRaise,false,false);
2831 perform fc_debug('Inserindo dados da parcela no Arrecad',lRaise,false,false);
2832 perform fc_debug('Numpre: '||v_numpre||' Numpar: '||v_record_recpar.parcela||' Receita: '||v_recdestino||' Valor: '||v_valparc||' - Round: '||round(v_valparc,2),lRaise,false,false);
2833 perform fc_debug(' ',lRaise,false,false);
2834 end if;
2835
2836 if lSeparaJuroMulta = 2 then
2837
2838 if (round(v_valparc,2) <= 0 or v_valparc is null) then
2839 return '[12] - valor da parcela ' || trim(to_char(v_record_recpar.parcela, '999')) || ' zerada ou em branco! Contate suporte';
2840 end if;
2841
2842 end if;
2843
2844 if lGravaArrecad is true then
2845
2846 insert into arrecad (k00_numcgm,
2847 k00_dtoper,
2848 k00_receit,
2849 k00_hist,
2850 k00_valor,
2851 k00_dtvenc,
2852 k00_numpre,
2853 k00_numpar,
2854 k00_numtot,
2855 k00_numdig,
2856 k00_tipo,
2857 k00_tipojm)
2858 values (v_cgmpri,
2859 dDataUsu,
2860 v_recdestino,
2861 v_record_recpar.hist,
2862 round(v_valparc,2),
2863 v_vcto,
2864 v_numpre,
2865 v_record_recpar.parcela,
2866 v_totalparcelas,
2867 0,
2868 v_tiponovo,
2869 0);
2870
2871 select k00_valor
2872 into v_teste
2873 from arrecad
2874 where k00_numpre = v_numpre
2875 and k00_numpar = v_record_recpar.parcela
2876 and k00_receit = v_recdestino;
2877
2878 if lRaise is true then
2879 perform fc_debug('Dados inseridos na Arrecad: Valor: '||v_valparc||' - Round: '||round(v_valparc,2)||' - Teste(Valor inserido no Arrecad): '||v_teste,lRaise,false,false);
2880 end if;
2881
2882 end if;
2883
2884 if lRaise is true then
2885 perform fc_debug(' ',lRaise,false,false);
2886 perform fc_debug(' ',lRaise,false,false);
2887 end if;
2888
2889 else
2890 perform fc_debug('Valor da parcela(v_valparc) menor ou igual a zero: '||v_valparc,lRaise,false,false);
2891 end if;
2892
2893 if lRaise is true then
2894 perform fc_debug('Receita Origem: '||v_record_recpar.receit||' - Receita Destino: '||v_recdestino,lRaise,false,false);
2895 perform fc_debug('Receita: '||v_record_recpar.receit||' - Qtd Total de Parcelas da Receita: '||v_totparcdestarec,lRaise,false,false);
2896 end if;
2897
2898 -- conta a quantidade total de parcelas desta receita
2899 select count(*)
2900 into v_totparcdestarec
2901 from parcelas
2902 where receit = v_record_recpar.receit;
2903
2904 if lRaise is true then
2905 perform fc_debug('Receita: '||v_record_recpar.receit||' - Qtd Total de Parcelas da Receita: '||v_totparcdestarec,lRaise,false,false);
2906 end if;
2907
2908 --
2909 -- Se parcela atual for igual a ultima parcela desta receita
2910 -- reinicia as variaveis com os dados especificados na CGF para o vencimento da parcela 2
2911 --
2912 if v_record_recpar.parcela = v_totparcdestarec then
2913
2914 select extract (year from v_segvenc)
2915 into v_anovenc;
2916
2917 select extract (month from v_segvenc)
2918 into v_mesvenc;
2919
2920 end if;
2921
2922 end loop;
2923
2924 if lRaise is true then
2925 perform fc_debug(' ',lRaise,false,false);
2926 perform fc_debug(' ',lRaise,false,false);
2927 perform fc_debug(' ',lRaise,false,false);
2928 perform fc_debug(' ',lRaise,false,false);
2929 perform fc_debug(' ',lRaise,false,false);
2930 end if;
2931
2932 if lRaise is true then
2933
2934 -- mostra os valores por parcela do arrecad, apenas para conferencia
2935 for v_record_recpar in select k00_numpar,
2936 sum(k00_valor)
2937 from arrecad
2938 where k00_numpre = v_numpre
2939 group by k00_numpar
2940 loop
2941
2942 if lRaise is true then
2943 perform fc_debug('2 - parcela: '||v_record_recpar.k00_numpar||' - valor: '||v_record_recpar.sum,lRaise,false,false);
2944 end if;
2945
2946 end loop;
2947
2948 end if;
2949
2950 -- sum do campo valor
2951 select sum(valor)
2952 into nValorTotalOrigem
2953 from w_base_parcelas;
2954
2955 for rPercOrigem in select numpre,
2956 numpar,
2957 receit,
2958 sum(valor) as valor
2959 from arrecad_parc_rec
2960 group by numpre, numpar, receit
2961 loop
2962
2963 nPercCalc := ( ( rPercOrigem.valor / nValorTotalOrigem ) * 100 );
2964
2965 --raise notice 'valor: % - nValorTotalOrigem: % - PercCalcComRound: %', rPercOrigem.valor, nValorTotalOrigem, nPercCalc ;
2966
2967 perform sum(k00_perc)
2968 from ( select k00_matric as k00_origem,
2969 coalesce(k00_perc, 100) as k00_perc,
2970 1 as tipo
2971 from arrematric
2972 where k00_numpre = rPercOrigem.numpre
2973 union
2974 select k00_inscr as k00_origem,
2975 coalesce(k00_perc, 100) as k00_perc,
2976 2 as tipo
2977 from arreinscr
2978 where k00_numpre = rPercOrigem.numpre
2979 union
2980 select 0 as k00_origem,
2981 100 as k00_perc,
2982 3 as tipo
2983 from arrenumcgm
2984 left join arrematric on arrematric.k00_numpre = arrenumcgm.k00_numpre
2985 left join arreinscr on arreinscr.k00_numpre = arrenumcgm.k00_numpre
2986 where arrematric.k00_numpre is null
2987 and arreinscr.k00_numpre is null
2988 and arrenumcgm.k00_numpre = rPercOrigem.numpre
2989 ) as x
2990 having cast(round(sum(k00_perc),2) as numeric) <> cast(100 as numeric);
2991 if found then
2992 return '[13] - Inconsistencia no percentual da origem - numpre: ' || rPercOrigem.numpre;
2993 end if;
2994
2995 for v_record_perc in select k00_matric as k00_origem,
2996 coalesce(k00_perc, 100) as k00_perc,
2997 1 as tipo
2998 from arrematric
2999 where k00_numpre = rPercOrigem.numpre
3000 union
3001 select k00_inscr as k00_origem,
3002 coalesce(k00_perc, 100) as k00_perc,
3003 2 as tipo
3004 from arreinscr
3005 where k00_numpre = rPercOrigem.numpre
3006 union
3007 select 0 as k00_origem,
3008 100 as k00_perc,
3009 3 as tipo
3010 from arrenumcgm
3011 left join arrematric on arrematric.k00_numpre = arrenumcgm.k00_numpre
3012 left join arreinscr on arreinscr.k00_numpre = arrenumcgm.k00_numpre
3013 where arrematric.k00_numpre is null
3014 and arreinscr.k00_numpre is null
3015 and arrenumcgm.k00_numpre = rPercOrigem.numpre
3016 loop
3017
3018 if lRaise then
3019 perform fc_debug('---------------------------------------------------------------',lRaise,false,false);
3020 perform fc_debug('numpre: '||rPercOrigem.numpre||' - perc: '||v_record_perc.k00_perc||' - tipo: '||v_record_perc.tipo||' - percentual por registro: '||nPercCalc,lRaise,false,false);
3021 perform fc_debug('---------------------------------------------------------------',lRaise,false,false);
3022 end if;
3023
3024 if v_record_perc.tipo = 1 then
3025
3026 execute 'insert into arrecad_parc_rec_perc values ('|| rPercOrigem.numpre || ','
3027 || rPercOrigem.numpar || ','
3028 || rPercOrigem.receit || ','
3029 || v_record_perc.k00_origem || ','
3030 || nPercCalc * v_record_perc.k00_perc / 100 || ','
3031 || 0 || ','
3032 || 0 || ','
3033 || 0 || ','
3034 || v_record_perc.tipo || ');';
3035 elsif v_record_perc.tipo = 2 then
3036
3037 execute 'insert into arrecad_parc_rec_perc values (' || rPercOrigem.numpre || ','
3038 || rPercOrigem.numpar || ','
3039 || rPercOrigem.receit || ','
3040 || 0 || ','
3041 || 0 || ','
3042 || v_record_perc.k00_origem || ','
3043 || nPercCalc * v_record_perc.k00_perc / 100 || ','
3044 || 0 || ','
3045 || v_record_perc.tipo || ');';
3046
3047 elsif v_record_perc.tipo = 3 then
3048
3049 execute 'insert into arrecad_parc_rec_perc values (' || rPercOrigem.numpre || ','
3050 || rPercOrigem.numpar || ','
3051 || rPercOrigem.receit || ','
3052 || 0 || ','
3053 || 0 || ','
3054 || 0 || ','
3055 || 0 || ','
3056 || nPercCalc * v_record_perc.k00_perc / 100 || ','
3057 || v_record_perc.tipo || ');';
3058 end if;
3059
3060 end loop;
3061
3062 end loop;
3063
3064 /**
3065 * Somamos o percentual virtual do cgm para distribui-lo entre as origens (Matricula e Inscricao)
3066 */
3067 select coalesce(sum(perccgm), 0)
3068 into nPercentualVirtualCgm
3069 from arrecad_parc_rec_perc
3070 where percmatric = 0
3071 and percinscr = 0;
3072
3073 select count(*)
3074 into iQtdRegistrosMatricula
3075 from arrecad_parc_rec_perc
3076 where tipo = 1;
3077
3078 select count(*)
3079 into iQtdRegistrosInscricao
3080 from arrecad_parc_rec_perc
3081 where tipo = 2;
3082
3083
3084 if ( ((iQtdRegistrosMatricula + iQtdRegistrosInscricao) > 0) and (nPercentualVirtualCgm > 0) ) then
3085
3086 nDiferencaPercentualCGM = coalesce((nPercentualVirtualCgm / (iQtdRegistrosMatricula + iQtdRegistrosInscricao)), 0);
3087
3088 if lRaise then
3089 perform fc_debug('nDiferencaPercentualCGM' || nDiferencaPercentualCGM, lRaise, false, false);
3090 end if;
3091
3092 update arrecad_parc_rec_perc
3093 set percmatric = percmatric + nDiferencaPercentualCGM
3094 where tipo = 1 ;
3095
3096 update arrecad_parc_rec_perc
3097 set percinscr = percinscr + nDiferencaPercentualCGM
3098 where tipo = 2 ;
3099
3100 update arrecad_parc_rec_perc
3101 set perccgm = 0
3102 where tipo = 3;
3103
3104 end if;
3105
3106
3107 /**
3108 * Calculamos a diferenca no valor percentual entre o somatorio de todas as origens (Matricula e Inscricao)
3109 */
3110 select 100 - (sum(percmatric) + sum(percinscr))
3111 into nDiferencaPercentualAjuste
3112 from arrecad_parc_rec_perc
3113 where tipo in (1, 2);
3114
3115 /**
3116 * Se existir diferenca no percentual
3117 * Ajustamos a diferenca no arredondamento no primeiro registro encontrado
3118 */
3119 if nDiferencaPercentualAjuste <> cast(0 as numeric(15, 10)) then
3120
3121 if lRaise then
3122 perform fc_debug('---------------------------------------------------------------',lRaise,false,false);
3123 perform fc_debug('Valor da diferenca de arredondamento: '||nDiferencaPercentualAjuste,lRaise,false,false);
3124 perform fc_debug('---------------------------------------------------------------',lRaise,false,false);
3125 end if;
3126
3127 for rAjusteDiferencaPercentual in select *
3128 from arrecad_parc_rec_perc
3129 where tipo <> 3
3130 limit 1
3131 loop
3132
3133 if rAjusteDiferencaPercentual.tipo = 1 then
3134
3135 update arrecad_parc_rec_perc
3136 set percmatric = percmatric + (select 100 - (sum(percmatric) + sum(percinscr))
3137 from arrecad_parc_rec_perc
3138 where tipo in (1, 2))
3139 where numpre = rAjusteDiferencaPercentual.numpre
3140 and numpar = rAjusteDiferencaPercentual.numpar
3141 and receit = rAjusteDiferencaPercentual.receit
3142 and matric = rAjusteDiferencaPercentual.matric;
3143
3144 elsif rAjusteDiferencaPercentual.tipo = 2 then
3145
3146 update arrecad_parc_rec_perc
3147 set percinscr = percinscr + (select 100 - (sum(percmatric) + sum(percinscr))
3148 from arrecad_parc_rec_perc
3149 where tipo in (1, 2))
3150 where numpre = rAjusteDiferencaPercentual.numpre
3151 and numpar = rAjusteDiferencaPercentual.numpar
3152 and receit = rAjusteDiferencaPercentual.receit
3153 and inscr = rAjusteDiferencaPercentual.inscr;
3154 end if;
3155
3156 end loop;
3157
3158 end if;
3159
3160 nSomaPercMatric = 0;
3161 nTotArreMatric = 0;
3162
3163 select sum(percmatric)
3164 into nTotArreMatric
3165 from arrecad_parc_rec_perc;
3166
3167 for rPercOrigem in select matric,
3168 sum(percmatric) as k00_perc,
3169 tipo
3170 from arrecad_parc_rec_perc
3171 where matric > 0
3172 group by matric,tipo
3173 loop
3174
3175 if lRaise then
3176 perform fc_debug('---------------------------------------------------------------',lRaise,false,false);
3177 perform fc_debug('matric: '||rPercOrigem.matric||' - perc: '||rPercOrigem.k00_perc||' numpre : '||v_numpre ,lRaise,false,false);
3178 perform fc_debug('---------------------------------------------------------------',lRaise,false,false);
3179 end if;
3180
3181 -- tipo = 3 quer dizer que nao tem origem de matricula ou inscricao
3182 -- (o numpre origem esta somente na arrenumcgm ou seja nao precisa gravar percentual na arrematric ou arreinscr)
3183 if rPercOrigem.tipo <> 3 then
3184 insert into arrematric (k00_matric,
3185 k00_numpre,
3186 k00_perc)
3187 values (rPercOrigem.matric,
3188 v_numpre,
3189 rPercOrigem.k00_perc);
3190 end if;
3191
3192 v_totalzao := v_totalzao + rPercOrigem.k00_perc;
3193 nSomaPercMatric := nSomaPercMatric + rPercOrigem.k00_perc;
3194
3195 end loop;
3196
3197 if lRaise then
3198 perform fc_debug('v_totalzao (1): '||v_totalzao,lRaise,false,false);
3199 end if;
3200
3201 nSomaPercInscr = 0;
3202 nTotArreInscr = 0;
3203
3204 select sum(percinscr)
3205 into nTotArreInscr
3206 from arrecad_parc_rec_perc;
3207
3208 for rPercOrigem in select inscr,
3209 sum(percinscr) as k00_perc,
3210 tipo
3211 from arrecad_parc_rec_perc
3212 where inscr > 0
3213 group by inscr,tipo
3214 loop
3215
3216 if lRaise then
3217 raise info 'inscr: % - perc: % numpre : % ',rPercOrigem.inscr, rPercOrigem.k00_perc, v_numpre;
3218 end if;
3219
3220 if lRaise then
3221 perform fc_debug('---------------------------------------------------------------',lRaise,false,false);
3222 perform fc_debug('inscr: '||rPercOrigem.inscr||' - perc: '||rPercOrigem.k00_perc||' numpre : '||v_numpre,lRaise,false,false);
3223 perform fc_debug('---------------------------------------------------------------',lRaise,false,false);
3224 end if;
3225
3226 -- tipo = 3 quer dizer que nao tem origem de matricula ou inscricao
3227 -- (o numpre origem esta somente na arrenumcgm ou seja nao precisa gravar percentual na arrematric ou arreinscr)
3228 if rPercOrigem.tipo <> 3 then
3229 insert into arreinscr (k00_inscr,
3230 k00_numpre,
3231 k00_perc)
3232 values (rPercOrigem.inscr,
3233 v_numpre,
3234 rPercOrigem.k00_perc);
3235 end if;
3236
3237 v_totalzao := v_totalzao + rPercOrigem.k00_perc;
3238 nSomaPercInscr := nSomaPercInscr + rPercOrigem.k00_perc;
3239
3240 end loop;
3241
3242 if lRaise then
3243 perform fc_debug('v_totalzao (2): '||v_totalzao,lRaise,false,false);
3244 perform fc_debug('nTotArreInscr : '|| nTotArreInscr || 'nSomaPercInscr : ' || nSomaPercInscr || 'TOTAL: ' ||(nTotArreInscr-nSomaPercInscr) );
3245 end if;
3246
3247 if lRaise then
3248 perform fc_debug('v_totalzao (3): '||v_totalzao,lRaise,false,false);
3249 end if;
3250
3251 for rPercOrigem in select numpre,
3252 sum(perccgm) as k00_perc
3253 from arrecad_parc_rec_perc
3254 where tipo = 3
3255 group by numpre
3256 loop
3257
3258 if lRaise then
3259 perform fc_debug('---------------------------------------------------------------',lRaise,false,false);
3260 perform fc_debug(' por cgm -- numpre -- '||rPercOrigem.k00_perc||' percentual -- '||rPercOrigem.numpre,lRaise,false,false);
3261 perform fc_debug('---------------------------------------------------------------',lRaise,false,false);
3262 end if;
3263
3264 v_totalzao := v_totalzao + rPercOrigem.k00_perc;
3265
3266 end loop;
3267
3268 -- Corrige arredondamentos
3269 nPercCalc = 100.00 - v_totalzao;
3270 if nPercCalc < 0.5 then
3271
3272 --
3273 -- Jogamos a diferença do percentual na Arreinscr quando:
3274 -- - Não existir vinculo com matricula
3275 -- - O percentual da inscrição for menor que o percentual da matricula
3276 --
3277 -- Jogamos a difença do percentual na Arrematric quando:
3278 -- - Não existir vinculo com a inscrição
3279 -- - O Percentual da matricula for menor que o percentual da inscrição
3280 --
3281 if lRaise then
3282 perform fc_debug('nPercCalc < 0.5 --------------------- nSomaPercInscr ...: '||nSomaPercInscr ,lRaise,false,false);
3283 perform fc_debug('nPercCalc < 0.5 --------------------- nSomaPercMatric...: '||nSomaPercMatric,lRaise,false,false);
3284 perform fc_debug('nPercCalc < 0.5 --------------------- nPercCalc.........: '||nPercCalc ,lRaise,false,false);
3285 perform fc_debug('nPercCalc < 0.5 --------------------- v_totalzao........: '||v_totalzao ,lRaise,false,false);
3286 end if;
3287
3288 v_totalzao := v_totalzao + nPercCalc;
3289 if lRaise then
3290 perform fc_debug('v_totalzao (4): '||v_totalzao,lRaise,false,false);
3291 end if;
3292
3293 end if;
3294
3295 -- soma os percentuais da arrematric e arreinscr... nao esquecendo de que pode NAO ter registros em nenhuma das duas tabelas
3296
3297 if lRaise is true then
3298 perform fc_debug(' Apos nPercCalc < 0.5 ---- total utilizado na comparacao final: '||v_total,lRaise,false,false);
3299 perform fc_debug(' Apos nPercCalc < 0.5 ---- totalzao ..........................: '||v_totalzao,lRaise,false,false);
3300 end if;
3301
3302 if round(v_totalzao, 2)::numeric <> 100::numeric and round(v_totalzao, 2)::numeric <> 0::numeric then
3303 return '[14] - Erro calculando percentual entre as origens devedoras';
3304 end if;
3305
3306 if lRaise is true then
3307 perform fc_debug('',lRaise,false,false);
3308 perform fc_debug(' Verificando percentuais na arrematric, arreinscr e arrenumcgm gerados para o numpre '||v_numpre,lRaise,false,false);
3309 perform fc_debug('',lRaise,false,false);
3310 end if;
3311
3312
3313 select sum(k00_perc)
3314 into nValidacaoPerc
3315
3316 from ( select k00_matric as k00_origem,
3317 coalesce(k00_perc, 100) as k00_perc,
3318 1 as tipo
3319 from arrematric
3320 where k00_numpre = v_numpre
3321 union
3322 select k00_inscr as k00_origem,
3323 coalesce(k00_perc, 100) as k00_perc,
3324 2 as tipo
3325 from arreinscr
3326 where k00_numpre = v_numpre
3327 union
3328 select 0 as k00_origem,
3329 100 as k00_perc,
3330 3 as tipo
3331 from arrenumcgm
3332 left join arrematric on arrematric.k00_numpre = arrenumcgm.k00_numpre
3333 left join arreinscr on arreinscr.k00_numpre = arrenumcgm.k00_numpre
3334 where arrematric.k00_numpre is null
3335 and arreinscr.k00_numpre is null
3336 and arrenumcgm.k00_numpre = v_numpre
3337 ) as x;
3338
3339 --having cast(round(nValidacaoPerc +nPercentualVirtualCgm,2) as numeric) <> cast(100.00 as numeric);
3340 --raise notice 'nValidacaoPerc : % nPercentualVirtualCgm : % ',nValidacaoPerc,nPercentualVirtualCgm;
3341
3342 --nValidacaoPerc := nValidacaoPerc + nPercentualVirtualCgm;
3343 nValidacaoPerc := nValidacaoPerc;
3344
3345 perform fc_debug('----nValidacaoPerc : ' || nValidacaoPerc);
3346 perform fc_debug('----nPercentualVirtualCgm : ' || nPercentualVirtualCgm);
3347 perform fc_debug('----v_totalzao : ' || v_totalzao);
3348
3349 -- return 'final percentual 2';
3350 if round(nValidacaoPerc, 2) <> 100.00 then
3351
3352 --return 'final : perc : '||round(nValidacaoPerc,2)||' numpre : '||v_numpre;
3353
3354 --
3355 -- Verificamos se o problema é devido estar no parcelamento débitos que pertencem a matricula/inscrição e débitos sem vinculo com matricula/inscricao
3356 -- Se for encontrado um numpre que não esteja vinculado a matricula e a inscrição na origem, mostramos uma mensagem de erro diferenciada para facilitar a
3357 -- correção do caso. Geralmente a correção é realizada vinculando o numpre a uma matricula ou inscrição.
3358 --
3359 select array_to_string(array_accum( distinct arrecad_parc_rec.numpre),',')
3360 into sNumpreSemVinculoMatricInsc
3361 from arrecad_parc_rec
3362 left join arrematric on arrematric.k00_numpre = arrecad_parc_rec.numpre
3363 left join arreinscr on arreinscr.k00_numpre = arrecad_parc_rec.numpre
3364 where arrematric.k00_numpre is null
3365 and arreinscr.k00_numpre is null;
3366 if sNumpreSemVinculoMatricInsc <> '' then
3367 return '[15] - Inconsistencia no percentual do débito gerado após o processamento do parcelamento - numpre: '||v_numpre||'. - Encontrados numpres que não possuem vinculo com Matricula/Inscrição. Numpres ['||sNumpreSemVinculoMatricInsc||']';
3368 else
3369 return '[15] - Inconsistencia no percentual do débito gerado após o processamento do parcelamento - numpre: '||v_numpre;
3370 end if;
3371
3372 end if;
3373
3374 if lRaise is true then
3375 perform fc_debug('',lRaise,false,false);
3376 end if;
3377
3378 -- insere registros na arreparc
3379 -- agrupados por receita
3380 for v_record_receitas in select receit,
3381 sum(vlrhis) as vlrhis,
3382 sum(vlrcor) as vlrcor,
3383 sum(vlrjur) as vlrjur,
3384 sum(vlrmul) as vlrmul,
3385 sum(vlrdes) as vlrdes,
3386 sum(valor) as valor
3387 from arrecad_parc_rec
3388 group by receit
3389 loop
3390
3391 if lRaise is true then
3392 perform fc_debug('receita: '||v_record_receitas.receit||' - valor: '||v_record_receitas.valor, lRaise,false,false);
3393 end if;
3394
3395 insert into arreparc values (v_numpre,v_record_receitas.receit,v_record_receitas.valor / v_total * 100);
3396
3397 nVlrHis := nVlrHis + v_record_receitas.vlrhis;
3398 nVlrCor := nVlrCor + v_record_receitas.vlrcor;
3399 nVlrJur := nVlrJur + v_record_receitas.vlrjur;
3400 nVlrMul := nVlrMul + v_record_receitas.vlrmul;
3401 nVlrDes := nVlrDes + v_record_receitas.vlrdes;
3402
3403 end loop;
3404
3405 if lRaise is true then
3406 perform fc_debug('',lRaise,false,false);
3407 end if;
3408
3409 -- insere na termo
3410 insert into termo ( v07_parcel,
3411 v07_dtlanc,
3412 v07_valor,
3413 v07_numpre,
3414 v07_totpar,
3415 v07_vlrpar,
3416 v07_dtvenc,
3417 v07_vlrent,
3418 v07_datpri,
3419 v07_vlrmul,
3420 v07_vlrjur,
3421 v07_perjur,
3422 v07_permul,
3423 v07_login,
3424 v07_numcgm,
3425 v07_hist,
3426 v07_ultpar,
3427 v07_desconto,
3428 v07_desccor,
3429 v07_descjur,
3430 v07_descmul,
3431 v07_situacao,
3432 v07_instit,
3433 v07_vlrhis,
3434 v07_vlrcor,
3435 v07_vlrdes )
3436 values ( v_termo,
3437 dDataUsu,
3438 v_total,
3439 v_numpre,
3440 v_totalparcelas,
3441 v_valorparcelanew,
3442 v_segvenc,
3443 v_entrada,
3444 v_privenc,
3445 nVlrMul,
3446 nVlrJur,
3447 0,
3448 0,
3449 v_login,
3450 v_cgmresp,
3451 sObservacao,
3452 v_valultimaparcelanew,
3453 v_desconto,
3454 v_descontocor,
3455 v_descontojur,
3456 v_descontomul,
3457 1, -- Situacao Ativo
3458 iInstit,
3459 nVlrHis,
3460 nVlrCor,
3461 nVlrDes );
3462
3463 -- se foi informado codigo do processo entao insere na termoprotprocesso
3464 if iProcesso is not null and iProcesso != 0 then
3465
3466 if lRaise is true then
3467 perform fc_debug(' Insere na protprocesso Processo : '||iProcesso,lRaise,false,false);
3468 end if;
3469
3470 insert into termoprotprocesso (v27_sequencial,
3471 v27_termo,
3472 v27_protprocesso)
3473 values (nextval('termoprotprocesso_v27_sequencial_seq'),
3474 v_termo,
3475 iProcesso);
3476 end if;
3477
3478 -- se origem tiver parcelamento
3479 -- insere na termoreparc
3480 if lParcParc then
3481 if lRaise is true then
3482 perform fc_debug('v08_parcel: '||v_termo||' - v08_parcelorigem: '||v_termo_ori,lRaise,false,false);
3483 end if;
3484
3485 for v_record_origem in select distinct v07_parcel
3486 from termo
3487 inner join numpres_parc on termo.v07_numpre = numpres_parc.k00_numpre
3488 loop
3489
3490 if lRaise is true then
3491 perform fc_debug('into termoreparc...',lRaise,false,false);
3492 end if;
3493
3494 insert into termoreparc (v08_sequencial,
3495 v08_parcel,
3496 v08_parcelorigem)
3497 values (nextval('termoreparc_v08_sequencial_seq'),
3498 v_termo,
3499 v_record_origem.v07_parcel);
3500
3501 end loop;
3502
3503 end if;
3504
3505 if lRaise is true then
3506 perform fc_debug('v_totaldivida: '||v_totaldivida,lRaise,false,false);
3507 end if;
3508
3509 /**
3510 * Deve ignorar a receita de juros e multa quando a forma utilizada no parcelamento
3511 * é juros e multa na ultima
3512 * retirado arredondamentos para reconstruir a termo div com os debitos tal qual estavam anteriormente
3513 */
3514 -- insere na termodiv (obs o select da arrecad_parc_rec da um inner join com a divida so para inserir na termodiv quando a origem for divida)
3515 if v_juronaultima is true then
3516
3517 insert into termodiv (parcel,
3518 coddiv,
3519 valor,
3520 vlrcor,
3521 juros,
3522 multa,
3523 desconto,
3524 total,
3525 vlrdesccor,
3526 vlrdescjur,
3527 vlrdescmul,
3528 numpreant,
3529 v77_perc)
3530 select x.*,
3531 x.valor / v_totaldivida * 100
3532 from ( select v_termo,
3533 v01_coddiv,
3534 sum(vlrhis)::numeric as vlrhis,
3535 sum(vlrcor)::numeric as vlrcor,
3536 sum(vlrjur)::numeric as vlrjur,
3537 sum(vlrmul)::numeric as vlrmul,
3538 sum(vlrdes)::numeric as vlrdes,
3539 sum(valor)::numeric as valor,
3540 sum(vlrdesccor)::numeric as vlrdesccor,
3541 sum(vlrdescjur)::numeric as vlrdescjur,
3542 sum(vlrdescmul)::numeric as vlrdescmul,
3543 divida.v01_numpre
3544 from arrecad_parc_rec
3545 inner join divida on divida.v01_numpre = arrecad_parc_rec.numpre
3546 and divida.v01_numpar = arrecad_parc_rec.numpar
3547 where tipo = 5
3548 and receit not in ( select distinct receit from arrecad_parc_rec where juro is true )
3549 group by v01_coddiv, v01_numpre ) as x;
3550 else
3551
3552 insert into termodiv (parcel,
3553 coddiv,
3554 valor,
3555 vlrcor,
3556 juros,
3557 multa,
3558 desconto,
3559 total,
3560 vlrdesccor,
3561 vlrdescjur,
3562 vlrdescmul,
3563 numpreant,
3564 v77_perc)
3565 select x.*,
3566 x.valor / v_totaldivida * 100
3567 from ( select v_termo,
3568 v01_coddiv,
3569 sum(vlrhis)::numeric as vlrhis,
3570 sum(vlrcor)::numeric as vlrcor,
3571 sum(vlrjur)::numeric as vlrjur,
3572 sum(vlrmul)::numeric as vlrmul,
3573 sum(vlrdes)::numeric as vlrdes,
3574 sum(valor)::numeric as valor,
3575 sum(vlrdesccor)::numeric as vlrdesccor,
3576 sum(vlrdescjur)::numeric as vlrdescjur,
3577 sum(vlrdescmul)::numeric as vlrdescmul,
3578 divida.v01_numpre
3579 from arrecad_parc_rec
3580 inner join divida on divida.v01_numpre = arrecad_parc_rec.numpre
3581 and divida.v01_numpar = arrecad_parc_rec.numpar
3582 where tipo = 5
3583 group by v01_coddiv, v01_numpre ) as x;
3584 end if;
3585
3586 -- mostra os valores com origem de divida ativa
3587 if lRaise is true then
3588
3589 for v_record_numpres in select *
3590 from termodiv
3591 where parcel = v_termo
3592 loop
3593
3594 perform fc_debug('coddiv: '||v_record_numpres.coddiv||' - vlcor: '||v_record_numpres.vlrcor||' - total: '||v_record_numpres.total||' - juro: '||v_record_numpres.juros||' - multa: '||v_record_numpres.multa,lRaise,false,false);
3595
3596 end loop;
3597
3598 end if;
3599
3600 -- SE ORIGEM FOR DIVERSOS
3601 if lParcDiversos then
3602
3603 if lRaise is true then
3604 perform fc_debug('inserindo em termodiver...',lRaise,false,false);
3605 end if;
3606
3607 -- insere na termodiver
3608 insert into termodiver (dv10_parcel,
3609 dv10_coddiver,
3610 dv10_valor,
3611 dv10_vlrcor,
3612 dv10_juros,
3613 dv10_multa,
3614 dv10_desconto,
3615 dv10_total,
3616 dv10_numpreant,
3617 dv10_vlrdescjur,
3618 dv10_vlrdescmul,
3619 dv10_perc)
3620 select x.*,
3621 x.valor/v_total
3622 from ( select v_termo,
3623 dv05_coddiver,
3624 sum(vlrhis)::numeric as vlrhis,
3625 sum(vlrcor)::numeric as vlrcor,
3626 sum(vlrjur)::numeric as vlrjur,
3627 sum(vlrmul)::numeric as vlrmul,
3628 sum(vlrdes)::numeric as vlrdes,
3629 sum(valor)::numeric as valor,
3630 diversos.dv05_numpre,
3631 sum(vlrdescjur)::numeric as vlrdescjur,
3632 sum(vlrdescmul)::numeric as vlrdescmul
3633 from arrecad_parc_rec
3634 inner join diversos on diversos.dv05_numpre = arrecad_parc_rec.numpre
3635 group by dv05_coddiver, dv05_numpre
3636 ) as x;
3637 end if;
3638
3639 -- SE ORIGEM FOR CONTRIBUICAO DE MELHORIAS
3640 if lParcContrib then
3641
3642 if lRaise is true then
3643 perform fc_debug('inserindo em termodiver...',lRaise,false,false);
3644 end if;
3645
3646 -- insere na termodiver
3647 insert into termocontrib (parcel,
3648 contricalc,
3649 valor,
3650 vlrcor,
3651 juros,
3652 multa,
3653 desconto,
3654 total,
3655 numpreant,
3656 vlrdescjur,
3657 vlrdescmul,
3658 perc)
3659 select x.*,
3660 x.valor/v_total
3661 from ( select v_termo,
3662 d09_sequencial,
3663 sum(vlrhis)::numeric as vlrhis,
3664 sum(vlrcor)::numeric as vlrcor,
3665 sum(vlrjur)::numeric as vlrjur,
3666 sum(vlrmul)::numeric as vlrmul,
3667 sum(vlrdes)::numeric as vlrdes,
3668 sum(valor)::numeric as valor,
3669 contricalc.d09_numpre,
3670 sum(vlrdescjur)::numeric as vlrdescjur,
3671 sum(vlrdescmul)::numeric as vlrdescmul
3672 from arrecad_parc_rec
3673 inner join contricalc on contricalc.d09_numpre = arrecad_parc_rec.numpre
3674 group by d09_sequencial,d09_numpre
3675 ) as x;
3676 end if;
3677
3678 if lRaise is true then
3679 perform fc_debug('v_parcinicial: '||v_parcinicial,lRaise,false,false);
3680 end if;
3681
3682 -- SE ORIGEM FOR INICIAL DO FORO
3683 if v_parcinicial is true then
3684
3685 if lRaise is true then
3686 perform fc_debug('inserindo em termoini...',lRaise,false,false);
3687 end if;
3688
3689 -- insere na termoini
3690 insert into termoini(parcel,
3691 inicial,
3692 valor,
3693 vlrcor,
3694 juros,
3695 multa,
3696 desconto,
3697 total,
3698 vlrdesccor,
3699 vlrdescjur,
3700 vlrdescmul,
3701 v61_perc)
3702 select x.*,
3703 x.valor/v_total
3704 from ( select v_termo,
3705 inicialnumpre.v59_inicial,
3706 round(sum(vlrhis),2)::float8 as vlrhis,
3707 round(sum(vlrcor),2)::float8 as vlrcor,
3708 round(sum(vlrjur),2)::float8 as vlrjur,
3709 round(sum(vlrmul),2)::float8 as vlrmul,
3710 round(sum(vlrdes),2)::float8 as vlrdes,
3711 round(sum(valor),2)::float8 as valor,
3712 round(sum(vlrdesccor),2)::float8 as vlrdesccor,
3713 round(sum(vlrdescjur),2)::float8 as vlrdescjur,
3714 round(sum(vlrdescmul),2)::float8 as vlrdescmul
3715 from arrecad_parc_rec
3716 inner join inicialnumpre on inicialnumpre.v59_numpre = arrecad_parc_rec.numpre
3717 group by inicialnumpre.v59_inicial
3718 ) as x;
3719
3720 for v_iniciais in select distinct v59_inicial
3721 from arrecad_parc_rec
3722 inner join inicialnumpre on inicialnumpre.v59_numpre = arrecad_parc_rec.numpre
3723 inner join inicial on inicial.v50_inicial = inicialnumpre.v59_inicial
3724 and inicial.v50_situacao = 1
3725 loop
3726
3727 select nextval('inicialmov_v56_codmov_seq') into v_inicialmov;
3728
3729 insert into inicialmov values (v_inicialmov,v_iniciais.v59_inicial,4,'',dDataUsu,v_login);
3730 update inicial set v50_codmov = v_inicialmov where v50_inicial = v_iniciais.v59_inicial;
3731
3732 end loop;
3733
3734 end if;
3735
3736 -- Deletando os registros do arreold que estao incorretamente devido a bug
3737 -- da versao antiga da funcao fc_excluiparcelamento
3738
3739 delete from arreold
3740 using arrecad_parc_rec
3741 where arreold.k00_numpre = arrecad_parc_rec.numpre
3742 and arreold.k00_numpar = arrecad_parc_rec.numpar
3743 and arreold.k00_receit = arrecad_parc_rec.receit;
3744
3745 -- insere no arreold
3746
3747 insert into arreold(k00_numcgm,
3748 k00_dtoper,
3749 k00_receit,
3750 k00_hist,
3751 k00_valor,
3752 k00_dtvenc,
3753 k00_numpre,
3754 k00_numpar,
3755 k00_numtot,
3756 k00_numdig,
3757 k00_tipo,
3758 k00_tipojm)
3759 select arrecad.k00_numcgm,
3760 arrecad.k00_dtoper,
3761 arrecad.k00_receit,
3762 arrecad.k00_hist,
3763 arrecad.k00_valor,
3764 arrecad.k00_dtvenc,
3765 arrecad.k00_numpre,
3766 arrecad.k00_numpar,
3767 arrecad.k00_numtot,
3768 arrecad.k00_numdig,
3769 arrecad.k00_tipo,
3770 arrecad.k00_tipojm
3771 from arrecad
3772 inner join arrecad_parc_rec on arrecad.k00_numpre = arrecad_parc_rec.numpre
3773 and arrecad.k00_numpar = arrecad_parc_rec.numpar
3774 and arrecad.k00_receit = arrecad_parc_rec.receit
3775 left join arreold on arreold.k00_numpre = arrecad_parc_rec.numpre
3776 and arreold.k00_numpar = arrecad_parc_rec.numpar
3777 and arreold.k00_receit = arrecad_parc_rec.receit
3778 where arreold.k00_numpre is null
3779 and arrecad.k00_valor > 0;
3780
3781 delete from arrecad
3782 using arrecad_parc_rec
3783 where arrecad.k00_numpre = arrecad_parc_rec.numpre
3784 and arrecad.k00_numpar = arrecad_parc_rec.numpar
3785 and arrecad.k00_receit = arrecad_parc_rec.receit;
3786
3787 -- conta a quantidade de registros do arrecad
3788 select count(*)
3789 from arrecad
3790 into v_contador
3791 where k00_numpre = v_numpre;
3792
3793 if lRaise is true then
3794 perform fc_debug('total final de registros no arrecad: '||v_contador,lRaise,false,false);
3795 end if;
3796
3797 -- soma o valor gravado no arrecad
3798 if lSeparaJuroMulta = 2 then
3799
3800 select round(sum(k00_valor),2)
3801 into v_resto
3802 from arrecad
3803 where k00_numpre = v_numpre;
3804
3805 else
3806
3807 select round(sum(arrecad.k00_valor)+coalesce(sum(arrecadcompos.k00_correcao),0) + coalesce(sum(arrecadcompos.k00_juros),0) + coalesce(sum(arrecadcompos.k00_multa),0) ,2)
3808 into v_resto
3809 from arrecad
3810 left join arreckey on arreckey.k00_numpre = arrecad.k00_numpre
3811 and arreckey.k00_numpar = arrecad.k00_numpar
3812 and arreckey.k00_receit = arrecad.k00_receit
3813 and arreckey.k00_hist = arrecad.k00_hist
3814 left join arrecadcompos on arrecadcompos.k00_arreckey = arreckey.k00_sequencial
3815 where arrecad.k00_numpre = v_numpre;
3816
3817 end if;
3818
3819 if lRaise is true then
3820 perform fc_debug('Total do arrecad (v_resto): '||v_resto||' - v_total: '||v_total,lRaise,false,false);
3821 end if;
3822
3823 -- registra a diferenca do valor gravado no arrecad e do total do parcelamento calculado durante o processamento
3824 v_teste = round(v_total,2) - round(v_resto,2);
3825
3826 if lRaise is true then
3827
3828 perform fc_debug('v_teste: '||v_teste,lRaise,false,false);
3829 perform fc_debug(' ',lRaise,false,false);
3830 perform fc_debug('ACERTAR DIFERENCA',lRaise,false,false);
3831 perform fc_debug(' ',lRaise,false,false);
3832
3833 end if;
3834
3835
3836 select db21_codcli
3837 into iCodcli
3838 from db_config
3839 where prefeitura is true;
3840
3841 -- Alterados valores para Capivari, para conseguir analisar melhor os impactos de como resolver o problema da
3842 -- diferença de valor, sem que seja adicionada a diferença há última parecela.
3843 --CAPIVARI
3844 if ( iCodcli = 26 ) then
3845
3846 nFaixaInicial := -0.01;
3847 nFaixaFinal := 0.5;
3848
3849 end if;
3850
3851 -- Alterado a lógica do v_teste para lançar na última parcela a diferença do valor gravado no arrecad e do total do parcelamento calculado durante o processamento, caso v_teste esteja entre 0.01 e 6.00.
3852 -- Não se sabe o porquê dos valores descritos, anteriormente já havia lógica semelhante, apenas alteramos o between.
3853 if abs(v_teste) between nFaixaInicial and nFaixaFinal and v_juronaultima is false then
3854 if lRaise is true then
3855 perform fc_debug('entrou no 0.01 - diferenca: '||v_teste,lRaise,false,false);
3856 end if;
3857
3858 select k00_receit
3859 into v_maxrec
3860 from arrecad
3861 where k00_numpre = v_numpre
3862 and k00_numpar = v_totalparcelas
3863 order by k00_valor desc limit 1;
3864
3865 update arrecad
3866 set k00_valor = k00_valor + v_teste
3867 where k00_numpre = v_numpre
3868 and k00_numpar = v_totalparcelas
3869 and k00_receit = v_maxrec;
3870
3871 end if;
3872
3873 -- se juros na ultima
3874 if v_juronaultima is true then
3875
3876 select k00_receit
3877 into v_receita
3878 from arrecad
3879 where k00_numpre = v_numpre
3880 and k00_numpar = v_totalparcelas - 1
3881 limit 1;
3882
3883 if round(v_total,2) <> round(v_resto,2) then
3884
3885 if lRaise is true then
3886 perform fc_debug('update: '||(round(v_total,2) - round(v_resto,2)),lRaise,false,false);
3887 end if;
3888
3889 -- altera o valor da penultima parcela com a diferenca
3890 update arrecad
3891 set k00_valor = k00_valor + round(round(v_total,2) - round(v_resto,2),2)
3892 where k00_numpre = v_numpre
3893 and k00_numpar = v_totalparcelas - 1
3894 and k00_receit = v_receita;
3895
3896 end if;
3897
3898 end if;
3899
3900 -- funcao que corrige o arrecad no caso de encontrar registros duplicados(numpre,numpar,receit)
3901 -- perform fc_corrigeparcelamento();
3902
3903 if lSeparaJuroMulta = 2 then
3904
3905 select round(sum(k00_valor),2)
3906 into v_resto
3907 from arrecad
3908 where k00_numpre = v_numpre;
3909
3910 else
3911
3912 select round(sum(arrecad.k00_valor)+coalesce(sum(arrecadcompos.k00_correcao),0) + coalesce(sum(arrecadcompos.k00_juros),0) + coalesce(sum(arrecadcompos.k00_multa),0) ,2)
3913 into v_resto
3914 from arrecad
3915 left join arreckey on arreckey.k00_numpre = arrecad.k00_numpre
3916 and arreckey.k00_numpar = arrecad.k00_numpar
3917 and arreckey.k00_receit = arrecad.k00_receit
3918 and arreckey.k00_hist = arrecad.k00_hist
3919 left join arrecadcompos on arrecadcompos.k00_arreckey = arreckey.k00_sequencial
3920 where arrecad.k00_numpre = v_numpre;
3921 end if;
3922
3923 if lRaise is true then
3924 perform fc_debug('total do arrecad (v_resto): '||v_resto||' - v_total: '||v_total||' - totparc: '||v_totparc,lRaise,false,false);
3925 end if;
3926
3927 for v_record_recpar in select k00_receit,
3928 sum(k00_valor)
3929 from arrecad
3930 where k00_numpre = v_numpre
3931 group by k00_receit
3932 loop
3933
3934 if lRaise is true then
3935 perform fc_debug('receita: '||v_record_recpar.k00_receit||' - valor: '||v_record_recpar.sum,lRaise,false,false);
3936 end if;
3937
3938 end loop;
3939
3940 -- se total do arrecad for diferenca do total calculado durante o processamento
3941 -- mostra mensagem de erro
3942 if lRaise then
3943 perform fc_debug('Parcelamento : '||v_termo||' Numpre : '||v_numpre||' Total: '||v_total||' - Resto: '||v_resto||' Diferenca: '||(round(v_total,2) - round(v_resto,2)),lRaise,false,false);
3944 raise notice '%',fc_debug('Fim do Processamento...',lRaise,false,true);
3945 end if;
3946
3947 if round(v_total, 2) <> round(v_resto, 2) then
3948 return '[16] - total gerado da soma das parcelas inconsistente!';
3949 end if;
3950
3951 return '1 - Parcelamento efetuado com sucesso - Termo Gerado: '||v_termo||' - Numpre: '||v_numpre;
3952
3953 end;
3954
3955$$ language 'plpgsql';