SET TERM ^ ;

CREATE OR ALTER procedure SPU_CONTA_PAGAR_SALDO3 (
    NFE_CONTROLE_1 integer,
    CONTROLE_1 integer)
as
declare variable CONTROLEX integer;
declare variable SALDOX numeric(10,2);
declare variable CONTROLE2 integer;
declare variable CONTROLE3 integer;
declare variable DATA date;
declare variable VALOR numeric(15,2);
declare variable SALDO numeric(15,2);
declare variable RM char(1);
declare variable TIPO char(1);
BEGIN
CONTROLEX = 0;
FOR SELECT
A.NFE_PARCELAMENTO_CONTROLE, A.CONTROLE, A.DATA, A.VALOR_TOTAL, A.VALOR_SALDO, A.REGISTRO_MESTRE, A.TIPO
FROM TBCAIXABANCO_LANCAMENTO_REG A
WHERE A.NFE_CONTROLE = :NFE_CONTROLE_1
  AND A.NFE_PARCELAMENTO_CONTROLE = :CONTROLE_1

ORDER BY A.CONTROLE

INTO
 :CONTROLE2,
 :CONTROLE3,
 :DATA,
 :VALOR,
 :SALDO,
 :RM,
 :TIPO
DO     

 IF (:CONTROLE2 > 0) THEN
    BEGIN
    IF (:CONTROLEX <> :CONTROLE2) THEN
       BEGIN
       SALDOX    = :VALOR;
       CONTROLEX = :CONTROLE2;
       END ELSE
       BEGIN

       IF (:TIPO = 'C') THEN
          BEGIN
          SALDOX = :SALDOX + :VALOR ;
          END
       IF (:TIPO = 'D') THEN
          BEGIN
          SALDOX = :SALDOX - :VALOR ;
          END
       END

       IF (:SALDOX < 0) THEN
          BEGIN
          SALDOX = 0;
          END

       /*if(:TIPO = 'D')then
       begin
          EXCEPTION "..." 'ATUALIZAR SALDO: '||:SALDOX;
       end */
       UPDATE TBCAIXABANCO_LANCAMENTO_REG SET
       VALOR_SALDO = :SALDOX
       WHERE CONTROLE = :CONTROLE3
         AND NFE_CONTROLE = :NFE_CONTROLE_1
         AND NFE_PARCELAMENTO_CONTROLE = :CONTROLE2;

   END

END^

SET TERM ; ^

