create or replace FUNCTION BUSCA_DATA_ULTIMA_BAIXA(
   P_CDFILIAL     IN FILIAL.CDFILIAL%TYPE,
   P_NRLANCTONF   IN NOTAFISCAL.NRLANCTONF%TYPE) RETURN DATE IS

   V_DTVENBOLREC   DATE;
   V_CDFILIAL     VARCHAR2(04);
   V_NRLANBOLREC   VARCHAR2(10);
   V_IDSTATBREC VARCHAR2(01);
   V_COUNT INTEGER;
BEGIN
   SELECT COUNT(1)
     INTO V_COUNT
     FROM CONTARECEBER CR
    WHERE CR.CDFILIAL =  P_CDFILIAL
      AND CR.NRLANCTONF = P_NRLANCTONF
      AND CR.IDSTATREC <> 'B';
      
   IF V_COUNT > 0 THEN
      RETURN(NULL);      
   ELSE
      
   SELECT MAX(CR.CDFILIBOLREC), MAX(CR.NRLANBOLREC)
     INTO V_CDFILIAL, V_NRLANBOLREC
     FROM NOTAFISCAL NF, CONTARECEBER CR
    WHERE NF.CDFILIAL =  P_CDFILIAL
      AND NF.NRLANCTONF = P_NRLANCTONF
      AND NF.CDFILIAL = CR.CDFILIAL
      AND NF.NRLANCTONF = CR.NRLANCTONF
      AND CR.DTATUAVENREC = (SELECT MAX(DTATUAVENREC)
                               FROM CONTARECEBER CR1
                              WHERE CR1.CDFILIAL = CR.CDFILIAL
                                AND CR1.NRLANCTONF = CR.NRLANCTONF);
      
      SELECT MAX(IDSTATBREC), MAX(DTBAIXAREC)
        INTO V_IDSTATBREC,  V_DTVENBOLREC
        FROM BOLETRECEBER BR, BAIXARECEBIDA BA
       WHERE BR.CDFILIAL = V_CDFILIAL
         AND BR.NRLANBOLREC = V_NRLANBOLREC
         AND BR.CDFILIBAIREC = BA.CDFILIAL
         AND BR.NRBAIXAREC = BA.NRBAIXAREC;
      
      IF (V_IDSTATBREC <> 'B') THEN
         RETURN(NULL);    
      ELSE
                
         RETURN(V_DTVENBOLREC);     
      END IF;
   END IF;
END;
/