CREATE OR REPLACE PROCEDURE ATUALIZA_IDEVOLESTOQ
   (P_CDFILIPROC IN LANCTOESTOQ.CDFILIAL%TYPE,
    P_NRLANCESTQ IN LANCTOESTOQ.NRLANCESTQ%TYPE)

AS

   CURSOR C_PRODIRREG IS
      SELECT DISTINCT I.CDFILIAL, I.NRLANCESTQ, I.NRSEQUITEM,
             I.CDPRODMOVI, I.CDFILIMOVI, I.DTLANCMOVI, NVL(PF.IDPERMESTNEG,'N') AS IDPERMESTNEG
      FROM ITLANCTOEST I, POSESTDIA P, PARAMFILIAL PF
      WHERE I.CDFILIAL     = P_CDFILIPROC   AND
            I.NRLANCESTQ   = P_NRLANCESTQ   AND
            I.CDFILIMOVI   = PF.CDFILIAL(+) AND
            I.CDFILIMOVI   = P.CDFILIAL     AND
            I.CDPRODMOVI   = P.CDPRODUTO    AND
            I.CDALMOXARIFE = P.CDALMOXARIFE AND
            I.CDLOCALESTOQ = P.CDLOCALESTOQ AND
            I.NRLOTEESTQ   = P.NRLOTEESTQ   AND
            I.NRSUBLOTE    = P.NRSUBLOTE    AND
            P.DTPOSIESTQ  >= I.DTLANCMOVI   AND
            P.QTESTOQDIA  < 0;

BEGIN
   FOR C_IRREGESTOQ IN C_PRODIRREG LOOP
      IF C_IRREGESTOQ.IDPERMESTNEG = 'N' THEN
         UPDATE ITLANCTOEST
         SET IDEVOLESTOQ = 'N'
         WHERE CDFILIAL   = C_IRREGESTOQ.CDFILIAL   AND
               NRLANCESTQ = C_IRREGESTOQ.NRLANCESTQ AND
               NRSEQUITEM = C_IRREGESTOQ.NRSEQUITEM;

         ATUALIZA_ESTOQUE(C_IRREGESTOQ.CDFILIMOVI, C_IRREGESTOQ.DTLANCMOVI, SYSDATE, C_IRREGESTOQ.CDFILIAL, C_IRREGESTOQ.NRLANCESTQ);
      END IF;
   END LOOP;
END;
/
