CREATE OR REPLACE PROCEDURE POSICAO_ESTOQUE_CONS(
   P_FILIAL       IN POSESTDIA.CDFILIAL%TYPE,
   P_PRODUTO      IN POSESTDIA.CDPRODUTO%TYPE,
   P_DTPOSICAO    IN POSESTDIA.DTPOSIESTQ%TYPE,
   P_QTDEESTO     OUT NUMBER,
   P_VALRESTO     OUT NUMBER,
   P_VALRBRUT     OUT NUMBER,
   P_POSNZERO     IN POSESTDIA.IDPOSIZERO%TYPE DEFAULT 'N',
   P_ALMOXARIFE   IN ALMOXARIFADO.CDALMOXARIFE%TYPE DEFAULT NULL,
   P_LOCALESTOQ   IN LOCALESTOQUE.CDLOCALESTOQ%TYPE DEFAULT NULL,
   P_IDUTILALMOX  IN POSESTDIA.IDPOSIZERO%TYPE DEFAULT NULL,
   P_IDUTILLCESTQ IN POSESTDIA.IDPOSIZERO%TYPE DEFAULT NULL,
   P_IDUTILLOTE   IN POSESTDIA.IDPOSIZERO%TYPE DEFAULT NULL,
   P_NRLOTEESTQ   IN POSESTDIA.NRLOTEESTQ%TYPE DEFAULT NULL,
   P_NRSUBLOTE    IN POSESTDIA.NRSUBLOTE%TYPE  DEFAULT NULL)

AS
   V_QTDEESTO     NUMBER;
   V_VALRESTO     NUMBER;
   V_VALRBRUT     NUMBER;
   V_QTDEANTE     NUMBER;
   V_VALRANTE     NUMBER;
   V_VRBRANTE     NUMBER;
   V_QTDEESTOAUX  NUMBER;
   V_VALRESTOAUX  NUMBER;
   V_VALRBRUTAUX  NUMBER;
BEGIN
  SELECT NVL(MAX(QTESTDIACON),0)           AS QTDEESTO,
         NVL(MAX(VRESTDIACON),0)           AS VALRESTO,
         ROUND(NVL(MAX(VRESTBRUTCON),0),5) AS VALRBRUT,
         ROUND(NVL(MAX(QTESTANTCON),0),5)  AS QTDEANTE,
         ROUND(NVL(MAX(VRESTANTCON),0),5)  AS VALRANTE,
         ROUND(NVL(MAX(VRBRUTANTCON),0),5)  AS VRBRANTE
   INTO V_QTDEESTO,
        V_VALRESTO,
        V_VALRBRUT,
        V_QTDEANTE,
        V_VALRANTE,
        V_VRBRANTE
   FROM POSESTCONS P
   WHERE (CDFILIAL    = P_FILIAL)     AND
         (CDPRODUTO   = P_PRODUTO)    AND
         (DTPOSESTCON = DTPOSICAO_POSESTCONS(P.CDFILIAL, P.CDPRODUTO, P_DTPOSICAO));

   IF (P_POSNZERO = 'S') AND (V_QTDEESTO = 0) THEN
      P_QTDEESTO := V_QTDEANTE;
      P_VALRESTO := V_VALRANTE;
      P_VALRBRUT := V_VRBRANTE;
   ELSE
      P_QTDEESTO := V_QTDEESTO;
      P_VALRESTO := V_VALRESTO;
      P_VALRBRUT := V_VALRBRUT;
   END IF;
END;
/
