CREATE OR replace FUNCTION VALOR_IMPOSTO_NFE(
   P_CDFILIAL       IN ITEMPRODUTO.CDFILIAL%TYPE,
   P_NRLANCTONF     IN ITEMPRODUTO.NRLANCTONF%TYPE,
   P_CDIMPOSTONFE   IN IMPOSTO.CDIMPOSTO%TYPE,
   P_IDVALOR        IN ITEMPROIMPOS.IDVALORINFIT%TYPE,
   P_CDFISCAL       IN ITEMPROIMPOS.CDFISCALIT%TYPE DEFAULT NULL) RETURN NUMBER
AS
   V_VRBASECALCIT ITEMPROIMPOS.VRBASECALCIT%TYPE;
   V_VRALIQITEM   ITEMPROIMPOS.VRALIQITEM%TYPE;
   V_VRIMPOSTOIT  ITEMPROIMPOS.VRIMPOSTOIT%TYPE;
   V_VRPERREDBCIT ITEMPROIMPOS.VRPERREDBCIT%TYPE;
   V_VRCONTITIMPO ITEMPROIMPOS.VRCONTITIMP%TYPE;
   V_VRTOTAITEM   ITEMPRODUTO.VRTOTAITEM%TYPE;
BEGIN
   IF P_IDVALOR = 'T' THEN
      SELECT SUM(VRTOTAITEM)
        INTO V_VRTOTAITEM
        FROM ITEMPRODUTO IP
       WHERE (IP.CDFILIAL   = P_CDFILIAL  )
         AND (IP.NRLANCTONF = P_NRLANCTONF);
      RETURN(V_VRTOTAITEM);
   ELSE
      SELECT NVL(SUM(ROUND(VRBASECALCIT,2)),0),
             NVL(MAX(VRALIQITEM),0),
             NVL(SUM(ROUND(VRIMPOSTOIT,2)),0),
             NVL(MAX(VRPERREDBCIT),0),
             NVL(SUM(ROUND(VRCONTITIMP,2)),0)
        INTO V_VRBASECALCIT,
             V_VRALIQITEM,
             V_VRIMPOSTOIT,
             V_VRPERREDBCIT,
             V_VRCONTITIMPO
        FROM ITEMPROIMPOS IT, IMPOSTO IM
       WHERE (IT.CDFILIAL     = P_CDFILIAL    ) AND
             (IT.NRLANCTONF   = P_NRLANCTONF  ) AND
             (IT.CDIMPOSTO    = IM.CDIMPOSTO  ) AND
             (IM.CDIMPOSTONFE = P_CDIMPOSTONFE) AND
             (IT.NRITPROIMPOS = '1'           ) AND
             (IT.CDFISCALIT = NVL(P_CDFISCAL, IT.CDFISCALIT));
      IF P_IDVALOR = 'A' THEN
         RETURN(V_VRALIQITEM);
      ELSIF P_IDVALOR = 'B' THEN
         RETURN(V_VRBASECALCIT);
      ELSIF P_IDVALOR = 'I' THEN
         RETURN(V_VRIMPOSTOIT);
      ELSIF P_IDVALOR = 'P' THEN
         RETURN(V_VRPERREDBCIT);
      ELSIF P_IDVALOR = 'C' THEN
         RETURN(V_VRCONTITIMPO);
      END IF;
   END IF;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('VALOR_IMPOSTO_NFE','6.39.005'); END;
/

