CREATE OR REPLACE FUNCTION VALOR_PEDIDO_BRUTO(
   P_CDFILIAL     IN FILIAL.CDFILIAL%TYPE,
   P_NRPEDIDO     IN PEDIDO.NRPEDIDO%TYPE) RETURN NUMBER IS

   V_VRPEDIDO_BRUT NUMBER;
   V_VRITEM NUMBER;
   V_VRENCARGO NUMBER;
   V_VRIMPOSTO NUMBER;
   V_VRIMPOSTODESON NUMBER;
BEGIN
   V_VRPEDIDO_BRUT := 0;
   SELECT NVL(SUM((I.QTITEMPED * ROUND(I.VRPREUNITPED,2))),0) VRITEM
     INTO V_VRITEM
     FROM ITEMPEDIDO I
    WHERE I.CDFILIAL = P_CDFILIAL
      AND I.NRPEDIDO = P_NRPEDIDO;

   SELECT NVL(SUM(CASE EN.IDENCARGO WHEN 'A' THEN NVL(E.VRENCARGOPED,0)
                                WHEN 'D' THEN (NVL(E.VRENCARGOPED,0) * -1)
                                ELSE 0 END),0) VRENCARGO
     INTO V_VRENCARGO
     FROM ENCARGOPED E, ENCARGO EN
    WHERE E.CDENCARGO = EN.CDENCARGO
      AND E.CDFILIAL = P_CDFILIAL
      AND E.NRPEDIDO = P_NRPEDIDO;

   SELECT NVL(SUM(CASE IM.IDTRATIMPO WHEN 'A' THEN NVL(IP.VRIMPOSTOITPED,0)
                                     WHEN 'D' THEN (NVL(IP.VRIMPOSTOITPED,0) * -1)
                                     ELSE 0 END),0) VRIMPOSTO
     INTO V_VRIMPOSTO
     FROM IMPOSTO IM, IMPITEMPEDIDO IP, ITEMPEDIDO IT
    WHERE IT.CDFILIAL = P_CDFILIAL
      AND IT.NRPEDIDO = P_NRPEDIDO
      AND NVL(IT.IDPRODBONIF, 'N') = 'N'
      AND IT.CDFILIAL = IP.CDFILIAL
      AND IT.NRPEDIDO = IP.NRPEDIDO
      AND IT.NRITEMPED = IP.NRITEMPED
      AND IP.CDIMPOSTO = IM.CDIMPOSTO;

   SELECT NVL(SUM(NVL(IP.VRIMPOSTODESON,0)),0)
     INTO V_VRIMPOSTODESON
     FROM IMPITEMPEDIDO IP
    WHERE IP.CDFILIAL = P_CDFILIAL
      AND IP.NRPEDIDO = P_NRPEDIDO
      AND IP.IDIMPDESONERAIT = 'S';

   V_VRPEDIDO_BRUT := V_VRITEM + V_VRENCARGO + V_VRIMPOSTO - V_VRIMPOSTODESON;

   RETURN(V_VRPEDIDO_BRUT);
END;
/