CREATE OR REPLACE FUNCTION SOMA_IMPOSTO(
   P_CDEMPRESA    IN MAPAAPURAC.CDEMPRESA%TYPE,
   P_CDIMPOSTO    IN MAPAAPURAC.CDIMPOSTO%TYPE,
   P_NRSEQUMAPAPU IN MAPAAPURAC.NRSEQUMAPAPU%TYPE,
   P_INSCRICAO    IN MAPAAPURAC.CDINSCESTA%TYPE,
   P_DTFINAL      IN MAPAAPURAC.DTFIMPERIODO%TYPE,
   P_DTINICIAL    IN MAPAAPURAC.DTINIPERIODO%TYPE,
   P_NOTASMAPA    IN MAPAAPURAC.VRTOTAIMPOS%TYPE) RETURN VARCHAR
AS
   V_VRTOTADEBI        NUMBER;
   V_VRTOTACRED        NUMBER;
   V_VRSALDODEBI       NUMBER;
   V_VRSALDOCRED       NUMBER;
   V_IDAPURACAO        VARCHAR2(01);
   V_NFFORAPERIODO     VARCHAR2(01);
   V_UTFORMULA         VARCHAR2(01);
   V_BOIMPOSAPUR       BOOLEAN;
   V_BOATUCTCTBL       BOOLEAN;
   V_ANO               VARCHAR2(04);
   V_MES               VARCHAR2(02);
   V_DIA               VARCHAR2(02);
   V_NRSEQITMAPA       NUMBER;
   V_IDORGARRECADNFE   VARCHAR2(01);
   V_IDFORMAPURNFE     VARCHAR2(01);
   V_IDIMPORECUPNFE    VARCHAR2(01);
   V_DTININFFORPER     DATE;
   V_IDNFFORAPERAPU    VARCHAR2(01);
   V_RETORNO           VARCHAR2(03);
   V_VROUTRDEBI        NUMBER;
   V_VRESTOCRED        NUMBER;
   V_VROUTRCRED        NUMBER;
   V_VRESTODEBI        NUMBER;
   V_VRDEDUCAO         NUMBER;
   V_VRDIFALIQU        NUMBER;
   V_VRCONTSAID        NUMBER;
   V_VRBASESAID        NUMBER;
   V_VRCONTENTR        NUMBER;
   V_VRBASEENTR        NUMBER;
   V_VRIMPOSAID        NUMBER;
   V_VRIMPOENTR        NUMBER;
   V_IDCREDDEBNORM     VARCHAR2(01);
   V_IDOUTCREDDEB      VARCHAR2(01);
   V_SEQMAPAANT        VARCHAR2(10);
   V_VRSALDOCREDANT    NUMBER;
   V_IDNFFORAPERAPUIMP VARCHAR2(01);
   V_IDSOMAFECP        VARCHAR2(01);
   
BEGIN
   
   V_BOIMPOSAPUR := FALSE;
   V_BOATUCTCTBL := FALSE;
   
   BEGIN 
      SELECT IDSOMAFECP 
        INTO V_IDSOMAFECP
        FROM AJUSTEFECP
       WHERE CDEMPRESA    = P_CDEMPRESA
         AND CDINSCESTA   = P_INSCRICAO
         AND CDIMPOSTO    = P_CDIMPOSTO;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDSOMAFECP := 'S';
   END;    
   V_IDSOMAFECP := NVL(V_IDSOMAFECP,'S');

   /******** Busca o orgao arrecadador, a forma de apuracao do imposto
             e se o mesmo e recuperavel ********/
   BEGIN
      SELECT IDORGARRECADNFE, IDFORMAPURNFE, IDIMPORECUPNFE
        INTO V_IDORGARRECADNFE, V_IDFORMAPURNFE, V_IDIMPORECUPNFE
        FROM IMPOSTONFE I
       WHERE CDIMPOSTONFE = P_CDIMPOSTO;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDORGARRECADNFE := NULL;
         V_IDFORMAPURNFE   := NULL;
         V_IDIMPORECUPNFE  := NULL;
   END;

   /******** Verifica se o imposto possui outro imposto relacionado para apuracao e, tambem,
             se atualiza a conta contabil dos itens do imposto                     ********/
   FOR C_IMPOSRELAC IN (SELECT CDIMPOSAPUR, IDATUCCTBITIMP
                          FROM IMPOSTO
                         WHERE CDIMPOSTONFE = P_CDIMPOSTO) LOOP

      IF C_IMPOSRELAC.CDIMPOSAPUR IS NOT NULL THEN
         V_BOIMPOSAPUR := TRUE;
      END IF;

      IF C_IMPOSRELAC.IDATUCCTBITIMP = 'S' THEN
         V_BOATUCTCTBL := TRUE;
      END IF;
   END LOOP;

   /******** Busca a data inicial para considerar as NF's fora do periodo ********/
   BEGIN
      SELECT DTININFFORPER, IDNFFORAPERAPU
        INTO V_DTININFFORPER, V_IDNFFORAPERAPU
        FROM PARAMFISCAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_DTININFFORPER  := '';
         V_IDNFFORAPERAPU := '';
   END;

   /******** Verifica se existe o parametro de vincula NF fora do periodo por Imposto ********/
   BEGIN
      SELECT MAX(IDNFFORAPERAPU)
        INTO V_IDNFFORAPERAPUIMP
        FROM IMPOSTO
       WHERE CDIMPOSTONFE = P_CDIMPOSTO;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDNFFORAPERAPUIMP := '';
   END;

   IF V_IDNFFORAPERAPUIMP <> 'I' THEN
      V_IDNFFORAPERAPU := V_IDNFFORAPERAPUIMP;
   END IF;

   CASE V_IDFORMAPURNFE
      WHEN 'P' THEN
         /******** Apuracao pela Data de Pagamento ********/
         V_RETORNO := APURA_DATA_PAGAMENTO(P_NRSEQUMAPAPU, P_CDEMPRESA, P_CDIMPOSTO, P_INSCRICAO, P_DTFINAL, P_DTINICIAL, V_BOIMPOSAPUR, V_IDORGARRECADNFE, V_DTININFFORPER, V_IDNFFORAPERAPU);
         V_IDAPURACAO    := SUBSTR(V_RETORNO,1,1);
         V_NFFORAPERIODO := SUBSTR(V_RETORNO,2,1);
      WHEN 'C' THEN
         /******** Apuracao pela Data de Competencia ********/
         V_RETORNO := APURA_DATA_COMPETENCIA(P_NRSEQUMAPAPU, P_CDEMPRESA, P_CDIMPOSTO, P_INSCRICAO, P_DTFINAL, P_DTINICIAL, V_BOIMPOSAPUR, V_IDORGARRECADNFE, V_DTININFFORPER, V_IDNFFORAPERAPU);
         V_IDAPURACAO    := SUBSTR(V_RETORNO,1,1);
         V_NFFORAPERIODO := SUBSTR(V_RETORNO,2,1);
         V_IDOUTCREDDEB  := SUBSTR(V_RETORNO,3,1);
      WHEN 'D' THEN
         /******** Apuracao pela Data de Entrada/Saida ********/
         V_RETORNO := APURA_DATA_ENTRSAID(P_NRSEQUMAPAPU, P_CDEMPRESA, P_CDIMPOSTO, P_INSCRICAO, P_DTFINAL, P_DTINICIAL, V_BOIMPOSAPUR, V_IDORGARRECADNFE, V_DTININFFORPER, V_IDNFFORAPERAPU);
         V_IDAPURACAO    := SUBSTR(V_RETORNO,1,1);
         V_NFFORAPERIODO := SUBSTR(V_RETORNO,2,1);
      WHEN 'E' THEN
         /******** Apuracao pela Data de Emissao ********/
         V_RETORNO := APURA_DATA_EMISSAO(P_NRSEQUMAPAPU, P_CDEMPRESA, P_CDIMPOSTO, P_INSCRICAO, P_DTFINAL, P_DTINICIAL, V_BOIMPOSAPUR, V_IDORGARRECADNFE, V_DTININFFORPER, V_IDNFFORAPERAPU);
         V_IDAPURACAO    := SUBSTR(V_RETORNO,1,1);
         V_NFFORAPERIODO := SUBSTR(V_RETORNO,2,1);
   END CASE;

   /**** Obs.: Neste ponto estava a rotina de Regime Especial ****/

   /******** Vincula as notas apuradas ao mapa, caso o parametro esteja marcado ********/
   IF V_IDNFFORAPERAPU = 'S' THEN
      UPDATE IMPOSTONF
         SET DTREFMAPAPU   = P_DTINICIAL
       WHERE (NRSEQUMAPAPU = P_NRSEQUMAPAPU OR
              NRSEQMAPOIMP = P_NRSEQUMAPAPU);

      UPDATE IMPBAIXAREC
         SET DTREFMAPAPU   = P_DTINICIAL
       WHERE (NRSEQUMAPAPU = P_NRSEQUMAPAPU OR
              NRSEQMAPOIMP = P_NRSEQUMAPAPU);
   ELSE
      UPDATE IMPOSTONF
         SET DTREFMAPAPU   = ''
       WHERE (NRSEQUMAPAPU = P_NRSEQUMAPAPU OR
              NRSEQMAPOIMP = P_NRSEQUMAPAPU);

      UPDATE IMPBAIXAREC
         SET DTREFMAPAPU   = ''
       WHERE (NRSEQUMAPAPU = P_NRSEQUMAPAPU OR
              NRSEQMAPOIMP = P_NRSEQUMAPAPU);
   END IF;

   /******** Busca os valores da ITMAPARECUP para atualizar a tabela MAPARECUP ********/
   BEGIN
      SELECT NVL(SUM(DECODE(IDTIPOITMAPR,'OD',VRITEMMAPR,0)),0) AS VROUTRDEBI,
             NVL(SUM(DECODE(IDTIPOITMAPR,'EC',VRITEMMAPR,0)),0) AS VRESTOCRED,
             NVL(SUM(DECODE(IDTIPOITMAPR,'OC',VRITEMMAPR,0)),0) AS VROUTRCRED,
             NVL(SUM(DECODE(IDTIPOITMAPR,'ED',VRITEMMAPR,0)),0) AS VRESTODEBI,
             NVL(SUM(DECODE(IDTIPOITMAPR,'DD',VRITEMMAPR,0)),0) AS VRDEDUCAO,
             NVL(SUM(DECODE(IDTIPOITMAPR,'DA',VRITEMMAPR,0)),0) AS VRDIFALIQU
        INTO V_VROUTRDEBI, V_VRESTOCRED, V_VROUTRCRED, V_VRESTODEBI,
             V_VRDEDUCAO, V_VRDIFALIQU
        FROM ITMAPARECUP
       WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
          V_VROUTRDEBI := 0;
          V_VRESTOCRED := 0;
          V_VROUTRCRED := 0;
          V_VRESTODEBI := 0;
          V_VRDEDUCAO  := 0;
          V_VRDIFALIQU := 0;
   END;

   /**** Obs.: Neste ponto estava a rotina Calcula Lucro Presumido ****/

   /******** Atualiza os valores na MAPAAPURAC ********/
   V_VRCONTENTR := 0;
   V_VRBASEENTR := 0;
   V_VRIMPOENTR := 0;
   V_VRCONTSAID := 0;
   V_VRBASESAID := 0;
   V_VRIMPOSAID := 0;

   /******** Impostos de Apuracao Conjunta ********/
   IF V_IDAPURACAO IN ('A','B','T','D') THEN
      BEGIN
         SELECT NVL(SUM(DECODE(IDENTRSAIDOP,'E',VRCONTABILNF,0)),0) AS VRCONTENTR,
                NVL(SUM(DECODE(IDENTRSAIDOP,'E',VRBASECALCNF,0)),0) AS VRBASEENTR,
                NVL(SUM(DECODE(IDENTRSAIDOP,'E',VRIMPOSTONF, 0)),0) AS VRIMPOENTR,
                NVL(SUM(DECODE(IDENTRSAIDOP,'S',VRCONTABILNF,0)),0) AS VRCONTSAID,
                NVL(SUM(DECODE(IDENTRSAIDOP,'S',VRBASECALCNF,0)),0) AS VRBASESAID,
                NVL(SUM(DECODE(IDENTRSAIDOP,'S',VRIMPOSTONF, 0)),0) AS VRIMPOSAID
           INTO V_VRCONTENTR, V_VRBASEENTR, V_VRIMPOENTR,
                V_VRCONTSAID, V_VRBASESAID, V_VRIMPOSAID
           FROM (SELECT NF.IDENTRSAIDOP, I.IDIMPORECUP, ROUND(IP.VRCONTABILNF,2) AS VRCONTABILNF,
                        ROUND(DECODE(IP.CDFISCALNF,'1',IP.VRBASECALCNF,0),2) AS VRBASECALCNF,
                        ROUND(DECODE(IP.CDFISCALNF,'1',IP.VRIMPOSTONF + DECODE( V_IDSOMAFECP, 'N', 0, 'S', NVL(IP.VRADICFECP,0) ), 0),2) AS VRIMPOSTONF
                   FROM IMPOSTONF IP, IMPOSTO I, NOTAFISCAL NF
                  WHERE I.CDIMPOSTONFE  = P_CDIMPOSTO
                    AND IP.CDIMPOSTO    = I.CDIMPOSTO
                    AND NF.CDFILIAL     = IP.CDFILIAL
                    AND NF.NRLANCTONF   = IP.NRLANCTONF
                    AND (IP.IDIMPOSTONF <> '3' OR IP.IDIMPOSTONF IS NULL)
                    AND IP.NRSEQMAPOIMP = P_NRSEQUMAPAPU
                  UNION ALL
                 SELECT N.IDENTRSAIDOP, IM.IDIMPORECUP, ROUND(I.VRPROPREC,2) AS VRCONTABIL,
                        ROUND(DECODE(I.CDFISCALNF,'1',I.VRPROPRECBC,0),2) AS VRBASECALC,
                        ROUND(DECODE(I.CDFISCALNF,'1',I.VRPROPRECBC*I.VRALIQNF/100, 0),2) AS VRIMPOSTO
                   FROM IMPBAIXAREC I, NOTAFISCAL N, IMPOSTO IM
                  WHERE IM.CDIMPOSTONFE = P_CDIMPOSTO
                    AND IM.CDIMPOSTO    = I.CDIMPOSTO
                    AND N.CDFILIAL      = I.CDFILIAL
                    AND N.NRLANCTONF    = I.NRLANCTONF
                    AND I.NRSEQMAPOIMP  = P_NRSEQUMAPAPU);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRCONTENTR := 0;
            V_VRBASEENTR := 0;
            V_VRIMPOENTR := 0;
            V_VRCONTSAID := 0;
            V_VRBASESAID := 0;
            V_VRIMPOSAID := 0;
      END;

      UPDATE MAPARECUP
         SET VRIMPCARGATRIBM = 0
       WHERE NRSEQUMAPAPU    = P_NRSEQUMAPAPU;

   /******** Impostos de Apuracao Normal ********/
   /******** Para o imposto 80 - ICMS ST, so pode haver credito na entrada se a empresa for Substituto Tributario ********/
   ELSIF  V_IDAPURACAO IN ('V','G','E','N') THEN
      BEGIN
         SELECT NVL(SUM(DECODE(IDENTRSAIDOP,'E',VRCONTABILNF,0)),0) AS VRCONTENTR,
                NVL(SUM(DECODE(IDENTRSAIDOP,'E',DECODE(P_CDIMPOSTO,'80',DECODE(IDREGIMEICMSST,'1',VRBASECALCNF,0),VRBASECALCNF),0)),0) AS VRBASEENTR,
                NVL(SUM(DECODE(IDENTRSAIDOP,'E',DECODE(P_CDIMPOSTO,'80',DECODE(IDREGIMEICMSST,'1',VRIMPOSTONF, 0),VRIMPOSTONF), 0)),0) AS VRIMPOENTR,
                NVL(SUM(DECODE(IDENTRSAIDOP,'S',VRCONTABILNF,0)),0) AS VRCONTSAID,
                NVL(SUM(DECODE(IDENTRSAIDOP,'S',VRBASECALCNF,0)),0) AS VRBASESAID,
                NVL(SUM(DECODE(IDENTRSAIDOP,'S',VRIMPOSTONF, 0)),0) AS VRIMPOSAID
           INTO V_VRCONTENTR, V_VRBASEENTR, V_VRIMPOENTR,
                V_VRCONTSAID, V_VRBASESAID, V_VRIMPOSAID
           FROM (SELECT NF.IDENTRSAIDOP, I.IDIMPORECUP, ROUND(IP.VRCONTABILNF,2) AS VRCONTABILNF,
                        ROUND(DECODE(IP.CDFISCALNF,'1',IP.VRBASECALCNF,0),2) AS VRBASECALCNF,
                        ROUND(DECODE(IP.CDFISCALNF,'1',IP.VRIMPOSTONF + DECODE( V_IDSOMAFECP, 'N', 0, 'S', NVL(IP.VRADICFECP,0) ), 0),2) AS VRIMPOSTONF,
                        E.IDREGIMEICMSST
                   FROM IMPOSTONF IP, IMPOSTO I, NOTAFISCAL NF, EMPRESA E
                  WHERE I.CDIMPOSTONFE   = P_CDIMPOSTO
                    AND IP.CDIMPOSTO     = I.CDIMPOSTO
                    AND IP.CDFILIAL      = NF.CDFILIAL
                    AND IP.NRLANCTONF    = NF.NRLANCTONF
                    AND ((IP.IDIMPOSTONF <> '3') OR (IP.IDIMPOSTONF IS NULL))
                    AND IP.NRSEQUMAPAPU  = P_NRSEQUMAPAPU
                    AND NF.CDEMPRESA     = E.CDEMPRESA
                  UNION ALL
                 SELECT N.IDENTRSAIDOP, IM.IDIMPORECUP, ROUND(I.VRPROPREC,2) AS VRCONTABIL,
                        ROUND(DECODE(I.CDFISCALNF,'1',I.VRPROPRECBC,0),2) AS VRBASECALC,
                        ROUND(DECODE(I.CDFISCALNF,'1',I.VRPROPRECBC*I.VRALIQNF/100, 0),2) AS VRIMPOSTO,
                        E.IDREGIMEICMSST
                   FROM IMPBAIXAREC I, NOTAFISCAL N, IMPOSTO IM, EMPRESA E
                  WHERE IM.CDIMPOSTONFE = P_CDIMPOSTO
                    AND I.CDIMPOSTO     = IM.CDIMPOSTO
                    AND I.CDFILIAL      = N.CDFILIAL
                    AND I.NRLANCTONF    = N.NRLANCTONF
                    AND I.NRSEQUMAPAPU  = P_NRSEQUMAPAPU
                    AND N.CDEMPRESA     = E.CDEMPRESA);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRCONTENTR := 0;
            V_VRBASEENTR := 0;
            V_VRIMPOENTR := 0;
            V_VRCONTSAID := 0;
            V_VRBASESAID := 0;
            V_VRIMPOSAID := 0;
      END;

      UPDATE MAPARECUP
         SET VRIMPCARGATRIBM = 0
       WHERE NRSEQUMAPAPU    = P_NRSEQUMAPAPU;

   /******** Apuracao com Carga Tributaria ********/
   ELSE /***** V_IDAPURACAO = 'C' *****/
      BEGIN
         SELECT NVL(VRCONTSAID,0), NVL(VRBASESAID,0), NVL(VRIMPOSAID,0), NVL(VRCONTENTR,0), NVL(VRBASEENTR,0), NVL(VRIMPOENTR,0)
           INTO V_VRCONTSAID, V_VRBASESAID, V_VRIMPOSAID, V_VRCONTENTR, V_VRBASEENTR, V_VRIMPOENTR

           /***** Carga Tributaria na Entrada *****/
           FROM (SELECT SUM(VRCONTABILNF) AS VRCONTENTR,
                        SUM(VRBASECALCNF) AS VRBASEENTR,
                        SUM(VRIMPOSTONF)  AS VRIMPOENTR
                   FROM (SELECT ROUND(IP.VRCONTABILNF,2) AS VRCONTABILNF,
                                0 AS VRBASECALCNF,
                                0 AS VRIMPOSTONF
                           FROM IMPOSTONF IP, IMPOSTO I, NOTAFISCAL NF
                          WHERE I.CDIMPOSTONFE   = P_CDIMPOSTO
                            AND NF.IDENTRSAIDOP  = 'E'
                            AND IP.CDIMPOSTO     = I.CDIMPOSTO
                            AND NF.CDFILIAL      = IP.CDFILIAL
                            AND NF.NRLANCTONF    = IP.NRLANCTONF
                            AND ((IP.IDIMPOSTONF <> '3') OR (IP.IDIMPOSTONF IS NULL))
                            AND IP.NRSEQUMAPAPU  = P_NRSEQUMAPAPU
                          UNION ALL
                         SELECT 0 AS VRCONTABIL,
                                VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL,N.NRLANCTONF,'B','I','1') AS VRBASECALCNF,
                                NVL(VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL,N.NRLANCTONF,'I','I','1'),0) +
                                NVL(VALOR_FECP_NFE(N.CDFILIAL,N.NRLANCTONF,'00','I','1'),0) +
                                NVL(DECODE(V_IDOUTCREDDEB,'S',0,VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL,N.NRLANCTONF,'I','C','1')),0) AS VRIMPOSTONF
                           FROM (SELECT DISTINCT IP.CDFILIAL, IP.NRLANCTONF
                                   FROM IMPOSTONF IP, IMPOSTO I, NOTAFISCAL NF
                                  WHERE I.CDIMPOSTONFE   = P_CDIMPOSTO
                                    AND NF.IDENTRSAIDOP  = 'E'
                                    AND IP.CDIMPOSTO     = I.CDIMPOSTO
                                    AND NF.CDFILIAL      = IP.CDFILIAL
                                    AND NF.NRLANCTONF    = IP.NRLANCTONF
                                    AND ((IP.IDIMPOSTONF <> '3') OR (IP.IDIMPOSTONF IS NULL))
                                    AND IP.NRSEQUMAPAPU  = P_NRSEQUMAPAPU)N))A,

                 /***** Carga Tributaria na Saida *****/
                 (SELECT SUM(VRCONTABILNF) AS VRCONTSAID,
                         SUM(VRBASECALCNF) AS VRBASESAID,
                         SUM(VRIMPOSTONF)  AS VRIMPOSAID
                    FROM (SELECT ROUND(IP.VRCONTABILNF,2) AS VRCONTABILNF,
                                 ROUND(DECODE(IP.CDFISCALNF,'1',IP.VRBASECALCNF,0),2) AS VRBASECALCNF,
                                 0  AS VRIMPOSTONF
                            FROM IMPOSTONF IP, IMPOSTO I, NOTAFISCAL NF
                           WHERE I.CDIMPOSTONFE  = P_CDIMPOSTO
                             AND NF.IDENTRSAIDOP = 'S'
                             AND IP.CDIMPOSTO    = I.CDIMPOSTO
                             AND NF.CDFILIAL     = IP.CDFILIAL
                             AND NF.NRLANCTONF   = IP.NRLANCTONF
                             AND ((IP.IDIMPOSTONF <> '3') OR (IP.IDIMPOSTONF IS NULL))
                             AND IP.NRSEQUMAPAPU = P_NRSEQUMAPAPU
                           UNION ALL
                          SELECT 0 AS VRCONTABILNF,
                                 DECODE(N.IDSISTEMA,'FIS',VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL,N.NRLANCTONF,'B','C','1'),0) AS VRBASECALCNF,
                                 NVL(VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL,N.NRLANCTONF,'I','I','1'),0) +
                                 NVL(VALOR_FECP_NFE(N.CDFILIAL,N.NRLANCTONF,'00','I','1'),0) +
                                 NVL(DECODE(N.IDSISTEMA,'FIS',VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL,N.NRLANCTONF,'I','C','1'),
                                                              DECODE(V_IDOUTCREDDEB,'S',0,VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL,N.NRLANCTONF,'I','C','1'))),0) AS VRIMPOSTONF
                            FROM (SELECT DISTINCT IP.CDFILIAL, IP.NRLANCTONF, NF.IDSISTEMA
                                   FROM IMPOSTONF IP, IMPOSTO I, NOTAFISCAL NF
                                  WHERE I.CDIMPOSTONFE   = P_CDIMPOSTO
                                    AND NF.IDENTRSAIDOP  = 'S'
                                    AND IP.CDIMPOSTO     = I.CDIMPOSTO
                                    AND NF.CDFILIAL      = IP.CDFILIAL
                                    AND NF.NRLANCTONF    = IP.NRLANCTONF
                                    AND ((IP.IDIMPOSTONF <> '3') OR (IP.IDIMPOSTONF IS NULL))
                                    AND IP.NRSEQUMAPAPU  = P_NRSEQUMAPAPU)N))B;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRCONTENTR := 0;
            V_VRBASEENTR := 0;
            V_VRIMPOENTR := 0;
            V_VRCONTSAID := 0;
            V_VRBASESAID := 0;
            V_VRIMPOSAID := 0;
      END;

      /******** Atualiza o Valor da Carga Tributaria no Mapa ********/
      UPDATE MAPARECUP
         SET VRIMPCARGATRIBM = (SELECT  VRSAIDA - VRENTRADA
                                  FROM (SELECT NVL((SELECT NVL(SUM(ROUND(I.VRIMPCARGATRIBI,2)),0)
                                                      FROM IMPOSTONF I
                                                     WHERE I.NRSEQUMAPAPU = P_NRSEQUMAPAPU
                                                       AND I.CDIMPOSTO    = P_CDIMPOSTO
                                                       AND SUBSTR(I.CDFISCOPERNF,1,1) IN ('5','6','7')),0) AS VRSAIDA,

                                               NVL((SELECT NVL(SUM(ROUND(I.VRIMPCARGATRIBI,2)),0)
                                                      FROM IMPOSTONF I
                                                     WHERE I.NRSEQUMAPAPU = P_NRSEQUMAPAPU
                                                       AND I.CDIMPOSTO    = P_CDIMPOSTO
                                                       AND SUBSTR(I.CDFISCOPERNF,1,1) IN ('1','2','3')),0) AS VRENTRADA
                                          FROM DUAL))
       WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU;
   END IF;

   /******** Atualiza a conta contabil dos itens do imposto ********/
   IF V_BOATUCTCTBL THEN
      ATUALIZA_CTBL_IMPOSTONF(P_NRSEQUMAPAPU, P_CDIMPOSTO);
   END IF;

   /******** Busca o credito de periodo anterior, para verificar se o mesmo foi alterado manualmente ********/
   BEGIN
      SELECT VRSLDCRANTE
        INTO V_VRSALDOCREDANT
        FROM MAPARECUP
       WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_VRSALDOCREDANT := NULL;
   END;

   /******** V_VRSALDOCREDANT := NVL(V_VRSALDOCREDANT,0);   ********/

   /******** Se o mapa nao possuia notas e o credito anterior e igual a zero,
             atualiza o campo com o valor de saldo credor do mapa anterior ********/

   /********IF (P_NOTASMAPA = 0) AND (V_VRSALDOCREDANT = 0) THEN********/

      /******** Busca o sequencial do mapa anterior ********/
      BEGIN
         SELECT MAX(M.NRSEQUMAPAPU)
           INTO V_SEQMAPAANT
           FROM MAPAAPURAC M, (SELECT NRSEQUMAPAPU, CDEMPRESA, CDINSCESTA, CDINSCMUNI, CDIMPOSTO
                                 FROM MAPAAPURAC
                                WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU) P
          WHERE M.CDEMPRESA    = P.CDEMPRESA
            AND M.CDIMPOSTO    = P.CDIMPOSTO
            AND (M.CDINSCESTA  = P.CDINSCESTA OR (M.CDINSCESTA IS NULL AND P.CDINSCESTA IS NULL))
            AND (M.CDINSCMUNI  = P.CDINSCMUNI OR (M.CDINSCMUNI IS NULL AND P.CDINSCMUNI IS NULL))
            AND M.NRSEQUMAPAPU < P.NRSEQUMAPAPU;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_SEQMAPAANT := NULL;
      END;

      /******** Busca o saldo credor do mapa anterior ********/
      BEGIN
         SELECT NVL(VRSALDOCRED,0) AS VRSALDOCRED
           INTO V_VRSALDOCREDANT
           FROM MAPARECUP
          WHERE NRSEQUMAPAPU = V_SEQMAPAANT;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRSALDOCREDANT := NULL;
      END;
   

   IF (V_IDIMPORECUPNFE = 'N') AND (P_CDIMPOSTO <> '80') THEN
      V_VRIMPOSAID := NVL(V_VRIMPOSAID,0)+NVL(V_VRIMPOENTR,0);
      V_VRIMPOENTR := 0;
   END IF;

   /******** Calcula os valores: Total Debitos, Total Creditos, Saldo Credor e Saldo Devedor  ********/
   V_VRTOTADEBI  := NVL(V_VRIMPOSAID,0) +  NVL(V_VROUTRDEBI,0) + NVL(V_VRESTOCRED,0);
   V_VRTOTACRED  := NVL(V_VRIMPOENTR,0) +  NVL(V_VROUTRCRED,0) + NVL(V_VRESTODEBI,0);
   V_VRSALDODEBI := NVL(V_VRTOTADEBI,0) - (NVL(V_VRTOTACRED,0) + NVL(V_VRSALDOCREDANT,0) + NVL(V_VRDEDUCAO,0));

   IF V_VRSALDODEBI < 0 THEN
      V_VRSALDOCRED := ABS(V_VRSALDODEBI);
      V_VRSALDODEBI := 0;
   ELSE
      V_VRSALDOCRED := 0;
   END IF;

   /***** Atualiza a tabela MAPARECUP *****/
   UPDATE MAPARECUP
      SET VRNORMDEBI   = V_VRIMPOSAID,
          VROUTRDEBI   = V_VROUTRDEBI,
          VRESTOCRED   = V_VRESTOCRED,
          VRTOTADEBI   = V_VRTOTADEBI,
          VRNORMCRED   = V_VRIMPOENTR,
          VROUTRCRED   = V_VROUTRCRED,
          VRESTODEBI   = V_VRESTODEBI,
          VRTOTACRED   = V_VRTOTACRED,
          VRSLDCRANTE  = NVL(V_VRSALDOCREDANT,VRSLDCRANTE),
          VRDEDUCAO    = V_VRDEDUCAO,
          VRDIFALIQU   = V_VRDIFALIQU,
          VRSALDOCRED  = V_VRSALDOCRED,
          VRSALDODEBI  = V_VRSALDODEBI
    WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU;

   /***** Atualiza a tabela MAPAAPURAC *****/
   UPDATE MAPAAPURAC
      SET VRTTCTBLDEB  = V_VRCONTSAID,
          VRTTBACALDEB = V_VRBASESAID,
          VRTTCTBLCRE  = V_VRCONTENTR,
          VRTTBACALCRE = V_VRBASEENTR,
          VRTOTAIMPOS  = V_VRSALDODEBI,
          IDFORMAPUR   = V_IDFORMAPURNFE
    WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU;

   RETURN(V_NFFORAPERIODO);
END;
/