CREATE OR REPLACE PROCEDURE MONTA_HISTORICO(
   P_CODIGO IN VARCHAR2,
   P_STLANCAMENTO IN VARCHAR2,
   P_CDHISTPADR IN HISTPADR.CDHISTPADR%TYPE,
   P_NRNOTAFISC IN VARCHAR2,
   P_DTEMISSAO IN DATE,
   P_TIPOHISTORICO IN VARCHAR2,
   P_CDAJUCONTA IN VARCHAR2,
   P_DSHISTPADR OUT VARCHAR2)
IS
   V_DSHISTPADR VARCHAR2(1000);
   V_STDSHISTPADR VARCHAR2(1000);
   V_STNOTAFISC VARCHAR2(20);
   V_NRINSJURCLIE VARCHAR2(20);
   V_IDTPIJURCLIE VARCHAR2(1);
   V_NMFANTFORN VARCHAR2(50);
   V_NMFANTCLIE VARCHAR2(50);
   V_NMRAZSOCCLIE VARCHAR2(50);
   V_NRINSJURFORN VARCHAR2(50);
   V_NMRAZSOCFORN VARCHAR2(50);
   V_IDENTRSAIDOP VARCHAR2(1);
   V_CDFILIEMIT VARCHAR2(4);
   V_CDFILIRECE VARCHAR2(4);
   V_DTEMISSAO DATE;
   V_DTENTRSAID DATE;
   V_CDFILIAL VARCHAR2(4);
   V_NRLANCTONF VARCHAR2(10);
   V_DSPRODEMIS VARCHAR2(400);
   V_NRNOTAFISC VARCHAR2(10);
   V_IDTPIJURFORN VARCHAR2(1);
   V_HISTCREDPRES VARCHAR2(1000);
BEGIN
   BEGIN
    SELECT DSHISTPADR
      INTO V_DSHISTPADR
      FROM HISTPADR
     WHERE CDHISTPADR = P_CDHISTPADR;
   EXCEPTION
    WHEN NO_DATA_FOUND THEN
     V_DSHISTPADR :=  NULL;
   END ;
   CASE P_TIPOHISTORICO
    WHEN '00' THEN
     BEGIN
       BEGIN
         SELECT NF.CDFILIAL, NF.NRLANCTONF, NF.NRNOTAFISC,
                C.NRINSJURCLIE, C.IDTPIJURCLIE,
                C.NMFANTCLIE,   C.NMRAZSOCCLIE,
                F.NRINSJURFORN, F.IDTPIJURFORN,
                F.NMFANTFORN,   F.NMRAZSOCFORN,
                NF.IDENTRSAIDOP, NF.CDFILIEMIT, NF.CDFILIRECE,
                NF.DTEMISSAO, NF.DTENTRSAID
           INTO V_CDFILIAL, V_NRLANCTONF, V_NRNOTAFISC,
                V_NRINSJURCLIE, V_IDTPIJURCLIE,
                V_NMFANTCLIE, V_NMRAZSOCCLIE,
                V_NRINSJURFORN, V_IDTPIJURFORN,
                V_NMFANTFORN, V_NMRAZSOCFORN,
                V_IDENTRSAIDOP, V_CDFILIEMIT, V_CDFILIRECE,
                V_DTEMISSAO, V_DTENTRSAID
           FROM NOTAFISCAL NF, CLIENTE C, FORNECEDOR F
          WHERE CDFILIAL      = P_CODIGO
            AND NRLANCTONF    = P_STLANCAMENTO
            AND NF.CDCLIENTE  = C.CDCLIENTE(+)
            AND NF.CDFORNECED = F.CDFORNECED(+);
       EXCEPTION
         WHEN NO_DATA_FOUND THEN
              V_CDFILIAL      := NULL;
              V_NRLANCTONF    := NULL;
              V_NRNOTAFISC    := NULL;
              V_NRINSJURCLIE  := NULL;
              V_IDTPIJURCLIE  := NULL;
              V_NRINSJURFORN  := NULL;
              V_IDTPIJURFORN  := NULL;
              V_IDTPIJURFORN  := NULL;
              V_NMFANTFORN    := NULL;
              V_NMRAZSOCFORN  := NULL;
              V_IDENTRSAIDOP  := NULL;
              V_CDFILIEMIT    := NULL;
              V_CDFILIRECE    := NULL;
              V_DTEMISSAO     := NULL;
              V_DTENTRSAID    := NULL;
       END;
      BEGIN
         SELECT MAX(DSPRODEMIS)
           INTO V_DSPRODEMIS
           FROM ITEMPRODUTO
          WHERE CDFILIAL   = P_CODIGO
            AND NRLANCTONF = P_STLANCAMENTO;
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
             V_DSPRODEMIS :=NULL;
      END;
       IF P_NRNOTAFISC IS NULL THEN
          V_STNOTAFISC := V_NRNOTAFISC;
       ELSE
          V_STNOTAFISC := P_NRNOTAFISC;
       END IF;
       V_STDSHISTPADR := V_DSHISTPADR;
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DOC]', V_STNOTAFISC);
       IF V_IDENTRSAIDOP = 'E' THEN
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[FIL]', V_CDFILIRECE);
       ELSE
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[FIL]', V_CDFILIEMIT);
       END IF;
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[SEQ]', V_NRLANCTONF);
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[CLI]', V_NRINSJURCLIE);
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[NFC]', V_NMFANTCLIE);
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[RSC]', V_NMRAZSOCCLIE);
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[RSC]', V_NMRAZSOCCLIE);
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[FOR]', V_NRINSJURFORN);
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[NFF]', V_NMFANTFORN);
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[RSF]', V_NMRAZSOCFORN);
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[NMPR]', V_DSPRODEMIS);
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DTEM-MA]', SUBSTR(TO_CHAR(P_DTEMISSAO),4,10));
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DTES-MA]', SUBSTR(TO_CHAR(V_DTENTRSAID),4,10));
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DTEM]', TO_CHAR(V_DTEMISSAO));
       V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DTES]', TO_CHAR(V_DTENTRSAID));
       IF INSTR(V_STDSHISTPADR,'[DOCO]') > 0 THEN
          BEGIN
            SELECT N.NRNOTAFISC
              INTO V_STNOTAFISC
              FROM ITEMNOTAFISC I, NOTAFISCAL N
             WHERE I.CDFILIAL = P_CODIGO
               AND I.NRLANCTONF = P_STLANCAMENTO
               AND I.CDFILIALIT = N.CDFILIAL
               AND I.NRLANCTONFIT = N.NRLANCTONF;
          EXCEPTION
             WHEN NO_DATA_FOUND THEN
              V_STNOTAFISC := NULL;
          END;
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DOCO]', V_STNOTAFISC);
       END IF;
     END;
    WHEN '06' THEN
     BEGIN
       V_STDSHISTPADR := V_DSHISTPADR;
       FOR C_CONTAPAGAR IN(
         SELECT CP.CDFILIAL    , CP.NRLANCTONF  , CP.NRSEQVENPAG , CP.VRATUAPAG  ,
                CP.DTATUAVENPAG, CP.DTORIGVENPAG, CP.DSCONTAPAG  , CP.CDTPCTPAGAR,
                CP.QTDIASVENPAG, CP.NRPARCELAPAG, CP.IDSTATPAG   , CP.CDFILIBPAG ,
                CP.NRLANBOLPAG , NF.CDSERIEENTR , CP.CDMOTIPARC  , CP.VRORIGPAG  ,
                CP.CDCLASSFINA , CP.CDEMPRESA   , CP.CDFIMOVFLPAG, CP.DTMOVFLUXO ,
                CP.IDMOVFLUXO, NF.CDINSCESTA, NF.CDINSCMUNI, NF.VRNOTAFISC, CP.CDMOTIPROR,
                NF.CDFILIRECE AS CDFILIORIG, NF.CDTIPOOPER, NF.IDTPIJURNF AS IDTPINSJUR, NF.NRINSJURNF AS NRINSJURFORN,
                NF.CDFORNECED, NF.NRNOTAFISC, NF.DTEMISSAO, NF.DTENTRSAID,  NF.IDSTATUS,
                NF.CDAUTDESPESA AS CDAUTODESP, NF.NRLANCTBDOC,
                F.NMFANTFORN, F.NMRAZSOCFORN
           FROM CONTAPAGAR CP, NOTAFISCAL NF, FORNECEDOR F
          WHERE (NF.CDFILIAL   = P_CODIGO)
            AND (NF.NRLANCTONF = P_STLANCAMENTO)
            AND (CP.CDFILIAL   = NF.CDFILIAL  )
            AND (CP.NRLANCTONF = NF.NRLANCTONF)
            AND (NF.CDFORNECED = F.CDFORNECED)
          ORDER BY CP.NRLANCTONF, CP.NRSEQVENPAG, CP.DTATUAVENPAG, CP.NRPARCELAPAG) LOOP
            FOR C_CDAJUCTPAG IN(
             SELECT T.DSAJUCTPAG
               FROM TIPOAJPAGAR T
              WHERE (T.CDAJUCTPAG = P_CDAJUCONTA)) LOOP
              V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[TAP]', C_CDAJUCTPAG.DSAJUCTPAG);
              V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DAP]', P_DTEMISSAO);
            END LOOP;
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[FIL]', C_CONTAPAGAR.CDFILIORIG);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[FOR]', C_CONTAPAGAR.NRINSJURFORN);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[NFF]', C_CONTAPAGAR.NMFANTFORN);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[RSF]', C_CONTAPAGAR.NMRAZSOCFORN);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DOC]', C_CONTAPAGAR.NRNOTAFISC);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[SEQ]', C_CONTAPAGAR.NRLANCTBDOC);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[TCP]', C_CONTAPAGAR.CDTPCTPAGAR);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DCP]', C_CONTAPAGAR.DSCONTAPAG);
       END LOOP;
     END;
    WHEN '07' THEN
     BEGIN
       V_STDSHISTPADR := V_DSHISTPADR;
       FOR C_CONTARECEBER IN (
         SELECT CP.CDFILIAL    , CP.NRLANCTONF  , CP.NRSEQVENREC , CP.VRATUAREC  ,
                CP.DTATUAVENREC, CP.DTORIGVENREC, CP.DSCONTAREC  , CP.CDTPCTRECEB,
                CP.QTDIASVENREC, CP.NRPARCELAREC, CP.IDSTATREC   , CP.CDFILIBOLREC ,
                CP.NRLANBOLREC , NF.CDSERIE     , CP.CDMOTIPARC  , CP.VRORIGREC  ,
                CP.CDCLASSFINA , CP.CDEMPRESA   , CP.CDFIMOVFLREC, CP.DTMOVFLUXO ,
                CP.IDMOVFLUXO, NF.CDINSCESTA, NF.CDINSCMUNI, NF.VRNOTAFISC,
                NF.CDFILIEMIT, NF.CDTIPOOPER, NF.IDTPIJURNF AS IDTPINSJUR, NF.NRINSJURNF AS NRINSJURCLIE,
                NF.CDCLIENTE, NF.NRNOTAFISC, NF.DTEMISSAO, NF.DTENTRSAID,  NF.IDSTATUS,
                NF.NRLANCTBDOC, CP.DTPREVRECEBI, CP.QTDIASPREREC,
                CL.NMFANTCLIE, CL.NMRAZSOCCLIE
           FROM CONTARECEBER CP, NOTAFISCAL NF, CLIENTE CL
          WHERE (NF.CDFILIAL      = P_CODIGO)
            AND (NF.NRLANCTONF    = P_STLANCAMENTO)
            AND (CP.CDFILIAL      = NF.CDFILIAL)
            AND (CP.NRLANCTONF    = NF.NRLANCTONF)
            AND (CL.CDCLIENTE(+)  = NF.CDCLIENTE)
          ORDER BY CP.NRLANCTONF, CP.NRSEQVENREC, CP.DTATUAVENREC, CP.NRPARCELAREC) LOOP
          FOR C_CDAJUCTPAG IN(
            SELECT T.DSAJUCTREC
              FROM TIPOAJRECEBER T
             WHERE (T.CDAJUCTREC = P_CDAJUCONTA)) LOOP
            V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[TAP]', C_CDAJUCTPAG.DSAJUCTREC);
            V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DAP]', P_DTEMISSAO);
          END LOOP;
         V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[FIL]', C_CONTARECEBER.CDFILIEMIT);
         V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[CLI]', C_CONTARECEBER.NRINSJURCLIE);
         V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[NFC]', C_CONTARECEBER.NMFANTCLIE);
         V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[RSC]', C_CONTARECEBER.NMRAZSOCCLIE);
         V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DOC]', C_CONTARECEBER.NRNOTAFISC);
         V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[SEQ]', C_CONTARECEBER.NRLANCTBDOC);
         V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[TCR]', C_CONTARECEBER.CDTPCTRECEB);
         V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DCR]', C_CONTARECEBER.DSCONTAREC);
       END LOOP;
     END;
    WHEN '08' THEN
     BEGIN
       V_STDSHISTPADR := V_DSHISTPADR;
        FOR C_BCO_LANCCORR IN(
          SELECT M.DTMOVICRED, C.DSTPCREDBANC AS TIPO, C.CDHISTPADR, C.CDCONTCTBL, M.CDTPCREDBANC AS CDTIPO,
                 M.NRLCTBMCRED AS LANCCONT, M.DSMOVICRED, M.VRMOVICRED, M.NRMOVICRED AS NUMERO, M.NRMOVBANC ,
                 M.CDEMPRESA, M.CDFILIAL, M.CDFILILANCRE AS CDFILILANCA, C.IDCTBLCRBANC AS IDCONTABILIZA,
                 L.NMRAZSOCCLIE, L.NMFANTCLIE, O.NMRAZSOCFORN, O.NMFANTFORN,
                 'C' AS DEBCRED, B.NRDOCMBANC
            FROM TPCREDBANC C, MOVBANCARIO B, MOVCREDBANC M, FORNECEDOR O, CLIENTE L
           WHERE (C.CDTPCREDBANC = M.CDTPCREDBANC)
             AND (M.NRMOVBANC    = B.NRMOVBANC)
             AND (B.CDREDUCONT   = M.CDREDUCONT)
             AND (M.CDREDUCONT   = P_CODIGO)
             AND (M.NRMOVBANC   = P_STLANCAMENTO)
             AND (M.CDCLIENTE    = L.CDCLIENTE(+))
             AND (M.CDFORNECED   = O.CDFORNECED(+))
           UNION ALL
          SELECT M.DTMOVIDEBI, C.DSTPDEBIBANC AS TIPO, C.CDHISTPADR, C.CDCONTCTBL, M.CDTPDEBIBANC AS CDTIPO,
                 M.NRLCTBMDEB AS LANCCONT, M.DSMOVIDEBI, M.VRMOVIDEBI, M.NRMOVIDEBI AS NUMERO,M.NRMOVBANC,
                 M.CDEMPRESA, M.CDFILIAL, M.CDFILILANDEB AS CDFILILANCA, C.IDCTBLDBBANC AS IDCONTABILIZA,
                 L.NMRAZSOCCLIE, L.NMFANTCLIE, O.NMRAZSOCFORN, O.NMFANTFORN,
                 'D' AS DEBCRED, B.NRDOCMBANC
           FROM TPDEBIBANC C, MOVBANCARIO B, MOVDEBBANC  M, FORNECEDOR  O, CLIENTE L
          WHERE (C.CDTPDEBIBANC = M.CDTPDEBIBANC)
            AND (M.NRMOVBANC    = B.NRMOVBANC)
            AND (B.CDREDUCONT   = M.CDREDUCONT(+))
            AND (M.CDREDUCONT   = P_CODIGO)
            AND (M.NRMOVBANC   = P_STLANCAMENTO)
            AND (M.CDCLIENTE    = L.CDCLIENTE(+))
            AND (M.CDFORNECED   = O.CDFORNECED(+))) LOOP
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DESC]', C_BCO_LANCCORR.DSMOVICRED);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[TIPO]', C_BCO_LANCCORR.TIPO);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[HIMB]', C_BCO_LANCCORR.DSMOVICRED||'('||C_BCO_LANCCORR.TIPO||')');
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DOC]', C_BCO_LANCCORR.NRDOCMBANC);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[RSC]', C_BCO_LANCCORR.NMRAZSOCCLIE);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[NFC]', C_BCO_LANCCORR.NMFANTCLIE);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[RSF]', C_BCO_LANCCORR.NMRAZSOCFORN);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[NFF]', C_BCO_LANCCORR.NMFANTFORN);
        END LOOP;
     END;
    WHEN '09' THEN
     BEGIN
        V_STDSHISTPADR := V_DSHISTPADR;
        FOR C_BCO_TRANSCCOR IN(
           SELECT I.CDEMPRESA, I.NRTRANBANC, I.CDREDUCONT, I.NRMOVBANC, I.IDMOVITBANC, I.VRMOVITBANC,
                  I.NRCHEQUE, C.CDBANCO, C.CDAGENCIA, C.CDCONTCORR, C.DSCONTCORR, B.CDPICTCONT, C.CDCONTCTBL,
                  T.NRLCTBTRAN, T.DSHISTTBANC, T.DTTRANBANC
             FROM ITTRANSFBANC I, CONTCORR C, BANCO B, TRANSFBANC T, LISTA LI
            WHERE (T.CDEMPRESA  = I.CDEMPRESA)
              AND (T.NRTRANBANC = I.NRTRANBANC)
              AND (I.CDREDUCONT = C.CDREDUCONT)
              AND (C.CDBANCO    = B.CDBANCO)
              AND (I.CDREDUCONT = P_CODIGO)
              AND (I.NRMOVBANC = P_STLANCAMENTO))LOOP
              V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[HITR]', C_BCO_TRANSCCOR.DSHISTTBANC);
              V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[#CHQ]', C_BCO_TRANSCCOR.NRCHEQUE);
        END LOOP;
     END;
    WHEN '10' THEN
     BEGIN
       V_STDSHISTPADR := V_DSHISTPADR;
       FOR C_DSBAIXA IN (
       SELECT B.NRCHEQUE, B.DSNOMCHEQUE, B.DSBAIXAPAG
         FROM BAIXAPAGA B
        WHERE B.CDFILIAL = P_CODIGO
          AND B.NRBAIXAPAG = P_STLANCAMENTO) LOOP
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[#CHQ]', C_DSBAIXA.NRCHEQUE);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DCHQ]', C_DSBAIXA.DSNOMCHEQUE);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DBXPG]', C_DSBAIXA.DSBAIXAPAG);
       END LOOP;
     END;
    WHEN '11' THEN
     BEGIN
       V_STDSHISTPADR := V_DSHISTPADR;
       FOR C_DSBAIXA IN (
       SELECT B.DSBAIXAREC
         FROM BAIXARECEBIDA B
        WHERE B.CDFILIAL = P_CODIGO
          AND B.NRBAIXAREC = P_STLANCAMENTO) LOOP
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DBXPG]', C_DSBAIXA.DSBAIXAREC);
       END LOOP;
     END;
    WHEN '12' THEN
     BEGIN
       V_STDSHISTPADR := V_DSHISTPADR;
       FOR C_NOTAFISCAL IN (SELECT NF.CDFILIAL, NF.NRLANCTONF, NF.CDINSCESTA, NF.CDINSCMUNI, NF.VRNOTAFISC,
                                   NF.CDFILIEMIT, NF.CDTIPOOPER, NF.IDTPIJURNF AS IDTPINSJUR,
                                   NF.NRINSJURNF AS NRINSJURCLIE, NF.CDCLIENTE, NF.NRNOTAFISC, NF.DTEMISSAO,
                                   NF.DTENTRSAID,  NF.IDSTATUS, NF.NRLANCTBDOC, CL.NMFANTCLIE, CL.NMRAZSOCCLIE
                              FROM NOTAFISCAL NF, CLIENTE CL
                             WHERE NF.CDFILIAL     = P_CODIGO
                               AND NF.NRLANCTONF   = P_STLANCAMENTO
                               AND CL.CDCLIENTE(+) = NF.CDCLIENTE
                             ORDER BY NF.NRLANCTONF) LOOP
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR,  '[FIL]', C_NOTAFISCAL.CDFILIEMIT);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR,  '[CLI]', C_NOTAFISCAL.NRINSJURCLIE);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR,  '[NFC]', C_NOTAFISCAL.NMFANTCLIE);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR,  '[RSC]', C_NOTAFISCAL.NMRAZSOCCLIE);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR,  '[DOC]', C_NOTAFISCAL.NRNOTAFISC);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DTEM]', TO_CHAR(C_NOTAFISCAL.DTEMISSAO));
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR,  '[SEQ]', C_NOTAFISCAL.NRLANCTBDOC);
       END LOOP;
       FOR C_CDAJUCTPAG IN(
          SELECT T.DSAJUCTREC
            FROM TIPOAJRECEBER T
           WHERE (T.CDAJUCTREC = P_CDAJUCONTA)) LOOP
           V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[TAP]', C_CDAJUCTPAG.DSAJUCTREC);
           V_STDSHISTPADR := REPLACE(V_STDSHISTPADR, '[DAP]', P_DTEMISSAO);
       END LOOP;
       FOR C_CONTARECEBER IN (SELECT CP.DSCONTAREC, CP.CDTPCTRECEB
                                FROM CONTARECEBER CP
                               WHERE CP.CDFILIAL   = P_CODIGO
                                 AND CP.NRLANCTONF = P_STLANCAMENTO) LOOP
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR,  '[TCR]', C_CONTARECEBER.CDTPCTRECEB);
          V_STDSHISTPADR := REPLACE(V_STDSHISTPADR,  '[DCR]', C_CONTARECEBER.DSCONTAREC);
       END LOOP;
       FOR C_ECF IN(
           /*Quando existir NFC-e e Redução Z para o mesmo Dia, Caixa e Filial, a NFC-e tem prioridade*/
          SELECT CDFILIAL, CDCAIXA, NRECFREDZ, NRREDREDZ
            FROM (SELECT DISTINCT '1' AS ID, MV.CDFILIAL, MV.CDCAIXA, R.NRECFREDZ, R.NRREDREDZ
                    FROM MOVCAIXA MV, REDUCAOZ R
                   WHERE MV.CDFILIAL            = R.CDFILIAL
                     AND MV.CDCAIXA             = R.CDCAIXA
                     AND TRUNC(MV.DTMOVIMCAIXA) = R.DTREDUCAOZ
                     AND MV.CDFILIALNF          = P_CODIGO
                     AND MV.NRLANCTONF          = P_STLANCAMENTO
                   UNION ALL
                  SELECT DISTINCT '2' AS ID, VE.CDFILIAL, VE.CDCAIXA, ' ' AS NRECFREDZ, TO_CHAR(VE.DTEMISSAONFCE,'DDMMYYYY') || VE.CDCAIXA AS NRREDREDZ
                    FROM MOVCAIXA MV, VENDA VE
                   WHERE MV.CDFILIALNF    = P_CODIGO
                     AND MV.NRLANCTONF    = P_STLANCAMENTO
                     AND MV.CDFILIAL      = VE.CDFILIAL
                     AND MV.CDCAIXA       = VE.CDCAIXA
                     AND MV.NRSEQVENDA    = VE.NRSEQVENDA
                     AND VE.IDTPEMISVEND  IN ('N','S')
                     AND VE.IDTPAMBNFCE   = '1'
                     AND VE.IDSTATUSNFCE  = 'A'
                   UNION ALL
                  SELECT DISTINCT '1' AS ID, MV.CDFILIAL, MV.CDCAIXA, R.NRECFREDZ, R.NRREDREDZ
                    FROM MOVCAIXA MV, REDUCAOZ R
                   WHERE MV.CDFILIAL            = R.CDFILIAL
                     AND MV.CDCAIXA             = R.CDCAIXA
                     AND TRUNC(MV.DTMOVIMCAIXA) = R.DTREDUCAOZ
                     AND MV.CDFILIALNFFIS       = P_CODIGO
                     AND MV.NRLANCTONFFIS       = P_STLANCAMENTO
                   UNION ALL
                  SELECT DISTINCT '2' AS ID, VE.CDFILIAL, VE.CDCAIXA, ' ' AS NRECFREDZ, TO_CHAR(VE.DTEMISSAONFCE,'DDMMYYYY') || VE.CDCAIXA AS NRREDREDZ
                    FROM MOVCAIXA MV, VENDA VE
                   WHERE MV.CDFILIALNFFIS = P_CODIGO
                     AND MV.NRLANCTONFFIS = P_STLANCAMENTO
                     AND MV.CDFILIAL      = VE.CDFILIAL
                     AND MV.CDCAIXA       = VE.CDCAIXA
                     AND MV.NRSEQVENDA    = VE.NRSEQVENDA
                     AND VE.IDTPEMISVEND  IN ('N','S')
                     AND VE.IDTPAMBNFCE   = '1'
                     AND VE.IDSTATUSNFCE  = 'A'
                   ORDER BY ID DESC)
           WHERE ROWNUM = 1) LOOP
           V_STDSHISTPADR := REPLACE(V_STDSHISTPADR,  '[ECF]', C_ECF.NRECFREDZ);
           V_STDSHISTPADR  := REPLACE(V_STDSHISTPADR, '[CXA]', C_ECF.CDCAIXA);
           V_STDSHISTPADR  := REPLACE(V_STDSHISTPADR, '[RED]', C_ECF.NRREDREDZ);
       END LOOP;
     END;
    WHEN '13' THEN
     BEGIN
      V_STDSHISTPADR := V_DSHISTPADR;
      BEGIN
         SELECT HISTLANC
           INTO V_DSHISTPADR
           FROM
         (SELECT
             NVL(DSESTORNOCRED,' ')||' '||'IE '||IE.CDINSCESTA||' '||TO_CHAR(P_DTEMISSAO,'MONTH')||'-'||TO_CHAR(P_DTEMISSAO,'YYYY')||'-'||P_CODIGO AS HISTLANC
           FROM ESTORNO E, INSCRESTAD IE
          WHERE E.CDINSCESTA = P_STLANCAMENTO
		      AND IE.CDINSCESTA  = E.CDINSCESTA
			   AND IE.SGESTADO  = 'PE'
          UNION ALL
         SELECT
             NVL(DSESTORNOCRED,' ')||' '||'IE '||IE.CDINSCESTA||' '||TO_CHAR(P_DTEMISSAO,'MONTH')||'-'||TO_CHAR(P_DTEMISSAO,'YYYY')||'-'||P_CODIGO AS HISTLANC
           FROM ESTORNO E, INSCRESTAD IE
          WHERE E.CDINSCESTA = P_STLANCAMENTO
		      AND IE.CDINSCESTA  = E.CDINSCESTA
		    	AND IE.SGESTADO  = 'SP'
          UNION ALL
         SELECT
             DECODE(P_CDAJUCONTA,'D',NVL(DSESTORNOCRED,' '),NVL(DSESTORNODEBI,''))||' '||'IE '||IE.CDINSCESTA||' '||TO_CHAR(P_DTEMISSAO,'MONTH')||'-'||TO_CHAR(P_DTEMISSAO,'YYYY')||'-'||P_CODIGO AS HISTLANC
           FROM ESTORNO E, INSCRESTAD IE
          WHERE E.CDINSCESTA = P_STLANCAMENTO
		      AND IE.CDINSCESTA  = E.CDINSCESTA
			   AND IE.SGESTADO  = 'BA'
          UNION ALL
         SELECT
             DECODE(P_CDAJUCONTA,'D',DSESTORNODEBI, DSESTORNOCRED)||' '||'IE '||IE.CDINSCESTA||' '||TO_CHAR(P_DTEMISSAO,'MONTH')||'-'||TO_CHAR(P_DTEMISSAO,'YYYY')||'-'||P_CODIGO AS HISTLANC
           FROM ESTORNO E, INSCRESTAD IE
          WHERE E.CDINSCESTA = P_STLANCAMENTO
		      AND IE.CDINSCESTA  = E.CDINSCESTA
		    	AND IE.SGESTADO  = 'RJ');
      EXCEPTION WHEN NO_DATA_FOUND THEN
           V_DSHISTPADR := NULL;
      END;
       V_STDSHISTPADR :=  V_DSHISTPADR;
     END;
    END CASE;
    P_DSHISTPADR := V_STDSHISTPADR;
END;
/
CREATE OR REPLACE PROCEDURE GERA_LOTECONTABIL(
  P_CDEMPRESA IN EMPRESA.CDEMPRESA%TYPE,
  P_TIPOMOVI IN VARCHAR2,
  P_CDFILIEMIT IN FILIAL.CDFILIAL%TYPE,
  P_CDFILIRECE IN FILIAL.CDFILIAL%TYPE,
  P_DTMOVI IN DATE,
  P_TIPOOPERAC IN VARCHAR2,
  P_TPCREDDEB IN VARCHAR2,
  P_CDLOTE OUT VARCHAR2,
  P_NRLANCLOTE OUT VARCHAR2,
  P_CODLOTE IN VARCHAR2 DEFAULT NULL)
IS
  V_CDLOTE VARCHAR(20);
  V_CDLOTE1 VARCHAR2(20);
  V_SEQUENCIAL VARCHAR2(20);
  V_NRLANCLOTE VARCHAR(06);
  V_EXISTELOTE VARCHAR(20);
  V_DTINI DATE;
  V_DTFIN DATE;
BEGIN
  CASE P_TIPOMOVI
    WHEN '00' THEN BEGIN
                     SELECT CDREFLOTECTBTO
                       INTO V_CDLOTE
                       FROM TIPOOPERAC A
                      WHERE (CDTIPOOPER = P_TIPOOPERAC)
                        AND (IDENTRSAIDOP = 'E');
                   EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDLOTE := NULL;
                   END;
    WHEN '01' THEN BEGIN
                     SELECT CDREFLOTECTBTO
                       INTO V_CDLOTE
                       FROM TIPOOPERAC A
                      WHERE (CDTIPOOPER = P_TIPOOPERAC)
                        AND (IDENTRSAIDOP = 'S');
                   EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDLOTE := NULL;
                   END;

    WHEN '02' THEN BEGIN
                     SELECT CDREFLOTECTBRET
                       INTO V_CDLOTE
                       FROM  PARAMESTOQUE;
                   EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDLOTE := NULL;
                   END;

    WHEN '03' THEN BEGIN
                     SELECT CDREFLOTECTBPRO
                       INTO V_CDLOTE
                       FROM PARAMESTOQUE;
                   EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDLOTE := NULL;
                   END;

    WHEN '04' THEN BEGIN
                     SELECT CDREFLOTECTBSAI
                       INTO V_CDLOTE
                       FROM  PARAMESTOQUE;
                   EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDLOTE := NULL;
                   END;

    WHEN '05' THEN BEGIN
                     SELECT CDREFLOTECTBIMP
                       INTO V_CDLOTE
                       FROM  PARAMESTOQUE;
                   EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDLOTE := NULL;
                   END;

    WHEN '06' THEN BEGIN
                     SELECT CDREFLOTECTBTP
                       INTO V_CDLOTE
                       FROM TIPOCTPAGAR
                      WHERE CDTPCTPAGAR = P_TIPOOPERAC;
                   EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDLOTE := NULL;
                   END;

    WHEN '07' THEN BEGIN
                     SELECT CDREFLOTECTBTR
                       INTO V_CDLOTE
                       FROM TIPOCTRECEBER
                      WHERE CDTPCTRECEB = P_TIPOOPERAC;
                   EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDLOTE := NULL;
                   END;

    WHEN '08' THEN IF P_TPCREDDEB = 'C' THEN
                       BEGIN
                         SELECT CDREFLOTECTBTCB
                           INTO V_CDLOTE
                           FROM TPCREDBANC
                          WHERE CDTPCREDBANC = P_TIPOOPERAC;
                       EXCEPTION
                         WHEN NO_DATA_FOUND THEN
                           V_CDLOTE := NULL;
                       END;
                   ELSE
                       BEGIN
                         SELECT CDREFLOTECTBTDB
                           INTO V_CDLOTE
                           FROM TPDEBIBANC
                          WHERE CDTPDEBIBANC = P_TIPOOPERAC;
                       EXCEPTION
                         WHEN NO_DATA_FOUND THEN
                          V_CDLOTE := NULL;
                       END;
                   END IF;
    WHEN '09' THEN BEGIN
                     SELECT CDREFLOTECTBL
                       INTO V_CDLOTE
                       FROM PARAMCTBL;
                     V_CDLOTE := V_CDLOTE;
                   EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDLOTE := NULL;
                   END;
    WHEN '10' THEN BEGIN
                     SELECT CDREFLOTECTBTBP
                       INTO V_CDLOTE
                       FROM TIPOBAIXAPAG
                      WHERE CDTPBAIXAPAG = P_TIPOOPERAC;
                   EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDLOTE := NULL;
                   END;

    WHEN '11' THEN BEGIN
                     SELECT CDREFLOTECTBTBR
                       INTO V_CDLOTE
                       FROM TIPOBAIXAREC
                      WHERE CDTPBAIXAREC = P_TIPOOPERAC;
                   EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDLOTE := NULL;
                   END;

    WHEN '12' THEN BEGIN
                     SELECT CDREFLOTECTBTR
                       INTO V_CDLOTE
                       FROM TIPOCTRECEBER
                      WHERE CDTPCTRECEB = P_TIPOOPERAC;
                   EXCEPTION
                      WHEN NO_DATA_FOUND THEN
                       V_CDLOTE := NULL;
                   END;
  END CASE;

  IF V_CDLOTE IS NULL THEN
     BEGIN
       SELECT CDREFLOTECTBL
         INTO V_CDLOTE
         FROM PARAMCTBL;
     EXCEPTION
       WHEN NO_DATA_FOUND THEN
        V_CDLOTE := NULL;
     END;
     IF P_CODLOTE IS NOT NULL THEN
        V_CDLOTE := P_CODLOTE;
     ELSE
        V_CDLOTE := V_CDLOTE || P_TIPOMOVI;
     END IF;
  END IF;

  V_CDLOTE := REPLACE(V_CDLOTE,'[EMP]',P_CDEMPRESA);

  V_CDLOTE := REPLACE(V_CDLOTE,'[FIEM]',P_CDFILIEMIT);

  V_CDLOTE := REPLACE(V_CDLOTE,'[FIRE]',P_CDFILIRECE);

  V_CDLOTE := REPLACE(V_CDLOTE,'[ANO]',SUBSTR(TO_CHAR(P_DTMOVI,'DD/MM/YYYY'),7,4));

  V_CDLOTE := REPLACE(V_CDLOTE,'[MES]',SUBSTR(TO_CHAR(P_DTMOVI,'DD/MM/YYYY'),4,2));

  V_CDLOTE := REPLACE(V_CDLOTE,'[DIA]',SUBSTR(TO_CHAR(P_DTMOVI,'DD/MM/YYYY'),1,2));

  IF (INSTR(V_CDLOTE,'[SEQ]')>0) THEN
     SELECT MAX(CDLOTE)
       INTO V_CDLOTE1
       FROM CAPALOTE
      WHERE CDEMPRESA = P_CDEMPRESA
        AND IDLOTE <> 'L'
        AND CDLOTE LIKE REPLACE(V_CDLOTE,'[SEQ]','') || '%';

     IF V_CDLOTE1 IS NULL THEN
        NOVO_CODIGO_NT(V_CDLOTE,V_SEQUENCIAL,1);
        V_CDLOTE := REPLACE(V_CDLOTE,'[SEQ]',SUBSTR(V_SEQUENCIAL,17,4));
     ELSE
        V_CDLOTE := V_CDLOTE1;
     END IF;
  END IF;

  BEGIN
    SELECT MAX(NRLANCLOTE)
      INTO V_NRLANCLOTE
      FROM LANCLOTE
     WHERE CDEMPRESA = P_CDEMPRESA
       AND CDLOTE = V_CDLOTE;
  EXCEPTION

    WHEN NO_DATA_FOUND THEN
      V_NRLANCLOTE := NULL;
  END;

  BEGIN
    SELECT CDLOTE
      INTO V_EXISTELOTE
      FROM CAPALOTE
     WHERE CDEMPRESA = P_CDEMPRESA
       AND CDLOTE = V_CDLOTE;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
      V_EXISTELOTE := NULL;
  END;

  IF P_TIPOMOVI IN ('06','07','08','09','10','11') THEN
     BEGIN
       SELECT DTINICCTBL,DTFINACCTBL
         INTO V_DTINI, V_DTFIN
         FROM CONTOPECTBL
        WHERE CDEMPRESA = P_CDEMPRESA;
     EXCEPTION
       WHEN NO_DATA_FOUND THEN
        V_DTINI := NULL;
        V_DTFIN := NULL;
     END;
  ELSIF (P_TIPOMOVI = '01') OR (P_TIPOMOVI = '12')  THEN
     BEGIN
        SELECT DTINIINTCONTDFS, DTFININTCONTDFS
          INTO V_DTINI, V_DTFIN
          FROM CONTOPECTBL
         WHERE CDEMPRESA = P_CDEMPRESA;
     EXCEPTION
        WHEN NO_DATA_FOUND THEN
         V_DTINI := NULL;
         V_DTFIN := NULL;
     END;
  ELSE
     BEGIN
        SELECT DTINIINTCONTDFE, DTFININTCONTDFE
          INTO V_DTINI, V_DTFIN
          FROM CONTOPECTBL
         WHERE CDEMPRESA = P_CDEMPRESA;
     EXCEPTION
        WHEN NO_DATA_FOUND THEN
         V_DTINI := NULL;
         V_DTFIN := NULL;
     END;
  END IF;

  IF V_EXISTELOTE IS NULL THEN
    INSERT INTO CAPALOTE
      (CDEMPRESA, CDLOTE, DTINICLOTE, DTFINALOTE,IDTPMOVLOTE,IDLOTE, DTULTATU)
    VALUES
      (P_CDEMPRESA, V_CDLOTE, V_DTINI, V_DTFIN, P_TIPOMOVI, 'D', SYSDATE);
  END IF;

  IF V_NRLANCLOTE IS NULL THEN
      V_NRLANCLOTE := '000001';
  ELSE
     V_NRLANCLOTE := LPAD(TO_CHAR(TO_NUMBER(V_NRLANCLOTE) + 1),6,'0');
  END IF;

  P_CDLOTE := V_CDLOTE;
  P_NRLANCLOTE := V_NRLANCLOTE;
END;
/

CREATE OR REPLACE PROCEDURE CTB_IMP_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 DÉBITO NA CONTA DE ESTORNO E O CRÉDITO NA CONTA DO IMPOSTO A RECOLHER

     CASO IMPOSTO A CONTABILIZAR SEJA POSITIVO O CRÉDITO NA CONTA DE ESTORNO E O DÉDITO NA CONTA DO IMPOSTO A RECOLHER
     */
   IF P_TIPO = '1' THEN /*ESTORNO CRÉDITO PRESUMIDO*/

      /*RETORNA OS PARÂMETROS PARA A CONTABILIZAÇÃO DO ESTORNO DE CRÉDITO 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 SAÍDAS 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 SAÍDAS 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 HISTÓRICO DO LANÇAMENTO*/
         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 RELATÓRIO*/
                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);

              /*DÉBITA 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 CONTÁBIL 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 CONTÁBIL É 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 RELATÓRIO*/
                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 CONTÁBIL 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 CONTÁBIL É 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 PARÂMETROS PARA A CONTABILIZAÇÃO 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 CONTÁBIL 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 HISTÓRICO DO LANÇAMENTO*/
                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 RELATÓRIO*/
              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);

              /*DÉBITA 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 CONTÁBIL 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 CONTÁBIL É 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 PARÂMETROS PARA A CONTABILIZAÇÃO DO ESTORNO DE CRÉDITO 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 SAÍDAS 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 SAÍDAS COM CÓDIGO 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 SAÍDAS 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 HISTÓRICO DO LANÇAMENTO*/
         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 RELATÓRIO*/
                 INSERT INTO CTB_TEMP_CREDPRES (CDFILIAL,  VRTOTSAIDAS, VRCREDPRES, CDCONTCTBLDEB, CDCONTCTBLCRED )
                       VALUES (C_IMP_BA.CDFILIAL, V_VRDIFERENCA, V_VRPARTIDA, V_CONTCTBLPASS, V_CDCONTCTBL);

                 /*DÉBITA 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 CONTÁBIL É 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 RELATÓRIO*/
                 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 CONTÁBIL É 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 PARÂMETROS PARA A CONTABILIZAÇÃO 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 HISTÓRICO DO LANÇAMENTO*/
         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 RELATÓRIO*/
            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);

          /*DÉBITA 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 CONTÁBIL  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 CONTÁBIL É 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 HISTÓRICO DO LANÇAMENTO*/
          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 RELATÓRIO*/
            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);

          /*DÉBITA 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 CONTÁBIL  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 CONTÁBIL É 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;