CREATE OR REPLACE FUNCTION VALOR_CARGA_TRIBUTARIA(
   P_CDIMPOSTO    IN IMPOSTO.CDIMPOSTO%TYPE,
   P_CDFILIAL     IN NOTAFISCAL.CDFILIAL%TYPE,
   P_NRLANCTONF   IN NOTAFISCAL.NRLANCTONF%TYPE) RETURN NUMBER
AS
   V_CDIMPCARGATRIB    VARCHAR2(02);
   V_VRCARGTRIBUT      NUMBER;
BEGIN

   V_VRCARGTRIBUT := 0;
   BEGIN
      SELECT CDIMPCARGATRIB
      INTO V_CDIMPCARGATRIB
      FROM IMPOSTO
      WHERE CDIMPOSTO = P_CDIMPOSTO;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_CDIMPCARGATRIB := NULL;
   END;

   BEGIN
      SELECT ROUND(SUM(I.VRIMPOSTOIT),2)
      INTO V_VRCARGTRIBUT
      FROM (SELECT IT.CDIMPOSTO, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT, CDFISCALIT,
                   CDSITUTRIBIT, CDFISCOPERIT, CDSUFXCFOPIT, IDTRIMPSTII, SUM(VRCONTITIMP) AS VRCONTITIMP,
                   SUM(VRBASECALCIT) AS VRBASECALCIT, SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,
                   MAX(NRITPROIMPOS) AS NRITPROIMPOS
            FROM ITEMPROIMPOS IT, IMPOSTO I
            WHERE CDFILIAL     = P_CDFILIAL
              AND NRLANCTONF   = P_NRLANCTONF
              AND IT.CDIMPOSTO = V_CDIMPCARGATRIB
              AND IT.CDIMPOSTO = I.CDIMPOSTO
              AND IT.NRITPROIMPOS = '1'
              AND IT.CDFISCALIT   = '1'
            GROUP BY IT.CDIMPOSTO, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT, CDFISCALIT,
                     CDSITUTRIBIT, CDFISCOPERIT, CDSUFXCFOPIT, IDTRIMPSTII) I;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_VRCARGTRIBUT := 0;
   END;

   RETURN(V_VRCARGTRIBUT);
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('VALOR_CARGA_TRIBUTARIA','5.05.059'); END;
/

