CREATE OR REPLACE FUNCTION USR_VRCANC_REDZ_LAVOR
   (P_CDFILIAL   IN NOTAFISCAL.CDFILIAL%TYPE,
    P_CDEMPRESA  IN NOTAFISCAL.CDEMPRESA%TYPE,
    P_CDINSCESTA IN NOTAFISCAL.CDINSCESTA%TYPE,
    P_CDINSCMUNI IN NOTAFISCAL.CDINSCMUNI%TYPE,
    P_NRINSJURNF IN NOTAFISCAL.NRINSJURNF%TYPE,
    P_CDCLIENTE  IN NOTAFISCAL.CDCLIENTE%TYPE,
    P_DTEMISSAO  IN NOTAFISCAL.DTEMISSAO%TYPE,
    P_DTENTRSAID IN NOTAFISCAL.DTENTRSAID%TYPE,
    P_VRNOTAFISC IN NOTAFISCAL.VRNOTAFISC%TYPE,
    P_CDFILIEMIT IN NOTAFISCAL.CDFILIEMIT%TYPE,
    P_NRSEQLANC  IN LANCCONT.NRSEQLANC%TYPE) RETURN FLOAT
IS
   V_CDFILIAL     VARCHAR2(4);
   V_NRLANCTONF   VARCHAR2(10);
   V_CDFILREDZ    VARCHAR2(4);
   V_CDCAIXA      VARCHAR2(3);
   V_DTCAIXABER   DATE;
   V_VRTOTCANREDZ FLOAT;

BEGIN
   V_CDFILIAL   := NULL;
   V_NRLANCTONF := NULL;
   V_CDFILREDZ  := NULL;
   V_CDCAIXA    := NULL;
   V_VRTOTCANREDZ := 0;
   
   IF P_NRSEQLANC IN ('00001', '00002') THEN
      SELECT CDFILIAL, NRLANCTONF
        INTO V_CDFILIAL, V_NRLANCTONF
        FROM NOTAFISCAL
       WHERE CDFILIAL   = P_CDFILIAL
         AND CDEMPRESA  = P_CDEMPRESA
         AND CDINSCESTA = P_CDINSCESTA
         AND CDINSCMUNI = P_CDINSCMUNI
         AND NRINSJURNF = P_NRINSJURNF
         AND CDCLIENTE  = P_CDCLIENTE
         AND DTEMISSAO  = P_DTEMISSAO
         AND DTENTRSAID = P_DTENTRSAID
         AND VRNOTAFISC = P_VRNOTAFISC
         AND CDFILIEMIT = P_CDFILIEMIT
         AND IDSISTEMA  = 'FIS';
   
      SELECT CDFILIAL, CDCAIXA, TO_DATE(DTABERCAIX)
        INTO V_CDFILREDZ, V_CDCAIXA, V_DTCAIXABER
        FROM MOVCAIXA
       WHERE CDFILIALNFFIS = V_CDFILIAL
         AND NRLANCTONFFIS = V_NRLANCTONF
         AND ROWNUM = 1;
          
      SELECT VRTOTCANREDZ 
        INTO V_VRTOTCANREDZ
        FROM REDUCAOZ
       WHERE CDFILIAL = V_CDFILREDZ
         AND CDCAIXA = V_CDCAIXA
         AND DTREDUCAOZ = V_DTCAIXABER;

      END IF;

  RETURN(V_VRTOTCANREDZ);
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('USR_VRCANC_REDZ_LAVOR','5.65.XXX'); END;
/