CREATE OR REPLACE PROCEDURE CTB_IMPOSTO_DIFERENCIADO(
   P_CDFILIAL     IN FILIAL.CDFILIAL%TYPE,
   P_CDINSCESTA   IN INSCRESTAD.CDINSCESTA%TYPE,
   P_DTINICIAL    IN NOTAFISCAL.DTEMISSAO%TYPE,
   P_DTFINAL      IN NOTAFISCAL.DTEMISSAO%TYPE,
   P_CDEMPRESA    IN EMPRESA.CDEMPRESA%TYPE,
   P_CDHISTPADR   IN HISTPADR.CDHISTPADR%TYPE,
   P_CDLOTE       IN VARCHAR2,
   P_TIPO         IN VARCHAR2)
AS
  V_TESTE             VARCHAR2(50);
  V_PERCENTESTORN     NUMBER;
  V_VRPARTIDA         NUMBER;
  V_DSESTORNOCRED      VARCHAR2(200);
  V_DSESTORNODEBI      VARCHAR2(200);
  V_CDCONTCTBL        VARCHAR2(20);
  V_CONTCTBLREC       VARCHAR2(20);
  V_CONTCTBLPASS      VARCHAR2(20);
  V_CDCONTCTBOL       VARCHAR2(20);
  V_CONTCTBLATIV      VARCHAR2(20); 
  V_CDLOTE            VARCHAR2(20);
  V_NRLANCLOTE        VARCHAR2(6);
  V_IDCODCOMECONTEST  VARCHAR2(1);
  V_IDCODCOMECONTICM  VARCHAR2(1);
  V_CODCOMEEST        VARCHAR2(30);
  V_CODCOMEICM        VARCHAR2(30);
  V_IDGEROULOTE       VARCHAR2(1);
  V_DSHISTPADR        VARCHAR2(1000);
  V_CDCENTCUST        VARCHAR2(04);
  V_IDCONTCCUS        VARCHAR2(01);
  V_DATACONTABIL      DATE;
  V_NRNOTAFISC        VARCHAR2(50);
  V_NRLANCTEMP        VARCHAR2(20);
  V_COUNT              NUMBER;
  V_VRIMPOSTOSAIDA     NUMBER;
  V_VRIMPOSTOENTRADA   NUMBER;
  V_VRCTBENTRADA       NUMBER;
  V_VRDIFIMP           NUMBER;
  V_VRDIFERENCA        NUMBER;
  V_VRCONTABILIZADO    NUMBER;
  V_VRTOTCONTABSAID    NUMBER;
  V_VRTOTCONTABDEV     NUMBER;
  V_VRTOTCONTABDEVCOMP NUMBER;
  V_VRCOMPRAGAS        NUMBER;
  V_ALIQGAS            NUMBER;
  V_CDFILIOL           VARCHAR2(04);
  V_TPPARTIDA          VARCHAR2(01);
  V_CDGRUPOFISC        VARCHAR2(03);
BEGIN
   V_IDGEROULOTE  := 'N';
   V_DATACONTABIL := LAST_DAY(P_DTFINAL);
   /*TOTAL DE ENTRADAS = SOMATORIO DO IMPOSTOS DAS ENTRADAS POR FILIAL
     GLP   = SOMATORIO DO IMPOSTO DOS CFOPS DE GAS POR FILIAL
     TOTAL = ENTRADAS + GLP

     TOTAL DE SAIDAS = SOMATORIO DO IMPOSTOS DAS SAIDAS POR FILIAL

     DIFERENCA = TOTAL DE SAIDAS - TOTAL POR FILIAL

     PRESUMIDO = 40%DIFERENCA
     FISCAL    = 60%

     IMPOSTO A CONTABILIZAR = FISCAL - IMPOSTO CONTABILIZADO

     CASO IMPOSTO A CONTABILIZAR SEJA NEGATIVO O DEBITO NA CONTA DE ESTORNO E O CREDITO NA CONTA DO IMPOSTO A RECOLHER

     CASO IMPOSTO A CONTABILIZAR SEJA POSITIVO O CREDITO NA CONTA DE ESTORNO E O DEDITO NA CONTA DO IMPOSTO A RECOLHER
     */
   IF P_TIPO = '1' THEN /*ESTORNO CREDITO PRESUMIDO*/

      /*RETORNA OS PARAMETROS PARA A CONTABILIZACAO DO ESTORNO DE CREDITO PRESUMIDO*/
      BEGIN
         SELECT VRPERCENTEST, DSESTORNOCRED, CDCONTCTBL, VRPERCENTGAS, CDCONTCTBOL
           INTO V_PERCENTESTORN, V_DSESTORNOCRED, V_CDCONTCTBL, V_ALIQGAS, V_CDCONTCTBOL
           FROM ESTORNO
          WHERE CDINSCESTA = P_CDINSCESTA;
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
             V_PERCENTESTORN     := 0;
             V_ALIQGAS           := 0;
             V_DSESTORNOCRED     := NULL;
             V_CDCONTCTBL        := NULL;
             V_CDCONTCTBOL       := NULL;
      END;

      /*RETORNA AS FILIAIS DA INSCRICAO ESTADUAL INFORMADA*/
      FOR C_IMP_PE IN (SELECT DISTINCT CDFILIAL
                         FROM(SELECT NF.CDFILIEMIT AS CDFILIAL
                                FROM NOTAFISCAL  NF, IMPOSTONF IP, IMPOSTO IM
                               WHERE NF.CDINSCESTA   = P_CDINSCESTA
                                 AND NF.IDENTRSAIDOP = 'S'
                                 AND NF.DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL
                                 AND NF.CDEMPRESA    = P_CDEMPRESA
                                 AND NF.CDFILIAL     = IP.CDFILIAL
                                 AND NF.NRLANCTONF   = IP.NRLANCTONF
                                 AND IM.CDIMPOSTONFE = '00'
                                 AND IM.CDIMPOSTO    = IP.CDIMPOSTO
                               UNION ALL
                              SELECT NF.CDFILIRECE  AS CDFILIAL
                                FROM NOTAFISCAL  NF, IMPOSTONF IP, IMPOSTO IM
                               WHERE NF.CDINSCESTA   = P_CDINSCESTA
                                 AND NF.IDENTRSAIDOP = 'E'
                                 AND NF.DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL
                                 AND NF.CDEMPRESA    = P_CDEMPRESA
                                 AND NF.CDFILIAL     = IP.CDFILIAL
                                 AND NF.NRLANCTONF   = IP.NRLANCTONF
                                 AND IM.CDIMPOSTONFE = '00'
                                 AND IM.CDIMPOSTO    = IP.CDIMPOSTO)
                              ORDER BY CDFILIAL)LOOP
      V_VRDIFIMP    := 0;
      V_VRDIFERENCA := 0;
      V_VRPARTIDA   := 0;
      V_CDFILIOL    := NULL;
      /*CONTA DO PASSIVO*/
      V_CONTCTBLPASS := CONTCTBL_IMPOSTO('00', 'P', 'S', '', '');
      /*CONTA DO ATIVO*/
      V_CONTCTBLATIV  := CONTCTBL_IMPOSTO('00', 'A', 'S', '', '');
      /*TOTAL DO IMPOSTO DO GAS (GLP)*/
      BEGIN
        SELECT SUM(ROUND((VRCONTABILNF)*V_ALIQGAS/100,2)) AS VRCOMPRAGAS
          INTO V_VRCOMPRAGAS
          FROM IMPOSTONF I, IMPOSTO IM, NOTAFISCAL N
         WHERE I.CDFILIAL = N.CDFILIAL
           AND I.NRLANCTONF = N.NRLANCTONF
           AND IM.CDIMPOSTONFE  = '00'
           AND IM.CDIMPOSTO = I.CDIMPOSTO
           AND N.CDEMPRESA  = P_CDEMPRESA
           AND N.CDINSCESTA = P_CDINSCESTA
           AND N.IDENTRSAIDOP = 'E'
           AND CDFISCOPERNF  = '1653'
           AND N.NRLANCTBDOC IS NOT NULL
           AND N.DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL
           AND N.CDFILIRECE = C_IMP_PE.CDFILIAL;
      EXCEPTION WHEN NO_DATA_FOUND THEN
                    V_VRCOMPRAGAS := 0;
      END;

       /*TOTAL DOS IMPOSTOS ENTRADAS POR FILIAL*/
      BEGIN
        SELECT SUM(VRIMPOSTONF) AS VRIMPENTRADA
          INTO V_VRIMPOSTOENTRADA
          FROM IMPOSTONF I, IMPOSTO IM, NOTAFISCAL N
         WHERE I.CDFILIAL = N.CDFILIAL
           AND I.NRLANCTONF = N.NRLANCTONF
           AND I.CDIMPOSTO  = IM.CDIMPOSTO
           AND IM.CDIMPOSTONFE = '00'
           AND N.CDEMPRESA  = P_CDEMPRESA
           AND N.CDINSCESTA = P_CDINSCESTA
           AND N.IDENTRSAIDOP = 'E'
           AND N.NRLANCTBDOC IS NOT NULL
           AND I.CDFISCALNF = '1'
           AND N.DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL
           AND N.CDFILIRECE = C_IMP_PE.CDFILIAL;
      EXCEPTION WHEN NO_DATA_FOUND THEN
                    V_VRIMPOSTOENTRADA := 0;
      END;
       /*TOTAL DOS IMPOSTOS SAIDAS POR FILIAL*/
      BEGIN
        SELECT SUM(VRIMPOSTONF) AS VRIMPSAIDA
          INTO V_VRIMPOSTOSAIDA
          FROM IMPOSTONF I, IMPOSTO IM, NOTAFISCAL N
         WHERE I.CDFILIAL = N.CDFILIAL
           AND I.NRLANCTONF = N.NRLANCTONF
           AND I.CDIMPOSTO  = IM.CDIMPOSTO
           AND IM.CDIMPOSTONFE = '00'
           AND N.CDEMPRESA  = P_CDEMPRESA
           AND N.CDINSCESTA = P_CDINSCESTA
           AND N.IDENTRSAIDOP = 'S'
           AND N.NRLANCTBDOC IS NOT NULL
           AND N.DTEMISSAO BETWEEN P_DTINICIAL AND P_DTFINAL
           AND N.CDFILIEMIT = C_IMP_PE.CDFILIAL;
      EXCEPTION WHEN NO_DATA_FOUND THEN
                    V_VRIMPOSTOSAIDA := 0;
      END;
       /*TOTAL DAS SAIDAS QUE FORAM CONTABILIZADAS FILIAL*/
      BEGIN
      SELECT SUM(VRLANCAMENT) AS VRIMPSAIDA
        INTO V_VRTOTCONTABSAID
        FROM NOTAFISCAL N, LANCCONT L, (SELECT DISTINCT CDFILIAL, NRLANCTONF
                                          FROM IMPOSTONF I, IMPOSTO IM
                                         WHERE IM.CDIMPOSTONFE = '00'
                                           AND I.CDIMPOSTO = IM.CDIMPOSTO) I
         WHERE I.CDFILIAL = N.CDFILIAL
           AND I.NRLANCTONF = N.NRLANCTONF
           AND N.CDEMPRESA  = P_CDEMPRESA
           AND N.CDINSCESTA = P_CDINSCESTA
           AND N.IDENTRSAIDOP = 'S'
           AND N.NRLANCTBDOC = L.NRLANCCONT
           AND N.CDEMPRESA   = L.CDEMPRESA
           AND N.DTEMISSAO BETWEEN P_DTINICIAL AND P_DTFINAL
           AND L.CDCONTCTBL  = V_CONTCTBLPASS
           AND N.CDFILIEMIT = C_IMP_PE.CDFILIAL;
      EXCEPTION WHEN NO_DATA_FOUND THEN
                    V_VRIMPOSTOSAIDA := 0;
      END;
      /*TOTAL DA DEVOLUCAO DE COMPRAS CONTABILIZADO*/
       BEGIN
      SELECT SUM(VRLANCAMENT) AS VRIMPSAIDA
        INTO V_VRTOTCONTABDEVCOMP
        FROM NOTAFISCAL N, LANCCONT L, (SELECT DISTINCT CDFILIAL, NRLANCTONF
                                          FROM IMPOSTONF I, IMPOSTO IM, CFOPPADRAO C
                                         WHERE IM.CDIMPOSTONFE  = '00'
                                           AND C.CDCFOPPADRAO   = I.CDFISCOPERNF
                                           AND C.IDTIPOCFOP     = 'D'
                                           AND I.CDIMPOSTO      = IM.CDIMPOSTO) I
         WHERE I.CDFILIAL = N.CDFILIAL
           AND I.NRLANCTONF = N.NRLANCTONF
           AND N.CDEMPRESA  = P_CDEMPRESA
           AND N.CDINSCESTA = P_CDINSCESTA
           AND N.IDENTRSAIDOP = 'S'
           AND N.NRLANCTBDOC = L.NRLANCCONT
           AND N.CDEMPRESA   = L.CDEMPRESA
           AND N.DTEMISSAO BETWEEN P_DTINICIAL AND P_DTFINAL
           AND L.CDCONTCTBL  = V_CONTCTBLATIV
           AND N.CDFILIEMIT = C_IMP_PE.CDFILIAL;
      EXCEPTION WHEN NO_DATA_FOUND THEN
                    V_VRTOTCONTABDEV := 0;
      END;
      /*TOTAL DA DEVOLUCAO DE VENDA*/
       BEGIN
      SELECT SUM(VRLANCAMENT) AS VRIMPSAIDA
        INTO V_VRTOTCONTABDEV
        FROM NOTAFISCAL N, LANCCONT L, (SELECT DISTINCT CDFILIAL, NRLANCTONF
                                          FROM IMPOSTONF I, IMPOSTO IM, CFOPPADRAO C
                                         WHERE IM.CDIMPOSTONFE  = '00'
                                           AND C.CDCFOPPADRAO   = I.CDFISCOPERNF
                                           AND C.IDTIPOCFOP     = 'D'
                                           AND I.CDIMPOSTO      = IM.CDIMPOSTO) I
         WHERE I.CDFILIAL = N.CDFILIAL
           AND I.NRLANCTONF = N.NRLANCTONF
           AND N.CDEMPRESA  = P_CDEMPRESA
           AND N.CDINSCESTA = P_CDINSCESTA
           AND N.IDENTRSAIDOP = 'E'
           AND N.NRLANCTBDOC = L.NRLANCCONT
           AND N.CDEMPRESA   = L.CDEMPRESA
           AND N.DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL
           AND L.CDCONTCTBL  = V_CONTCTBLPASS
           AND N.CDFILIRECE = C_IMP_PE.CDFILIAL;
      EXCEPTION WHEN NO_DATA_FOUND THEN
                    V_VRTOTCONTABDEV := 0;
      END;
         /*VERIFICA DIFERENCA ENTRE O IMPOSTO DAS ENTRADAS MAIS O VALOR DO GAS E DAS SAIDAS*/
         V_VRDIFIMP   := ROUND(NVL(V_VRIMPOSTOSAIDA,0) - (NVL(V_VRIMPOSTOENTRADA,0)+ NVL(V_VRCOMPRAGAS,0)),2);
         /*CALCULA O CREDITO PRESUMIDO*/
         V_VRDIFERENCA  := ROUND(NVL(V_VRDIFIMP,0)*NVL(V_PERCENTESTORN,0)/100,2);
         /*VALOR QUE FOI CONTABILIZADO MAIS AS DEVOLUCOES MENOS O TOTAL DE ENTRADAS MAIS O GAS */
         V_VRCONTABILIZADO := ROUND((NVL(V_VRTOTCONTABSAID,0) + NVL(V_VRTOTCONTABDEV,0) + NVL(V_VRTOTCONTABDEVCOMP,0)) - (NVL(V_VRIMPOSTOENTRADA,0)+ NVL(V_VRCOMPRAGAS,0)),2);
         /*VALOR DA PARTIDA E O VALOR DO CREDITO PRESUMIDO - O VALOR QUE FOI CONTABILIZADO*/
         V_VRPARTIDA := ROUND(NVL(V_VRDIFERENCA,0) - NVL(V_VRCONTABILIZADO,0),2);

         V_NRNOTAFISC := '00PE'||C_IMP_PE.CDFILIAL;

            /*MONTA O HISTORICO DO LANCAMENTO*/
         MONTA_HISTORICO(C_IMP_PE.CDFILIAL, P_CDINSCESTA ,P_CDHISTPADR,'',V_DATACONTABIL,'13', '', V_DSHISTPADR);
           /*GERA LOTE CONTABIL*/
         GERA_LOTECONTABIL(P_CDEMPRESA,'01',C_IMP_PE.CDFILIAL,'',V_DATACONTABIL,'','',V_CDLOTE,V_NRLANCLOTE,P_CDLOTE);

          BEGIN
            SELECT DISTINCT CDFILIAL
              INTO V_CDFILIOL
              FROM FILIAL
             WHERE CDFILIAL = C_IMP_PE.CDFILIAL
               AND IDFUNCAOFILI = 'O';
           EXCEPTION WHEN NO_DATA_FOUND THEN
                        V_CDFILIOL := NULL;

          END;
         IF V_CDFILIOL IS NOT NULL THEN
            V_CDCONTCTBL := V_CDCONTCTBOL;
         ELSE
            V_CDCONTCTBL := V_CDCONTCTBL;
         END IF;
         IF V_VRPARTIDA IS NOT NULL THEN
            IF V_VRPARTIDA > 0 THEN
               /*INSERE A TABELA PARA EXIBIR O RELATORIO*/
                INSERT INTO CTB_TEMP_CREDPRES (CDFILIAL, VRTOTENTRADAS, VRTOTSAIDAS, VRCREDPRES,
                                               VRGLP, VRSAIDCONTAB, CDCONTCTBLDEB, CDCONTCTBLCRED )
                      VALUES (C_IMP_PE.CDFILIAL, NVL(V_VRIMPOSTOENTRADA,0),  NVL(V_VRIMPOSTOSAIDA,0), V_VRDIFERENCA,
                                             NVL(V_VRCOMPRAGAS,0), nvl(V_VRPARTIDA,0), V_CDCONTCTBL, V_CONTCTBLPASS);

              /*DEBITA CONTA DE ESTORNO*/
                NOVA_PARTIDA(P_CDEMPRESA,V_CDLOTE,V_DATACONTABIL,V_NRLANCLOTE,  V_CDCONTCTBL, P_CDHISTPADR,
                           NVL(V_DSHISTPADR,V_DSESTORNOCRED), nvl(V_VRPARTIDA,0)*-1, V_IDCODCOMECONTEST, V_CODCOMEEST, '',V_NRNOTAFISC, 'N');

              /*VERIFICA O CENTRO DE CUSTO PARAMETRIZADO*/
                BEGIN
                   SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                     INTO V_CDCENTCUST
                     FROM FILIAL F, EMPRESA E
                    WHERE F.CDFILIAL  = C_IMP_PE.CDFILIAL
                      AND E.CDEMPRESA = P_CDEMPRESA;
                EXCEPTION
                   WHEN NO_DATA_FOUND THEN
                      V_CDCENTCUST := NULL;
                END;
                /*INSERE RATEIO DA PARTIDA DE ESTORNO*/
                IF V_CDCENTCUST IS NOT NULL THEN
                  RATEIO_PARTIDA(P_CDEMPRESA,V_CDLOTE,V_DATACONTABIL,V_NRLANCLOTE,C_IMP_PE.CDFILIAL,
                                 V_CDCENTCUST, nvl(V_VRPARTIDA,0)*-1);
                END IF;

                /* CREDITA CONTA CONTABIL DE DESPESA */
                 NOVA_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, V_CONTCTBLPASS, P_CDHISTPADR,
                               NVL(V_DSHISTPADR,V_DSESTORNOCRED), nvl(V_VRPARTIDA,0), V_IDCODCOMECONTICM, V_CODCOMEICM, '', V_NRNOTAFISC, 'N');

                /*VERIFICA O CENTRO DE CUSTO CADASTRADO*/
                BEGIN
                   SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                     INTO V_CDCENTCUST
                     FROM FILIAL F, EMPRESA E
                    WHERE F.CDFILIAL  = C_IMP_PE.CDFILIAL
                      AND E.CDEMPRESA = P_CDEMPRESA;
                EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                      V_CDCENTCUST := NULL;
                END;
                /*VERIFICA SE A CONTA CONTABIL E OFICIAL/GERENCIAL E GERENCIAL*/
                BEGIN
                 SELECT IDCONTCCUS
                   INTO V_IDCONTCCUS
                   FROM CONTCTBL
                  WHERE CDCONTCTBL = V_CONTCTBLPASS;
                EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                    V_IDCONTCCUS := NULL;
                END;

                IF V_CDCENTCUST IS NOT NULL THEN
                   IF V_IDCONTCCUS <> 'O' THEN
                    RATEIO_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, C_IMP_PE.CDFILIAL,
                                   V_CDCENTCUST, nvl(V_VRPARTIDA,0));
                   END IF;
                END IF;
            ELSIF V_VRPARTIDA < 0 THEN
              /*INSERE A TABELA PARA EXIBIR O RELATORIO*/
                INSERT INTO CTB_TEMP_CREDPRES (CDFILIAL, VRTOTENTRADAS, VRTOTSAIDAS, VRCREDPRES,
                                               VRGLP, VRSAIDCONTAB, CDCONTCTBLDEB, CDCONTCTBLCRED )
                     VALUES (C_IMP_PE.CDFILIAL, NVL(V_VRIMPOSTOENTRADA,0),  NVL(V_VRIMPOSTOSAIDA,0), V_VRDIFERENCA,
                             NVL(V_VRCOMPRAGAS,0), nvl(V_VRPARTIDA,0), V_CONTCTBLPASS, V_CDCONTCTBL);

                /*CREDITA CONTA DE ESTORNO*/
                NOVA_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, V_CDCONTCTBL, P_CDHISTPADR,
                            NVL(V_DSHISTPADR,V_DSESTORNOCRED), nvl(V_VRPARTIDA,0)*-1, V_IDCODCOMECONTEST, V_CODCOMEEST, '',V_NRNOTAFISC, 'N');

                /*VERIFICA O CENTRO DE CUSTO PARAMETRIZADO*/
                BEGIN
                   SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                     INTO V_CDCENTCUST
                     FROM FILIAL F, EMPRESA E
                    WHERE F.CDFILIAL  = C_IMP_PE.CDFILIAL
                      AND E.CDEMPRESA = P_CDEMPRESA;
                EXCEPTION
                   WHEN NO_DATA_FOUND THEN
                      V_CDCENTCUST := NULL;
                END;
                /*INSERE RATEIO DA PARTIDA DE ESTORNO*/
                IF V_CDCENTCUST IS NOT NULL THEN
                  RATEIO_PARTIDA(P_CDEMPRESA,V_CDLOTE,V_DATACONTABIL,V_NRLANCLOTE,C_IMP_PE.CDFILIAL,
                                 V_CDCENTCUST, V_VRPARTIDA*-1);
                END IF;

                /* CREDITA CONTA CONTABIL DE DESPESA */
                  NOVA_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, V_CONTCTBLPASS, P_CDHISTPADR,
                               NVL(V_DSHISTPADR,V_DSESTORNOCRED), nvl(V_VRPARTIDA,0), V_IDCODCOMECONTICM, V_CODCOMEICM, '', V_NRNOTAFISC, 'N');

                /*VERIFICA O CENTRO DE CUSTO CADASTRADO*/
                BEGIN
                   SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                     INTO V_CDCENTCUST
                     FROM FILIAL F, EMPRESA E
                    WHERE F.CDFILIAL  = C_IMP_PE.CDFILIAL
                      AND E.CDEMPRESA = P_CDEMPRESA;
                EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                      V_CDCENTCUST := NULL;
                END;
                /*VERIFICA SE A CONTA CONTABIL E OFICIAL/GERENCIAL E GERENCIAL*/
                BEGIN
                 SELECT IDCONTCCUS
                   INTO V_IDCONTCCUS
                   FROM CONTCTBL
                  WHERE CDCONTCTBL = V_CONTCTBLPASS;
                EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                    V_IDCONTCCUS := NULL;
                END;

                IF V_CDCENTCUST IS NOT NULL THEN
                   IF V_IDCONTCCUS <> 'O' THEN
                    RATEIO_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, C_IMP_PE.CDFILIAL,
                                   V_CDCENTCUST, nvl(V_VRPARTIDA,0));
                   END IF;
                END IF;

            END IF;
         END IF;
      END LOOP;
         /*CRED ICMS 3,9%*/
   ELSIF P_TIPO = '2' THEN
         /*RETORNA OS PARAMETROS PARA A CONTABILIZACAO DO ESTORNO DE ICMS 3.9*/
         BEGIN
            SELECT VRPERCENTEST, DSESTORNOCRED, CDCONTCTBL
              INTO V_PERCENTESTORN, V_DSESTORNOCRED, V_CDCONTCTBL
              FROM ESTORNO
             WHERE CDINSCESTA = P_CDINSCESTA;
         EXCEPTION
              WHEN NO_DATA_FOUND THEN
                V_PERCENTESTORN     := 0;
                V_DSESTORNOCRED := NULL;
                V_CDCONTCTBL        := NULL;
         END;

         FOR C_IMP_SP IN (SELECT DISTINCT NF.CDFILIRECE  AS CDFILIAL
                            FROM NOTAFISCAL  NF, IMPOSTONF IP, IMPOSTO IM
                           WHERE NF.CDINSCESTA   = P_CDINSCESTA
                             AND NF.IDENTRSAIDOP = 'E'
                             AND NF.DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL
                             AND NF.CDEMPRESA    = P_CDEMPRESA
                             AND NF.CDFILIAL     = IP.CDFILIAL
                             AND NF.NRLANCTONF   = IP.NRLANCTONF
                             AND IM.CDIMPOSTONFE = '00'
                             AND IM.CDIMPOSTO    = IP.CDIMPOSTO
                           ORDER BY NF.CDFILIRECE)LOOP


                /*CONTA DO PASSIVO*/
                V_CONTCTBLPASS := CONTCTBL_IMPOSTO('00', 'P', 'S', '', '');

                /*TOTAL DOS VALOR CONTABIL DAS ENTRADAS POR FILIAL*/
                BEGIN
                  SELECT SUM(VRCONTABILNF) AS VRCTBENTRADA
                    INTO V_VRCTBENTRADA
                    FROM IMPOSTONF I, IMPOSTO IM, NOTAFISCAL N
                   WHERE I.CDFILIAL = N.CDFILIAL
                     AND I.NRLANCTONF = N.NRLANCTONF
                     AND I.CDIMPOSTO  = IM.CDIMPOSTO
                     AND IM.CDIMPOSTONFE = '00'
                     AND N.CDEMPRESA  = P_CDEMPRESA
                     AND N.CDINSCESTA = P_CDINSCESTA
                     AND N.IDENTRSAIDOP = 'E'
                     AND SUBSTR(I.CDFISCOPERNF,2,3) IN ('403','409')
                     AND N.NRLANCTBDOC IS NOT NULL
                     AND N.DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL
                     AND N.CDFILIRECE = C_IMP_SP.CDFILIAL;
                EXCEPTION WHEN NO_DATA_FOUND THEN
                              V_VRCTBENTRADA := 0;
                END;

                /*CALCULA O VALOR DO ESTORNO DAS ENTRADAS*/
                V_VRDIFERENCA := ROUND(NVL(V_VRCTBENTRADA,0)*NVL(V_PERCENTESTORN,0),2/100);

                V_NRNOTAFISC := '00SP'||C_IMP_SP.CDFILIAL;

                /*MONTA O HISTORICO DO LANCAMENTO*/
                MONTA_HISTORICO(C_IMP_SP.CDFILIAL, P_CDINSCESTA ,P_CDHISTPADR,'',V_DATACONTABIL,'13', '', V_DSHISTPADR);

                /*GERA LOTE CONTABIL*/
                GERA_LOTECONTABIL(P_CDEMPRESA,'01',C_IMP_SP.CDFILIAL,'',V_DATACONTABIL,'','',V_CDLOTE,V_NRLANCLOTE,P_CDLOTE);

           IF V_VRPARTIDA > 0 THEN
              /*INSERE A TABELA PARA EXIBIR O RELATORIO*/
              INSERT INTO CTB_TEMP_CREDPRES (CDFILIAL, VRTOTENTRADAS, VRCREDPRES,  CDCONTCTBLDEB, CDCONTCTBLCRED )
                   VALUES (C_IMP_SP.CDFILIAL, NVL(V_VRIMPOSTOENTRADA,0), V_VRPARTIDA, V_CDCONTCTBL, V_CONTCTBLPASS);

              /*DEBITA CONTA DE ESTORNO*/
              NOVA_PARTIDA(P_CDEMPRESA,V_CDLOTE,V_DATACONTABIL,V_NRLANCLOTE,  V_CDCONTCTBL, P_CDHISTPADR,
                         NVL(V_DSHISTPADR,V_DSESTORNOCRED), V_VRPARTIDA*-1, V_IDCODCOMECONTEST, V_CODCOMEEST, '',V_NRNOTAFISC, 'N');

              /*VERIFICA O CENTRO DE CUSTO PARAMETRIZADO*/
              BEGIN
                 SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                   INTO V_CDCENTCUST
                   FROM FILIAL F, EMPRESA E
                  WHERE F.CDFILIAL  = C_IMP_SP.CDFILIAL
                    AND E.CDEMPRESA = P_CDEMPRESA;
              EXCEPTION
                 WHEN NO_DATA_FOUND THEN
                    V_CDCENTCUST := NULL;
              END;

              /*INSERE RATEIO DA PARTIDA DE ESTORNO*/
              IF V_CDCENTCUST IS NOT NULL THEN
                RATEIO_PARTIDA(P_CDEMPRESA,V_CDLOTE,V_DATACONTABIL,V_NRLANCLOTE,C_IMP_SP.CDFILIAL,
                               V_CDCENTCUST, V_VRPARTIDA*-1);
              END IF;

              /* CREDITA CONTA CONTABIL DE DESPESA */
               NOVA_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, V_CONTCTBLPASS, P_CDHISTPADR,
                             NVL(V_DSHISTPADR,V_DSESTORNOCRED), V_VRPARTIDA, V_IDCODCOMECONTICM, V_CODCOMEICM, '', V_NRNOTAFISC, 'N');

              /*VERIFICA O CENTRO DE CUSTO CADASTRADO*/
              BEGIN
                 SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                   INTO V_CDCENTCUST
                   FROM FILIAL F, EMPRESA E
                  WHERE F.CDFILIAL  = C_IMP_SP.CDFILIAL
                    AND E.CDEMPRESA = P_CDEMPRESA;
              EXCEPTION
                   WHEN NO_DATA_FOUND THEN
                    V_CDCENTCUST := NULL;
              END;

              /*VERIFICA SE A CONTA CONTABIL E OFICIAL/GERENCIAL E GERENCIAL*/
              BEGIN
               SELECT IDCONTCCUS
                 INTO V_IDCONTCCUS
                 FROM CONTCTBL
                WHERE CDCONTCTBL = V_CONTCTBLPASS;
              EXCEPTION
                WHEN NO_DATA_FOUND THEN
                  V_IDCONTCCUS := NULL;
              END;

              IF V_CDCENTCUST IS NOT NULL THEN
                 IF V_IDCONTCCUS <> 'O' THEN
                  RATEIO_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, C_IMP_SP.CDFILIAL,
                                 V_CDCENTCUST, V_VRPARTIDA);
                 END IF;
              END IF;
           END IF;
        END LOOP;
        /*ESTORNO - BA*/
   ELSIF P_TIPO = '3' THEN
     /*RETORNA OS PARAMETROS PARA A CONTABILIZACAO DO ESTORNO DE CREDITO PRESUMIDO*/
      BEGIN
         SELECT VRPERCENTEST, DSESTORNOCRED, DSESTORNODEBI, CDCONTCTBL, CDGRUPOFISC
           INTO V_PERCENTESTORN, V_DSESTORNOCRED, V_DSESTORNODEBI, V_CDCONTCTBL, V_CDGRUPOFISC
           FROM ESTORNO
          WHERE CDINSCESTA = P_CDINSCESTA;
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
             V_PERCENTESTORN     := 0;
             V_DSESTORNOCRED     := NULL;
             V_CDCONTCTBL        := NULL;
             V_CDGRUPOFISC       := NULL;
      END;

      /*RETORNA AS FILIAIS DA INSCRICAO ESTADUAL INFORMADA*/
      FOR C_IMP_BA IN (SELECT DISTINCT CDFILIAL
                         FROM(SELECT NF.CDFILIEMIT AS CDFILIAL
                                FROM NOTAFISCAL  NF, IMPOSTONF IP, IMPOSTO IM
                               WHERE NF.CDINSCESTA   = P_CDINSCESTA
                                 AND NF.IDENTRSAIDOP = 'S'
                                 AND NF.DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL
                                 AND NF.CDEMPRESA    = P_CDEMPRESA
                                 AND NF.CDFILIAL     = IP.CDFILIAL
                                 AND NF.NRLANCTONF   = IP.NRLANCTONF
                                 AND IM.CDIMPOSTONFE = '00'
                                 AND IM.CDIMPOSTO    = IP.CDIMPOSTO)
                        ORDER BY CDFILIAL)LOOP
         V_VRDIFIMP    := 0;
         V_VRDIFERENCA := 0;
         V_VRPARTIDA   := 0;

         /*CONTA DO PASSIVO*/
         V_CONTCTBLPASS := CONTCTBL_IMPOSTO('00', 'P', 'S', '', '');

          /*TOTAL DO IMPOSTOS DAS SAIDAS POR FILIAL*/
         BEGIN
           SELECT SUM(VRIMPOSTONF) AS VRIMPSAIDA
             INTO V_VRIMPOSTOSAIDA
             FROM IMPOSTONF I, IMPOSTO IM, NOTAFISCAL N
            WHERE I.CDFILIAL = N.CDFILIAL
              AND I.NRLANCTONF = N.NRLANCTONF
              AND I.CDIMPOSTO  = IM.CDIMPOSTO
              AND IM.CDIMPOSTONFE = '00'
              AND N.CDEMPRESA  = P_CDEMPRESA
              AND N.CDINSCESTA = P_CDINSCESTA
              AND N.IDENTRSAIDOP = 'S'
              AND N.NRLANCTBDOC IS NOT NULL
              AND I.CDFISCALNF = '1'
              AND SUBSTR(I.CDFISCOPERNF,2,3) = '102'
              AND N.DTEMISSAO BETWEEN P_DTINICIAL AND P_DTFINAL
              AND N.CDFILIEMIT = C_IMP_BA.CDFILIAL;
         EXCEPTION WHEN NO_DATA_FOUND THEN
                       V_VRIMPOSTOSAIDA := 0;
         END;

          /*CALCULO DO IMPOSTOS DAS SAIDAS COM CODIGO FISCAL 3*/
         BEGIN
           SELECT SUM(ROUND(VRCONTABILNF*NVL(V_PERCENTESTORN,0)/100,2)) AS VRIMPSAIDA
             INTO V_VRTOTCONTABSAID
             FROM IMPOSTONF I, IMPOSTO IM, NOTAFISCAL N, CLIENTE CL, (SELECT A.CDCLIENTE, A.CDGRUPOFISC
                                                                        FROM GRFISIMPIECLIE A, IMPOSTO IM, GRUPOFISCAL G
                                                                       WHERE A.CDEMPRESA = P_CDEMPRESA
                                                                         AND A.CDINSCESTA = P_CDINSCESTA
                                                                         AND A.CDGRUPOFISC = G.CDGRUPOFISC
                                                                         AND A.CDIMPOSTO   = IM.CDIMPOSTO
                                                                         AND IM.CDIMPOSTONFE = '00') GC
            WHERE I.CDFILIAL = N.CDFILIAL
              AND I.NRLANCTONF = N.NRLANCTONF
              AND I.CDIMPOSTO  = IM.CDIMPOSTO
              AND CL.CDCLIENTE = N.CDCLIENTE
              AND (CL.CDGRUPOFISC = V_CDGRUPOFISC or GC.CDGRUPOFISC = V_CDGRUPOFISC)
              AND CL.CDCLIENTE = GC.CDCLIENTE(+)
              AND IM.CDIMPOSTONFE = '00'
              AND N.CDEMPRESA  = P_CDEMPRESA
              AND N.CDINSCESTA = P_CDINSCESTA
              AND N.IDENTRSAIDOP = 'S'
              AND N.NRLANCTBDOC IS NOT NULL
              AND I.CDFISCALNF = '3'
              AND SUBSTR(I.CDFISCOPERNF,2,3) = '102'
              AND N.DTEMISSAO BETWEEN P_DTINICIAL AND P_DTFINAL
              AND N.CDFILIEMIT = C_IMP_BA.CDFILIAL;
         EXCEPTION WHEN NO_DATA_FOUND THEN
                       V_VRTOTCONTABSAID := 0;
         END;

          /*TOTAL DAS SAIDAS QUE FORAM CONTABILIZADAS FILIAL*/
         BEGIN
           SELECT SUM(VRLANCAMENT) AS VRIMPSAIDA
             INTO V_VRCONTABILIZADO
             FROM NOTAFISCAL N, LANCCONT L, (SELECT DISTINCT CDFILIAL, NRLANCTONF
                                               FROM IMPOSTONF I, IMPOSTO IM
                                              WHERE IM.CDIMPOSTONFE = '00'
                                                AND I.CDIMPOSTO = IM.CDIMPOSTO
												AND SUBSTR(I.CDFISCOPERNF,2,3) = '102') I
          WHERE I.CDFILIAL = N.CDFILIAL
              AND I.NRLANCTONF = N.NRLANCTONF
              AND N.CDEMPRESA  = P_CDEMPRESA
              AND N.CDINSCESTA = P_CDINSCESTA
              AND N.IDENTRSAIDOP = 'S'
              AND N.NRLANCTBDOC = L.NRLANCCONT
              AND N.CDEMPRESA   = L.CDEMPRESA
              AND N.DTEMISSAO BETWEEN P_DTINICIAL AND P_DTFINAL
              AND L.CDCONTCTBL  = V_CONTCTBLPASS
              AND N.CDFILIEMIT = C_IMP_BA.CDFILIAL;
         EXCEPTION WHEN NO_DATA_FOUND THEN
                       V_VRCONTABILIZADO := 0;
         END;
         /*SOMA TOTAL DO IMPOSTO*/
         V_VRDIFERENCA   := NVL(V_VRIMPOSTOSAIDA,0) + NVL(V_VRTOTCONTABSAID,0);

         /*CALCULA O VALOR DA PARTIDA*/
         V_VRPARTIDA := NVL(V_VRCONTABILIZADO,0) - NVL(V_VRDIFERENCA,0);

         V_NRNOTAFISC := '00BA'||C_IMP_BA.CDFILIAL;
         IF NVL(V_VRPARTIDA,0) >= 0.01 THEN
            V_TPPARTIDA := 'D';
         ELSIF NVL(V_VRPARTIDA,0) <= 0.01 THEN
            V_TPPARTIDA := 'C';
         END IF;
         /*MONTA O HISTORICO DO LANCAMENTO*/
         MONTA_HISTORICO(C_IMP_BA.CDFILIAL, P_CDINSCESTA ,P_CDHISTPADR,'',V_DATACONTABIL,'13', V_TPPARTIDA, V_DSHISTPADR);

         /*GERA LOTE CONTABIL*/
         GERA_LOTECONTABIL(P_CDEMPRESA,'01',C_IMP_BA.CDFILIAL,'',V_DATACONTABIL,'','',V_CDLOTE,V_NRLANCLOTE,P_CDLOTE);
         IF V_VRPARTIDA IS NOT NULL THEN
             IF V_VRPARTIDA > 0 THEN
                 /*INSERE A TABELA PARA EXIBIR O RELATORIO*/
                 INSERT INTO CTB_TEMP_CREDPRES (CDFILIAL,  VRTOTSAIDAS, VRCREDPRES, CDCONTCTBLDEB, CDCONTCTBLCRED )
                       VALUES (C_IMP_BA.CDFILIAL, V_VRDIFERENCA, V_VRPARTIDA, V_CONTCTBLPASS, V_CDCONTCTBL);

                 /*DEBITA CONTA DE IMPOSTO A RECOLHER*/
                 NOVA_PARTIDA(P_CDEMPRESA,V_CDLOTE,V_DATACONTABIL,V_NRLANCLOTE,  V_CONTCTBLPASS, P_CDHISTPADR,
                            NVL(V_DSHISTPADR,V_DSESTORNOCRED), V_VRPARTIDA*-1, V_IDCODCOMECONTEST, V_CODCOMEEST, '',V_NRNOTAFISC, 'N');

                 /*VERIFICA O CENTRO DE CUSTO PARAMETRIZADO*/
                 BEGIN
                    SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                      INTO V_CDCENTCUST
                      FROM FILIAL F, EMPRESA E
                     WHERE F.CDFILIAL  = C_IMP_BA.CDFILIAL
                       AND E.CDEMPRESA = P_CDEMPRESA;
                 EXCEPTION
                    WHEN NO_DATA_FOUND THEN
                       V_CDCENTCUST := NULL;
                 END;

                 /*INSERE RATEIO DA PARTIDA DE ESTORNO*/
                 IF V_CDCENTCUST IS NOT NULL THEN
                   RATEIO_PARTIDA(P_CDEMPRESA,V_CDLOTE,V_DATACONTABIL,V_NRLANCLOTE,C_IMP_BA.CDFILIAL,
                                  V_CDCENTCUST, V_VRPARTIDA*-1);
                 END IF;

                 /* CREDITA CONTA DE ESTORNO */
                  NOVA_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, V_CDCONTCTBL, P_CDHISTPADR,
                                NVL(V_DSHISTPADR,V_DSESTORNOCRED), V_VRPARTIDA, V_IDCODCOMECONTICM, V_CODCOMEICM, '', V_NRNOTAFISC, 'N');

                 /*VERIFICA O CENTRO DE CUSTO CADASTRADO*/
                 BEGIN
                    SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                      INTO V_CDCENTCUST
                      FROM FILIAL F, EMPRESA E
                     WHERE F.CDFILIAL  = C_IMP_BA.CDFILIAL
                       AND E.CDEMPRESA = P_CDEMPRESA;
                 EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDCENTCUST := NULL;
                 END;

                 /*VERIFICA SE A CONTA CONTABIL E OFICIAL/GERENCIAL E GERENCIAL*/
                 BEGIN
                  SELECT IDCONTCCUS
                    INTO V_IDCONTCCUS
                    FROM CONTCTBL
                   WHERE CDCONTCTBL = V_CONTCTBLPASS;
                 EXCEPTION
                   WHEN NO_DATA_FOUND THEN
                     V_IDCONTCCUS := NULL;
                 END;

                 IF V_CDCENTCUST IS NOT NULL THEN
                    IF V_IDCONTCCUS <> 'O' THEN
                     RATEIO_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, C_IMP_BA.CDFILIAL,
                                    V_CDCENTCUST, V_VRPARTIDA);
                    END IF;
                 END IF;
             ELSIF V_VRPARTIDA < 0 THEN
                 /*INSERE A TABELA PARA EXIBIR O RELATORIO*/
                 INSERT INTO CTB_TEMP_CREDPRES (CDFILIAL, VRTOTSAIDAS, VRCREDPRES,  CDCONTCTBLDEB, CDCONTCTBLCRED )
                      VALUES (C_IMP_BA.CDFILIAL,  V_VRDIFERENCA,  V_VRPARTIDA, V_CDCONTCTBL, V_CONTCTBLPASS);

                 /*DEBITA CONTA DE ESTORNO*/
                 NOVA_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, V_CDCONTCTBL, P_CDHISTPADR,
                             NVL(V_DSHISTPADR,V_DSESTORNOCRED), V_VRPARTIDA, V_IDCODCOMECONTEST, V_CODCOMEEST, '',V_NRNOTAFISC, 'N');

                 /*VERIFICA O CENTRO DE CUSTO PARAMETRIZADO*/
                 BEGIN
                    SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                      INTO V_CDCENTCUST
                      FROM FILIAL F, EMPRESA E
                     WHERE F.CDFILIAL  = C_IMP_BA.CDFILIAL
                       AND E.CDEMPRESA = P_CDEMPRESA;
                 EXCEPTION
                    WHEN NO_DATA_FOUND THEN
                       V_CDCENTCUST := NULL;
                 END;

                 /*INSERE RATEIO DA PARTIDA DE ESTORNO*/
                 IF V_CDCENTCUST IS NOT NULL THEN
                   RATEIO_PARTIDA(P_CDEMPRESA,V_CDLOTE,V_DATACONTABIL,V_NRLANCLOTE,C_IMP_BA.CDFILIAL,
                                  V_CDCENTCUST, V_VRPARTIDA);
                 END IF;

                 /*CREDITA CONTA IMPOSTO A RECOLHER*/
                   NOVA_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, V_CONTCTBLPASS, P_CDHISTPADR,
                                NVL(V_DSHISTPADR,V_DSESTORNOCRED), V_VRPARTIDA*-1, V_IDCODCOMECONTICM, V_CODCOMEICM, '', V_NRNOTAFISC, 'N');

                 /*VERIFICA O CENTRO DE CUSTO CADASTRADO*/
                 BEGIN
                    SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                      INTO V_CDCENTCUST
                      FROM FILIAL F, EMPRESA E
                     WHERE F.CDFILIAL  = C_IMP_BA.CDFILIAL
                       AND E.CDEMPRESA = P_CDEMPRESA;
                 EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDCENTCUST := NULL;
                 END;

                 /*VERIFICA SE A CONTA CONTABIL E OFICIAL/GERENCIAL E GERENCIAL*/
                 BEGIN
                  SELECT IDCONTCCUS
                    INTO V_IDCONTCCUS
                    FROM CONTCTBL
                   WHERE CDCONTCTBL = V_CONTCTBLPASS;
                 EXCEPTION
                   WHEN NO_DATA_FOUND THEN
                     V_IDCONTCCUS := NULL;
                 END;

                 IF V_CDCENTCUST IS NOT NULL THEN
                    IF V_IDCONTCCUS <> 'O' THEN
                     RATEIO_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, C_IMP_BA.CDFILIAL,
                                    V_CDCENTCUST, V_VRPARTIDA*-1);
                    END IF;
                 END IF;

             END IF;
         END IF;
      END LOOP;
      /*ESTORNO RJ*/
   ELSIF P_TIPO = '4' THEN
         /*ESTORNAR IMPOSTO NAS ENTRADAS E NAS SAIDAS QUE TIVEREM TRIBUTACAO E FOR CFOP DE VENDA ESTORNAR 8%
         SE FOR DIFERENTE DE VENDA ESTORNAR O VALOR TOTAL*/
        /*RETORNA OS PARAMETROS PARA A CONTABILIZACAO DO ESTORNO RJ*/
      BEGIN
         SELECT VRPERCENTEST, DSESTORNOCRED, DSESTORNODEBI, CDCONTCTBL
           INTO V_PERCENTESTORN, V_DSESTORNOCRED, V_DSESTORNODEBI, V_CDCONTCTBL
           FROM ESTORNO
          WHERE CDINSCESTA = P_CDINSCESTA;
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
             V_PERCENTESTORN     := 0;
             V_DSESTORNOCRED  := NULL;
             V_CDCONTCTBL        := NULL;
      END;
        /*ESTORNO IMPOSTO DAS ENTRADAS*/
      FOR C_IMP_RJ_E IN (SELECT SUM(ROUND(VRIMPOSTONF,2)) AS VRIMPOSTO, NF.NRNOTAFISC, NF.CDFILIRECE, NF.NRLANCTONF, NF.CDFILIAL
                           FROM NOTAFISCAL  NF, IMPOSTONF IP, IMPOSTO IM
                          WHERE NF.CDINSCESTA   = P_CDINSCESTA
                            AND NF.IDENTRSAIDOP = 'E'
                            AND NF.DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL
                            AND NF.CDEMPRESA    = P_CDEMPRESA
                            AND NF.CDFILIAL     = IP.CDFILIAL
                            AND NF.NRLANCTONF   = IP.NRLANCTONF
                            AND IM.CDIMPOSTONFE = '00'
                            AND IM.CDIMPOSTO    = IP.CDIMPOSTO
                            AND IP.VRIMPOSTONF > 0
                            AND IP.CDFISCALNF   = '1'
                          GROUP BY NF.NRNOTAFISC, NF.CDFILIRECE, NF.NRLANCTONF, NF.CDFILIAL)LOOP
         V_CONTCTBLATIV := CONTCTBL_IMPOSTO('00', 'A', 'S', '', '');

        /*MONTA O HISTORICO DO LANCAMENTO*/
         MONTA_HISTORICO(C_IMP_RJ_E.CDFILIRECE, P_CDINSCESTA ,P_CDHISTPADR,'',V_DATACONTABIL,'13', 'C', V_DSHISTPADR);
        /*GERA LOTE CONTABIL*/
         GERA_LOTECONTABIL(P_CDEMPRESA,'01',C_IMP_RJ_E.CDFILIRECE,'',V_DATACONTABIL,'','',V_CDLOTE,V_NRLANCLOTE,P_CDLOTE);
         IF C_IMP_RJ_E.VRIMPOSTO > 0 THEN
           /*INSERE A TABELA PARA EXIBIR O RELATORIO*/
            INSERT INTO CTB_TEMP_CREDPRES (CDFILIAL, VRTOTENTRADAS, VRTOTSAIDAS, VRCREDPRES,
                                           VRGLP, VRSAIDCONTAB, CDCONTCTBLDEB, CDCONTCTBLCRED )
                  VALUES (C_IMP_RJ_E.CDFILIRECE, NVL(V_VRIMPOSTOENTRADA,0),  NVL(V_VRIMPOSTOSAIDA,0), V_VRDIFERENCA,
                                         NVL(V_VRCOMPRAGAS,0), C_IMP_RJ_E.VRIMPOSTO, V_CDCONTCTBL, V_CONTCTBLATIV);

          /*DEBITA CONTA DE ESTORNO*/
            NOVA_PARTIDA(P_CDEMPRESA,V_CDLOTE,V_DATACONTABIL,V_NRLANCLOTE,  V_CDCONTCTBL, P_CDHISTPADR,
                       NVL(V_DSHISTPADR,V_DSESTORNOCRED), nvl(C_IMP_RJ_E.VRIMPOSTO,0)*-1, V_IDCODCOMECONTEST, V_CODCOMEEST, '',C_IMP_RJ_E.NRNOTAFISC, 'N');

          /*VERIFICA O CENTRO DE CUSTO PARAMETRIZADO*/
            BEGIN
               SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                 INTO V_CDCENTCUST
                 FROM FILIAL F, EMPRESA E
                WHERE F.CDFILIAL  = C_IMP_RJ_E.CDFILIRECE
                  AND E.CDEMPRESA = P_CDEMPRESA;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_CDCENTCUST := NULL;
            END;
            /*INSERE RATEIO DA PARTIDA DE ESTORNO*/
            IF V_CDCENTCUST IS NOT NULL THEN
              RATEIO_PARTIDA(P_CDEMPRESA,V_CDLOTE,V_DATACONTABIL,V_NRLANCLOTE,C_IMP_RJ_E.CDFILIRECE,
                             V_CDCENTCUST, nvl(C_IMP_RJ_E.VRIMPOSTO,0)*-1);
            END IF;

            /* CREDITA CONTA CONTABIL  DO ATIVO */
             NOVA_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, V_CONTCTBLATIV, P_CDHISTPADR,
                           NVL(V_DSHISTPADR,V_DSESTORNOCRED), nvl(C_IMP_RJ_E.VRIMPOSTO,0), V_IDCODCOMECONTICM, V_CODCOMEICM, '', C_IMP_RJ_E.NRNOTAFISC, 'N');

            /*VERIFICA O CENTRO DE CUSTO CADASTRADO*/
            BEGIN
               SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                 INTO V_CDCENTCUST
                 FROM FILIAL F, EMPRESA E
                WHERE F.CDFILIAL  = C_IMP_RJ_E.CDFILIRECE
                  AND E.CDEMPRESA = P_CDEMPRESA;
            EXCEPTION
                 WHEN NO_DATA_FOUND THEN
                  V_CDCENTCUST := NULL;
            END;
            /*VERIFICA SE A CONTA CONTABIL E OFICIAL/GERENCIAL E GERENCIAL*/
            BEGIN
             SELECT IDCONTCCUS
               INTO V_IDCONTCCUS
               FROM CONTCTBL
              WHERE CDCONTCTBL = V_CONTCTBLATIV;
            EXCEPTION
              WHEN NO_DATA_FOUND THEN
                V_IDCONTCCUS := NULL;
            END;

            IF V_CDCENTCUST IS NOT NULL THEN
               IF V_IDCONTCCUS <> 'O' THEN
                RATEIO_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, C_IMP_RJ_E.CDFILIRECE,
                               V_CDCENTCUST, nvl(C_IMP_RJ_E.VRIMPOSTO,0));
               END IF;
            END IF;
         END IF;
      END LOOP;
      FOR C_IMP_RJ_S IN (SELECT SUM(ROUND(VRBASECALCNF*V_PERCENTESTORN/100,2)) AS VRIMPOSTO, NF.NRNOTAFISC, NF.CDFILIEMIT, NF.NRLANCTONF, NF.CDFILIAL
                           FROM NOTAFISCAL  NF, IMPOSTONF IP, IMPOSTO IM
                          WHERE NF.CDINSCESTA   = P_CDINSCESTA
                            AND NF.IDENTRSAIDOP = 'S'
                            AND NF.DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL
                            AND NF.CDEMPRESA    = P_CDEMPRESA
                            AND NF.CDFILIAL     = IP.CDFILIAL
                            AND NF.NRLANCTONF   = IP.NRLANCTONF
                            AND IM.CDIMPOSTONFE = '00'
                            AND IM.CDIMPOSTO    = IP.CDIMPOSTO
                            AND IP.VRIMPOSTONF > 0
                            AND IP.CDFISCALNF   = '1'
                            AND SUBSTR(IP.CDFISCOPERNF,2,3) = '102'
                          GROUP BY NF.NRNOTAFISC, NF.CDFILIEMIT, NF.NRLANCTONF, NF.CDFILIAL) LOOP
          V_CONTCTBLPASS := CONTCTBL_IMPOSTO('00', 'P', 'S', '', '');
          V_CONTCTBLREC  := CONTCTBL_IMPOSTO('00', 'D', 'S', '', '');
         /*MONTA O HISTORICO DO LANCAMENTO*/
          MONTA_HISTORICO(C_IMP_RJ_S.CDFILIEMIT, P_CDINSCESTA ,P_CDHISTPADR,'',V_DATACONTABIL,'13', 'D', V_DSHISTPADR);
         /*GERA LOTE CONTABIL*/
          GERA_LOTECONTABIL(P_CDEMPRESA,'01',C_IMP_RJ_S.CDFILIEMIT,'',V_DATACONTABIL,'','',V_CDLOTE,V_NRLANCLOTE,P_CDLOTE);
         IF C_IMP_RJ_S.VRIMPOSTO > 0 THEN
           /*INSERE A TABELA PARA EXIBIR O RELATORIO*/
            INSERT INTO CTB_TEMP_CREDPRES (CDFILIAL, VRTOTENTRADAS, VRTOTSAIDAS, VRCREDPRES,
                                           VRGLP, VRSAIDCONTAB, CDCONTCTBLDEB, CDCONTCTBLCRED )
                  VALUES (C_IMP_RJ_S.CDFILIEMIT, NVL(V_VRIMPOSTOENTRADA,0),  NVL(V_VRIMPOSTOSAIDA,0), V_VRDIFERENCA,
                                         NVL(V_VRCOMPRAGAS,0), C_IMP_RJ_S.VRIMPOSTO, V_CONTCTBLPASS, V_CONTCTBLREC);

          /*DEBITA CONTA DO PASSIVO*/
            NOVA_PARTIDA(P_CDEMPRESA,V_CDLOTE,V_DATACONTABIL,V_NRLANCLOTE,  V_CONTCTBLPASS, P_CDHISTPADR,
                       NVL(V_DSHISTPADR,V_DSESTORNODEBI), nvl(C_IMP_RJ_S.VRIMPOSTO,0)*-1, V_IDCODCOMECONTEST, V_CODCOMEEST, '',C_IMP_RJ_S.NRNOTAFISC, 'N');

          /*VERIFICA O CENTRO DE CUSTO PARAMETRIZADO*/
            BEGIN
               SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                 INTO V_CDCENTCUST
                 FROM FILIAL F, EMPRESA E
                WHERE F.CDFILIAL  = C_IMP_RJ_S.CDFILIEMIT
                  AND E.CDEMPRESA = P_CDEMPRESA;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_CDCENTCUST := NULL;
            END;
            /*INSERE RATEIO DA PARTIDA DE ESTORNO*/
            IF V_CDCENTCUST IS NOT NULL THEN
              RATEIO_PARTIDA(P_CDEMPRESA,V_CDLOTE,V_DATACONTABIL,V_NRLANCLOTE,C_IMP_RJ_S.CDFILIEMIT,
                             V_CDCENTCUST, nvl(C_IMP_RJ_S.VRIMPOSTO,0)*-1);
            END IF;

            /* CREDITA CONTA CONTABIL  DE RECEITA */
             NOVA_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, V_CONTCTBLREC, P_CDHISTPADR,
                           NVL(V_DSHISTPADR,V_DSESTORNODEBI), nvl(C_IMP_RJ_S.VRIMPOSTO,0), V_IDCODCOMECONTICM, V_CODCOMEICM, '', C_IMP_RJ_S.NRNOTAFISC, 'N');

            /*VERIFICA O CENTRO DE CUSTO CADASTRADO*/
            BEGIN
               SELECT NVL(F.CDCENTCUST, E.CDCENTCUST) AS CDCENTCUST
                 INTO V_CDCENTCUST
                 FROM FILIAL F, EMPRESA E
                WHERE F.CDFILIAL  = C_IMP_RJ_S.CDFILIEMIT
                  AND E.CDEMPRESA = P_CDEMPRESA;
            EXCEPTION
                 WHEN NO_DATA_FOUND THEN
                  V_CDCENTCUST := NULL;
            END;
            /*VERIFICA SE A CONTA CONTABIL E OFICIAL/GERENCIAL E GERENCIAL*/
            BEGIN
             SELECT IDCONTCCUS
               INTO V_IDCONTCCUS
               FROM CONTCTBL
              WHERE CDCONTCTBL = V_CONTCTBLREC;
            EXCEPTION
              WHEN NO_DATA_FOUND THEN
                V_IDCONTCCUS := NULL;
            END;

            IF V_CDCENTCUST IS NOT NULL THEN
               IF V_IDCONTCCUS <> 'O' THEN
                RATEIO_PARTIDA(P_CDEMPRESA, V_CDLOTE, V_DATACONTABIL, V_NRLANCLOTE, C_IMP_RJ_S.CDFILIEMIT,
                               V_CDCENTCUST, nvl(C_IMP_RJ_S.VRIMPOSTO,0));
               END IF;
            END IF;
         END IF;
      END LOOP;
   END IF;
   /*VERIFICACAO DE ERROS NAS PARTIDAS E NO LANCAMENTO CONTABIL*/
     VERIFICA_ERRO_CTB(V_NRLANCTEMP, P_CDEMPRESA);
     BEGIN
        SELECT COUNT(*)
          INTO V_COUNT
          FROM ERROCTBTEMP
         WHERE NRLANCCTBTEMP = V_NRLANCTEMP
           AND CDEMPRESA = P_CDEMPRESA;
     EXCEPTION
        WHEN NO_DATA_FOUND THEN
           V_COUNT := 0;
     END;

END;