ALTER TABLE PARAMFISCAL ADD IDUTCREDDIFER VARCHAR2(01) DEFAULT 'N' NOT NULL 
   CONSTRAINT CKC_IDUTCREDDIFER_PARAMFISCAL CHECK (IDUTCREDDIFER IN ('N','S'))
/
ALTER TABLE DETAPURACONTR ADD VRCREDDIFERIDO FLOAT DEFAULT 0 NULL
/
ALTER TABLE DETAPURACONTR ADD VRCONTRIBDIF FLOAT DEFAULT 0 NULL
/
ALTER TABLE DETAPURACONTR ADD VRCONTRIBDIFANT FLOAT DEFAULT 0 NULL
/
ALTER TABLE IMPBAIXAREC ADD NRSEQMAPADIF VARCHAR2(10) NULL
/
CREATE INDEX FIS00734_FK ON IMPBAIXAREC (NRSEQMAPADIF  ASC)
/
ALTER TABLE IMPBAIXAREC 
  	ADD CONSTRAINT FKFIS00734MAPAAPUR FOREIGN KEY (NRSEQMAPADIF )
     		REFERENCES MAPAAPURAC (NRSEQUMAPAPU)
/
CREATE TABLE CONTRIBDIFERIDA 
(
   NRSEQCONTRDIF    	VARCHAR2(10)        NOT NULL,
   NRSEQUMAPAPU     	VARCHAR2(10)        NOT NULL,   
   CDFILIAL         		VARCHAR2(04)        NOT NULL,
   NRLANCTONF       	VARCHAR2(10)        NOT NULL,
   CDCLIENTE        		VARCHAR2(21)        NOT NULL,
   CDIMPOSTO        		VARCHAR2(02)        NOT NULL,
   CDSITUTRIB       		VARCHAR2(02)        NULL,
   CDCONTRIBAPUR    	VARCHAR2(02)        NULL,
   VRALIQUOTA       		FLOAT         	DEFAULT 0   NOT NULL,
   VRCONTABIL       		FLOAT         	DEFAULT 0   NOT NULL,
   VRCONTABILREC    	FLOAT         	DEFAULT 0   NOT NULL,
   VRBASECALC       		FLOAT        	DEFAULT 0   NOT NULL,
   VRBASECALCREC    	FLOAT         	DEFAULT 0   NOT NULL,
   VRCONTNAOREC     	FLOAT         	DEFAULT 0   NOT NULL,
   VRBASENAOREC     	FLOAT         	DEFAULT 0   NOT NULL,
   VRCONTRIBDIF     	FLOAT         	DEFAULT 0   NOT NULL,
   VRCREDDIFERIDO   	FLOAT         	DEFAULT 0   NOT NULL,
   VRCONTRIBDIFAT   	FLOAT         	DEFAULT 0   NOT NULL,
   VRCREDDIFAT      		FLOAT         	DEFAULT 0   NOT NULL,
   VRCONTRIBDIFANT  	FLOAT        	DEFAULT 0   NOT NULL,
   NRSEQMAPADIF     	VARCHAR2(10)        NOT NULL,
   DTRECEBIMENTO    	DATE                      	NULL,
   NRORG                       	NUMBER 		DEFAULT 	 SYS_CONTEXT('nrorg_ctx','nrorg') NOT NULL,
   IDATIVO                    	VARCHAR2(1)     	DEFAULT 'S' NOT NULL
      CONSTRAINT CKC_IDATIVO_CONTRIBDIFERIDA  CHECK (IDATIVO IN ('S','N')),
   DTINCLUSAO             	DATE                   	NULL,
   DTULTATU                  	DATE                  	NULL,
   NRORGINCLUSAO      	NUMBER             	DEFAULT 1 NULL,
   CDOPERINCLUSAO    	VARCHAR2(12)  	DEFAULT '1' NULL,
   NRORGULTATU          	NUMBER            	DEFAULT 1 NULL,
   CDOPERULTATU        	VARCHAR2(12)  	DEFAULT '1',
   CONSTRAINT PK_CONTRIBDIFERIDA PRIMARY KEY (NRSEQCONTRDIF)
)
/
CREATE INDEX FIS00735_FK ON CONTRIBDIFERIDA (NRSEQUMAPAPU ASC)
/
ALTER TABLE CONTRIBDIFERIDA
   ADD CONSTRAINT FKFIS00735MAPAAPURAC  FOREIGN KEY (NRSEQUMAPAPU)
      REFERENCES MAPAAPURAC (NRSEQUMAPAPU)
/
CREATE INDEX FIS00736_FK ON CONTRIBDIFERIDA (CDFILIAL ASC, NRLANCTONF ASC)
/
ALTER TABLE CONTRIBDIFERIDA
   ADD CONSTRAINT FKFIS00736NOTAFISCAL  FOREIGN KEY (CDFILIAL, NRLANCTONF)
      REFERENCES NOTAFISCAL (CDFILIAL, NRLANCTONF)
/
ALTER TABLE CONTRIBDIFERIDA
   ADD CONSTRAINT FKFIS00737CLIENTE  FOREIGN KEY (CDCLIENTE)
      REFERENCES CLIENTE (CDCLIENTE)
/
CREATE INDEX FIS00738_FK ON CONTRIBDIFERIDA (CDIMPOSTO ASC)
/
ALTER TABLE CONTRIBDIFERIDA
   ADD CONSTRAINT FKFIS00738IMPOSTO  FOREIGN KEY (CDIMPOSTO)
      REFERENCES IMPOSTO (CDIMPOSTO)
/
CREATE INDEX FIS00739_FK ON CONTRIBDIFERIDA (NRSEQMAPADIF ASC)
/
ALTER TABLE CONTRIBDIFERIDA
   ADD CONSTRAINT FKFIS00739MAPAAPURAC FOREIGN KEY (NRSEQMAPADIF)
      REFERENCES MAPAAPURAC (NRSEQUMAPAPU) ON DELETE CASCADE
/
CREATE TABLE CONTROLCREDDIF 
(
   NRSEQCREDDIF     	VARCHAR2(10)        NOT NULL,
   NRSEQCONTRDIF    	VARCHAR2(10)        NOT NULL,
   VRCREDDIFERIDO   	FLOAT          	DEFAULT 0     NULL,
   VRCONTRIBDIF    		FLOAT          	DEFAULT 0     NULL,
   VRCONTRIBDIFANT  	FLOAT          	DEFAULT 0     NOT NULL,
   VRCONTRIBDIFAT   	FLOAT         	DEFAULT 0   NOT NULL,
   VRCREDDIFAT      		FLOAT         	DEFAULT 0   NOT NULL,
   CDNATUCREDDIF    	VARCHAR2(02)   	DEFAULT '01'  NULL,
   CDTPCREDITO      	VARCHAR2(03)       	NULL,
   NRSEQMAPADIF     	VARCHAR2(10)        NOT NULL,
   NRORG                       	NUMBER 		DEFAULT 	 SYS_CONTEXT('nrorg_ctx','nrorg') NOT NULL,
   IDATIVO                    	VARCHAR2(1)     	DEFAULT 'S' NOT NULL
      CONSTRAINT CKC_IDATIVO_CONTROLCREDDIF CHECK (IDATIVO IN ('S','N')),
   DTINCLUSAO             	DATE                   	NULL,
   DTULTATU                  	DATE                  	NULL,
   NRORGINCLUSAO      	NUMBER             	DEFAULT 1 NULL,
   CDOPERINCLUSAO    	VARCHAR2(12)  	DEFAULT '1' NULL,
   NRORGULTATU          	NUMBER            	DEFAULT 1 NULL,
   CDOPERULTATU        	VARCHAR2(12)  	DEFAULT '1',
	CONSTRAINT PK_CONTROLCREDDIF PRIMARY KEY (NRSEQCREDDIF)
)
/
CREATE INDEX FIS00740_FK ON CONTROLCREDDIF (NRSEQCONTRDIF ASC)
/
ALTER TABLE CONTROLCREDDIF
   ADD CONSTRAINT FKFIS00740CONTRIBDIFERIDA  FOREIGN KEY (NRSEQCONTRDIF)
      REFERENCES CONTRIBDIFERIDA (NRSEQCONTRDIF) ON DELETE CASCADE
/
CREATE INDEX FIS00741_FK ON CONTROLCREDDIF (NRSEQMAPADIF ASC)
/
ALTER TABLE CONTROLCREDDIF
   ADD CONSTRAINT FKFIS00741MAPAAPURAC  FOREIGN KEY (NRSEQMAPADIF)
      REFERENCES MAPAAPURAC (NRSEQUMAPAPU) ON DELETE CASCADE
/
ALTER TABLE ALIQIMPFIS ADD CDCBENEF VARCHAR2(10)
/
ALTER TABLE ITEMVENDA ADD CDCBENEFIT VARCHAR2(10) 
/
CREATE OR REPLACE PROCEDURE LIBERA_LOTE_VND(
   P_CDFILIAL   IN FILIAL.CDFILIAL%TYPE,
   P_CDCAIXA    IN CAIXA.CDCAIXA%TYPE,
   P_DTREDUZ    IN DATE,
   P_DTEMISSAO  IN DATE,
   P_NRLANC     IN LANCCONT.NRLANCCONT%TYPE,
   P_CDOPERADOR IN LANCCONT.CDOPERINS%TYPE,
   P_CDLOJA     IN CAIXA.CDLOJA%TYPE DEFAULT NULL)
IS
   V_NRLANCLOTE LANCLOTE.NRLANCLOTE%TYPE;
   V_NRLANCCONT LANCCONT.NRLANCCONT%TYPE;
   V_IDCONTGERE CONTOPECTBL.IDCONTGERE%TYPE;
   V_IDCONTCOME CONTOPECTBL.IDCONTCOME%TYPE;
   V_IDLANCINTE VARCHAR2(1);
   V_SEQUENCIAL VARCHAR2(5);
BEGIN
   V_NRLANCCONT := P_NRLANC;
   V_NRLANCLOTE := '0';
   V_SEQUENCIAL := '00001';
   FOR C_RELAC IN (SELECT R.CDEMPRESA, R.CDLOTE, R.NRLANCLOTE, R.NRSEQLANLOTE, R.CDFILIAL, R.NRLANCTONF
                     FROM RELACNFLANCLOTE R, NOTAFISCAL N
                    WHERE R.CDFILIALVND = P_CDFILIAL
                      AND NVL(R.CDCAIXA,'T') = NVL(P_CDCAIXA,'T')
                      AND NVL(R.CDLOJA,'T')  = NVL(P_CDLOJA,'T')
                      AND R.DTREDUCAOZ  = P_DTREDUZ
                      AND R.DTEMISSAO   = P_DTEMISSAO
                      AND R.CDFILIAL    = N.CDFILIAL
                      AND R.NRLANCTONF  = N.NRLANCTONF
                      AND N.NRLANCTBDOC IS NULL) LOOP
      FOR LOTE IN (SELECT LANCLOTE.*
                     FROM LANCLOTE
                    WHERE LANCLOTE.CDEMPRESA  = C_RELAC.CDEMPRESA
                      AND LANCLOTE.CDLOTE     = C_RELAC.CDLOTE
                      AND LANCLOTE.NRLANCLOTE = C_RELAC.NRLANCLOTE
                    ORDER BY  NRLANCLOTE, NRSEQLANLOTE) LOOP
         V_IDLANCINTE := 'I';
         INSERT INTO LANCCONT
            (CDEMPRESA, NRLANCCONT, NRSEQLANC, CDCONTCTBL, CDHISTPADR,
             DTLANCCONT, CDDOCUCONT, IDTIPOLANC, DSHISTLANC, VRLANCAMENT,
             IDLANCCOME, CDCONTCOME, IDLANCSALDO, IDLANCINTE, IDLANCMANI,
             CDOPERINS, DTULTATULAN, IDSALDLANCO, IDSALDLANGE, IDSISTEMA)
         VALUES
            (C_RELAC.CDEMPRESA, V_NRLANCCONT, V_SEQUENCIAL, LOTE.CDCONTCTBL,
             LOTE.CDHISTPADR, LOTE.DTLANCLOTE, LOTE.NRDOCULOTE, 'C',
             LOTE.DSHISTLOTE, LOTE.VRLANCLOTE, LOTE.IDLLOTCOME,
             LOTE.CDLLOTCOME, 'N',V_IDLANCINTE,'N', P_CDOPERADOR, SYSDATE, 'N', 'N', 'VND');
         UPDATE LANCLOTE
            SET LANCLOTE.NRLANCDEFI   = V_NRLANCCONT,
                LANCLOTE.NRSEQUDEFI   = V_SEQUENCIAL
          WHERE LANCLOTE.CDEMPRESA    = LOTE.CDEMPRESA
            AND LANCLOTE.CDLOTE       = LOTE.CDLOTE
            AND LANCLOTE.NRLANCLOTE   = LOTE.NRLANCLOTE
            AND LANCLOTE.NRSEQLANLOTE = LOTE.NRSEQLANLOTE;
         INSERT INTO LANCCCUSTO
            (CDEMPRESA, NRLANCCONT, NRSEQLANC, CDFILIAL, CDCENTCUST, VRLANCCUST, DTCOMPCUSTO)
         (SELECT C_RELAC.CDEMPRESA, V_NRLANCCONT, V_SEQUENCIAL,
                 RATECCUS.CDFILIAL, RATECCUS.CDCENTCUST, RATECCUS.VRRATECCUS, RATECCUS.DTCOMPRATECCUS
            FROM RATECCUS
           WHERE RATECCUS.CDEMPRESA    = LOTE.CDEMPRESA
             AND RATECCUS.CDLOTE       = LOTE.CDLOTE
             AND RATECCUS.NRLANCLOTE   = LOTE.NRLANCLOTE
             AND RATECCUS.NRSEQLANLOTE = LOTE.NRSEQLANLOTE);
         V_NRLANCLOTE := LOTE.NRLANCLOTE;
         V_SEQUENCIAL := LPAD(TO_CHAR(TO_NUMBER(V_SEQUENCIAL) + 1), 5, '0');
      END LOOP;
      UPDATE NOTAFISCAL
         SET NRLANCTBDOC = V_NRLANCCONT
       WHERE CDFILIAL    = C_RELAC.CDFILIAL
         AND NRLANCTONF  = C_RELAC.NRLANCTONF;
  END LOOP;
END;
/
CREATE OR REPLACE FUNCTION SPED_PIS_COFINS_BLOCOC(
   P_NRLANCTONF       IN NOTAFISCAL.NRLANCTONF%TYPE,
   P_CDFILIAL         IN NOTAFISCAL.CDFILIAL%TYPE,
   P_CDCAIXA          IN VENDA.CDCAIXA%TYPE,
   P_NRSEQARQMAG      IN ARQMAGPISCOFINS.NRSEQARQMAG%TYPE,
   P_NRINSJUREST      IN INSCRESTAD.NRINSJURIEST%TYPE,
   P_IDNOVOEST        IN NOTAFISCAL.IDSTATUS%TYPE,
   P_IDENTRSAIDOP     IN NOTAFISCAL.IDENTRSAIDOP%TYPE,
   P_IDSTATUS         IN NOTAFISCAL.IDSTATUS%TYPE,
   P_IDORIGDESTNF     IN NOTAFISCAL.IDORIGDESTNF%TYPE,
   P_CDFILIEMIT       IN NOTAFISCAL.CDFILIEMIT%TYPE,
   P_CDFILIRECE       IN NOTAFISCAL.CDFILIRECE%TYPE,       
   P_CDCLIENTE        IN NOTAFISCAL.CDCLIENTE%TYPE,
   P_CDFORNECED       IN NOTAFISCAL.CDFORNECED%TYPE,
   P_CDSERIE          IN NOTAFISCAL.CDSERIE%TYPE,
   P_NRNOTAFISC       IN NOTAFISCAL.NRNOTAFISC%TYPE,
   P_DTEMISSAO        IN NOTAFISCAL.DTEMISSAO%TYPE,
   P_DTENTRSAID       IN NOTAFISCAL.DTEMISSAO%TYPE,
   P_VRNOTAFISC       IN NOTAFISCAL.VRNOTAFISC%TYPE,
   P_VRCONTABIL       IN IMPOSTONF.VRCONTABILNF%TYPE,
   P_PIS              IN IMPOSTO.CDIMPOSTO%TYPE,
   P_PIS_RET_E        IN IMPOSTO.CDIMPOSTO%TYPE,
   P_PIS_RET_S        IN IMPOSTO.CDIMPOSTO%TYPE,
   P_COFINS           IN IMPOSTO.CDIMPOSTO%TYPE,
   P_COFINS_RET_E     IN IMPOSTO.CDIMPOSTO%TYPE,
   P_COFINS_RET_S     IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ISS_E            IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ISS_S            IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ISS_RET_E        IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ISS_RET_S        IN IMPOSTO.CDIMPOSTO%TYPE,
   P_CONTEST          IN NUMBER,
   P_CDPAIS           IN PAIS.CDPAIS%TYPE,
   P_CDEMPRESA        IN EMPRESA.CDEMPRESA%TYPE,
   P_CONTREGA         IN DOUBLE PRECISION,
   P_IDPGTOFRETE      IN NOTAFISCAL.IDPGTOFRETE%TYPE,
   P_NRACESSONFE      IN NOTAFISCAL.NRACESSONFE%TYPE,
   P_CDMODDOCFISC     IN NOTAFISCAL.CDMODDOCFISC%TYPE,
   P_VRPRODUTOS       IN NOTAFISCAL.VRPRODUTOS%TYPE,
   P_ICMS_ST          IN VARCHAR2,
   P_IPI              IN VARCHAR2,
   P_ICMS             IN VARCHAR2,
   P_DTINICIAL        IN NOTAFISCAL.DTEMISSAO%TYPE,
   P_DTFINAL          IN NOTAFISCAL.DTEMISSAO%TYPE,
   P_VRDESCONTO       IN FLOAT,
   P_CDTIPOOPER       IN NOTAFISCAL.CDTIPOOPER%TYPE,
   P_IDSTATUSNFE      IN NOTAFISCAL.IDSTATUSNFE%TYPE,
   P_VRFRETE          IN FLOAT,
   P_VROUTROS         IN FLOAT,
   P_VRSEGUR          IN FLOAT,
   P_TIPOOPER_COMPL_S IN TIPOOPERAC.CDTIPOOPER%TYPE,
   P_TIPOOPER_COMPL_E IN TIPOOPERAC.CDTIPOOPER%TYPE,
   P_SEQUPROD         IN IMPOSTONF.VRIMPOSTONF%TYPE,
   P_TMPBLCM          IN IMPOSTONF.VRIMPOSTONF%TYPE,
   P_NRNOTAFISCALELE  IN NOTAFISCAL.NRNOTAFISCALELE%TYPE,
   P_LIVROMAG         IN RELACPRODITGEN.CDLIVROMAG%TYPE,
   P_GERADEVOLVEND    IN VARCHAR2) RETURN VARCHAR
AS
   V_REG_C010         VARCHAR2(1000);
   V_REG              VARCHAR2(1000);
   V_COD_PAR          VARCHAR(100);
   V_COD_NAT          VARCHAR2(100);
   V_UNID             VARCHAR2(100);
   V_PRODUTO          VARCHAR2(100);
   V_CSTPIS           VARCHAR2(2);
   V_CSTCOFINS        VARCHAR2(2);
   V_CDNATBCCOFINS    VARCHAR2(2);
   V_CDNATBCPIS       VARCHAR2(2);
   V_CDTPCREDPIS      VARCHAR2(3);
   V_CDTPCREDCOFINS   VARCHAR2(3);
   V_CDFISCALPIS      VARCHAR2(1);
   V_CDFISCALCOFINS   VARCHAR2(1);
   V_TIPOOPER_COMPL_S VARCHAR2(2);
   V_TIPOOPER_COMPL_E VARCHAR2(2);
   V_IDC010           VARCHAR2(20);
   V_COD_CC           VARCHAR2(20);
   V_SEQCCTBL         NUMBER;
   V_SEQUPROD         NUMBER;
   V_TMPBLCM          NUMBER;
   V_SEQITPROD        NUMBER;
   V_CONTREGA         NUMBER;
   V_COUNTPARC        NUMBER;
   V_VRBCPIS          NUMBER;
   V_VRBCCOFINS       NUMBER;
   V_VRCREDPIS        NUMBER;
   V_VRCREDCOFINS     NUMBER;
   V_VRALIQPIS        NUMBER;
   V_VRALIQCOFINS     NUMBER;
   V_VRPISRET         NUMBER;
   V_VRCOFINSRET      NUMBER;
   V_IDATIVO          VARCHAR2(1);
   V_IDGERANOTA       VARCHAR2(1);
   V_VRPRODATIV       NUMBER;
   V_VRBCICMSATIV     NUMBER;
   V_VRICMSATIV       NUMBER;
   V_VRBCSTATIV       NUMBER;
   V_VRSTATIV         NUMBER;
   V_VRPISATIV        NUMBER;
   V_VRCOFINSATIV     NUMBER;
   V_SEQNOTAS         NUMBER;
   V_INSCRICAO        VARCHAR2(14);
   V_VRPIS            NUMBER;
   V_VRCOFINS         NUMBER;
   V_REG_C120         VARCHAR2(1000);
   V_NRDOCIMP         VARCHAR2(10);
   V_NRDRAWBACK       VARCHAR2(20);
   V_IDTPALIQ         VARCHAR2(01);
BEGIN
   V_CONTREGA     := P_CONTREGA;
   V_SEQUPROD     := P_SEQUPROD;
   V_TMPBLCM      := P_TMPBLCM;
   V_IDATIVO      := 'S';
   V_VRPRODATIV   := 0;
   V_VRBCICMSATIV := 0;
   V_VRICMSATIV   := 0;
   V_VRBCSTATIV   := 0;
   V_VRSTATIV     := 0;
   V_VRPISATIV    := 0;
   V_VRCOFINSATIV := 0;
   V_SEQNOTAS     := 0;
   V_IDGERANOTA   := 'S';

   /*SELECIONA O INDICADOR DE PAGAMENTO DAS NOTAS(a prazo ou a vista)*/
   BEGIN
     SELECT SUM(PARC)
       INTO V_COUNTPARC
       FROM (SELECT COUNT(*) AS  PARC
               FROM CONTARECEBER
              WHERE CDFILIAL   = P_CDFILIAL
                AND NRLANCTONF = P_NRLANCTONF
              UNION ALL
             SELECT COUNT(*) AS PARC
               FROM CONTAPAGAR
              WHERE CDFILIAL   = P_CDFILIAL
                AND NRLANCTONF = P_NRLANCTONF);
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_COUNTPARC := 0;
   END;

   IF P_IDENTRSAIDOP = 'E' THEN
      BEGIN
      /*VERIFICA SE A NOTA POSSUI CRÉDITO DE AQUISIÇÃO PARA ATIVO IMOBILIZADO. CASO SIM, GERA C100 SOMENTE SE EXISTIR ITEM QUE NÃO SEJA DO ATIVO.
      OS VALORES REFERENTES ÀS AQUISIÇÕES PARA O ATIVO SÃO GERADOS NO F130*/
         SELECT NVL(SUM(DECODE(IM.CDIMPOSTONFE,P_PIS,IT.VRCONTITIMP,0)),0),
                NVL(SUM(DECODE(IM.CDIMPOSTONFE,P_ICMS,IT.VRBASECALCIT,0)),0), NVL(SUM(DECODE(IM.CDIMPOSTONFE,P_ICMS,IT.VRIMPOSTOIT,0)),0),
                NVL(SUM(DECODE(IM.CDIMPOSTONFE,P_ICMS_ST,IT.VRBASECALCIT,0)),0), NVL(SUM(DECODE(IM.CDIMPOSTONFE,P_ICMS_ST,IT.VRIMPOSTOIT,0)),0),
                NVL(SUM(DECODE(IM.CDIMPOSTONFE,P_PIS,IT.VRIMPOSTOIT,0)),0), NVL(SUM(DECODE(IM.CDIMPOSTONFE,P_COFINS,IT.VRIMPOSTOIT,0)),0)
           INTO V_VRPRODATIV, V_VRBCICMSATIV, V_VRICMSATIV, V_VRBCSTATIV, V_VRSTATIV, V_VRPISATIV, V_VRCOFINSATIV
           FROM ITEMPRODUTO IP, ITEMPROIMPOS IT, IMPOSTO IM
          WHERE IT.CDFILIAL    = P_CDFILIAL
            AND IT.NRLANCTONF  = P_NRLANCTONF
            AND SUBSTR(IT.CDFISCOPERIT,2,3) IN ('406','551','552','553','554','555','604')
            AND IT.CDIMPOSTO   = IM.CDIMPOSTO
            AND IT.CDFISCALIT  = '1'
            AND DECODE(IM.CDIMPOSTONFE,P_PIS,IT.VRIMPOSTOIT,0) > 0
            AND IT.CDFILIAL    = IP.CDFILIAL
            AND IT.NRLANCTONF  = IP.NRLANCTONF
            AND IT.NRSEQITPROD = IP.NRSEQITPROD;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRPRODATIV   :=0;
            V_VRBCICMSATIV :=0;
            V_VRICMSATIV   :=0;
            V_VRBCSTATIV   :=0;
            V_VRSTATIV     :=0;
            V_VRPISATIV    :=0;
            V_VRCOFINSATIV :=0;
      END;
   END IF;

   IF ((V_IDATIVO = 'S') AND (V_VRPISATIV+V_VRCOFINSATIV > 0)) THEN
      BEGIN
      /*VERIFICA SE A NOTA POSSUI OUTRO CFOP ALÉM DO ITEM DE AQUISIÇÃO PARA ATIVO IMOBILIZADO PARA GERAR O C100.*/
         SELECT DISTINCT 'S'
           INTO V_IDGERANOTA
           FROM IMPOSTONF I, IMPOSTO P
          WHERE I.CDFILIAL     = P_CDFILIAL
            AND I.NRLANCTONF   = P_NRLANCTONF
            AND P_IDENTRSAIDOP = 'E'
            AND SUBSTR(I.CDFISCOPERNF,2,3) NOT IN ('406','551','552','553','554','555','604')
            AND I.CDIMPOSTO    = P.CDIMPOSTO;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDGERANOTA := 'N';
      END;

      SELECT MAX(CDINSCESTA)
        INTO V_INSCRICAO
        FROM NOTAFISCAL
       WHERE CDFILIAL   = P_CDFILIAL
         AND NRLANCTONF = P_NRLANCTONF;

      /*INSERE AS NOTAS QUE POSSUEM CRÉDITO DE AQUISIÇÕES DE ATIVO PARA GERAR O REGISTRO F130 NO BLOCO F*/
      V_SEQNOTAS := NVL(V_SEQNOTAS,0) + 1;
      INSERT INTO TMP_REGDADOSSPED_PIS
         (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1, CDCAMPO2, CDCAMPO7, CDESTAB, CDCAMPO3, CDCAMPO4)
       VALUES
         ('F130', V_SEQNOTAS, P_CDFILIAL||P_NRLANCTONF, P_CDFILIAL, P_NRLANCTONF, V_INSCRICAO, P_CONTEST, TO_CHAR(P_DTENTRSAID,'MMYYYY'), P_CDFILIRECE);
   ELSE
      V_IDATIVO := 'N';
   END IF;

   IF P_CDMODDOCFISC IN ('55','65','01','1B','04') AND V_IDGERANOTA = 'S' THEN
      BEGIN
         SELECT SUM(I.VRIMPPIS)    AS VRPIS,
                SUM(I.VRIMPCOFINS) AS VRCOFINS
           INTO V_VRPIS, V_VRCOFINS
           FROM ITVENDAIMPOS I
          WHERE I.CDFILIAL     = P_CDFILIAL
            AND I.CDCAIXA      = P_CDCAIXA
            AND I.NRSEQVENDA   = P_NRLANCTONF
            AND (I.VRPERPIS IS NOT NULL OR I.VRPERCOFINS IS NOT NULL);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRPIS    := 0;
            V_VRCOFINS := 0;
      END;
      /*GERA O REGISTRO C100*/
      FOR REG_C100 IN(SELECT ('|C100'                            ||'|'||
                              DECODE(P_IDENTRSAIDOP,'E','0','1') ||'|'||
                              DECODE(P_IDENTRSAIDOP,'E',DECODE(P_IDSTATUSNFE,'A','0',DECODE(P_IDSTATUS,'E','0','1')), '0')||'|'||/*INDICADOR DE EMISSÃO*/
                              DECODE(P_CDMODDOCFISC,'65','',P_IDORIGDESTNF||DECODE(P_IDORIGDESTNF,'L',DECODE(P_IDENTRSAIDOP,'E',P_CDFILIEMIT,P_CDFILIRECE),NVL(P_CDCLIENTE,P_CDFORNECED)))||'|'||
                              P_CDMODDOCFISC                     ||'|'||
                              DECODE(P_IDSTATUS,'C','02',
                                     DECODE(P_IDENTRSAIDOP,'S', (CASE WHEN P_DTEMISSAO < P_DTINICIAL
                                                                      THEN DECODE(P_CDTIPOOPER,'03','07',V_TIPOOPER_COMPL_S,'07','01')
                                                                      ELSE DECODE(P_CDTIPOOPER,'03','06',V_TIPOOPER_COMPL_S,'06','00') END),
                                                                (CASE WHEN ((P_CDSERIE BETWEEN '890' AND '899') AND (P_CDMODDOCFISC = '55'))
                                                                      THEN '08'
                                                                      ELSE (CASE WHEN P_DTENTRSAID < P_DTINICIAL
                                                                                 THEN DECODE(P_CDTIPOOPER,'03','07',V_TIPOOPER_COMPL_E,'07','01')
                                                                                 ELSE DECODE(P_CDTIPOOPER,'03','06',V_TIPOOPER_COMPL_E,'06','00') END) END))) ||'|'||
                              P_CDSERIE                          ||'|'||
                              DECODE(P_IDSTATUSNFE, 'A', LTRIM(P_NRNOTAFISCALELE, '0'),LTRIM(REPLACE(LTRIM(P_NRNOTAFISC, '0'),' ')))  || '|' ||/*NÚMERO DA NOTA FISCAL*/
                              DECODE(P_IDSTATUS,'C','',DECODE(P_CDMODDOCFISC,'65',P_NRACESSONFE,CASE WHEN P_CDMODDOCFISC = '55' AND P_IDSTATUSNFE = 'A' THEN P_NRACESSONFE
                                      WHEN P_CDMODDOCFISC = '55' AND P_IDSTATUSNFE <> 'A' AND P_DTINICIAL >= '01/04/2012' THEN P_NRACESSONFE ELSE '' END))  || '|' ||  --chave da nota fiscal eletronica
                              TO_CHAR(P_DTEMISSAO,'ddmmyyyy')    ||'|'||
                              CASE WHEN P_DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL THEN TO_CHAR(P_DTENTRSAID,'ddmmyyyy') ELSE TO_CHAR(P_DTFINAL,'ddmmyyyy') END ||'|'||
                              REPLACE(LTRIM(TO_CHAR(ROUND(P_VRNOTAFISC,2),'9999999999990.00')),'.',',') ||'|'||
                              DECODE(NVL(V_COUNTPARC,0),0,'0','1')        ||'|'||
                              REPLACE(LTRIM(TO_CHAR(ROUND(NVL(P_VRDESCONTO,0),2),'9999999999990.00')),'.',',') ||'|'||
                              ''                                          ||'|'|| /*CAMPO 15*/
                              REPLACE(LTRIM(TO_CHAR(ROUND(P_VRCONTABIL-NVL(V_VRPRODATIV,0),2),'9999999999990.00')),'.',',') ||'|'||
                              DECODE(P_IDSTATUS, 'C', '', NVL(P_IDPGTOFRETE,1) )                                                         ||'|'||
                              REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(P_IDSTATUS, 'C', '', NVL(P_VRFRETE,0)) ,2),'999999999990.00')),'.',',') ||'|'||
                              REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(P_IDSTATUS, 'C', '', NVL(P_VRSEGUR,0)) ,2),'999999999990.00')),'.',',') ||'|'||
                              REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(P_IDSTATUS, 'C', '', NVL(P_VROUTROS,0)),2),'999999999990.00')),'.',',') ||'|'|| --campo20
                              REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(P_CDFILIAL,P_NRLANCTONF,P_ICMS,'B','1')-V_VRBCICMSATIV,2),'9999999999990.00')),'.',',') ||'|'||
                              REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(P_CDFILIAL,P_NRLANCTONF,P_ICMS,'I','1'),2)-V_VRICMSATIV,'9999999999990.00')),'.',',') ||'|'||
                              DECODE(P_IDSTATUS,'C','',DECODE(P_CDMODDOCFISC,'65','',REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(P_CDFILIAL, P_NRLANCTONF,P_ICMS_ST, 'B','1')-V_VRBCSTATIV,2),'9999999999990.00')),'.',',')))||'|'||/*BASE DE CALCULO ICMS ST*/
                              DECODE(P_IDSTATUS,'C','',DECODE(P_CDMODDOCFISC,'65','',REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(P_CDFILIAL, P_NRLANCTONF,P_ICMS_ST, 'I','1')-V_VRSTATIV,  2),'9999999999990.00')),'.',',')))||'|'||/*IMPOSTO ICMS ST*/
                              DECODE(P_IDSTATUS,'C','',DECODE(P_CDMODDOCFISC,'65','',REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(P_CDFILIAL, P_NRLANCTONF,P_IPI,     'I','1'),2),             '9999999999990.00')),'.',',')))||'|'||/*VALOR IPI*/
                              REPLACE(LTRIM(TO_CHAR(DECODE(P_CDMODDOCFISC,'65',V_VRPIS,   ROUND(VALOR_IMPOSTO_NFE(P_CDFILIAL,P_NRLANCTONF,P_PIS,   'I','1')-V_VRPISATIV,   2)),    '9999999999990.00')),'.',',') ||'|'||
                              REPLACE(LTRIM(TO_CHAR(DECODE(P_CDMODDOCFISC,'65',V_VRCOFINS,ROUND(VALOR_IMPOSTO_NFE(P_CDFILIAL,P_NRLANCTONF,P_COFINS,'I','1')-V_VRCOFINSATIV,2)),    '9999999999990.00')),'.',',') ||'|'||
                              ''                                         ||'|'||
                              ''                                         ||'|') AS REG0100,
                              P_IDORIGDESTNF||DECODE(P_IDORIGDESTNF,'L',DECODE(P_IDENTRSAIDOP,'E',P_CDFILIEMIT,P_CDFILIRECE),NVL(P_CDCLIENTE,P_CDFORNECED)) AS CD_PARTC
                         FROM DUAL)LOOP

         V_CONTREGA := NVL(V_CONTREGA,0)+1;
         INSERT INTO ARQMAGPISCOFINS
            (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
            (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(P_CONTEST,'000'))||'01'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_C100.REG0100);

         V_COD_PAR:= NULL;

         /* CÓDIGO DO PARTICIPANTE */
         SELECT MAX(CDCHAVEREG)
           INTO V_COD_PAR
           FROM TMP_REGDADOSSPED_PIS
          WHERE CDCHAVEREG = REG_C100.CD_PARTC
            AND CDREGISTRO = '0150'
            AND CDESTAB    = LTRIM(TO_CHAR(P_CONTEST,'000'));

         IF (V_COD_PAR IS NULL) AND (REG_C100.CD_PARTC IS NOT NULL) THEN
            V_SEQUPROD:= NVL(V_SEQUPROD,0)+1;
            INSERT INTO TMP_REGDADOSSPED_PIS
              (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
            VALUES
              ('0150', V_SEQUPROD, REG_C100.CD_PARTC, NULL, LTRIM(TO_CHAR(P_CONTEST,'000')));
         END IF;
      END LOOP;

      IF (P_IDENTRSAIDOP = 'E')  THEN
         BEGIN
            SELECT MAX(NRDOCIMPNFE), MAX(A.NRDRAWBACK)
              INTO V_NRDOCIMP, V_NRDRAWBACK
              FROM DECIMPNFE D, ADICDECIMPNFE A
             WHERE D.CDFILIAL   = P_CDFILIAL
               AND D.NRLANCTONF = P_NRLANCTONF
               AND D.CDFILIAL   = A.CDFILIAL
               AND D.NRLANCTONF = A.NRLANCTONF;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_NRDOCIMP := NULL;
               V_NRDRAWBACK := NULL;
         END;

         /*INSERE O REGISTRO C120 PARA NOTAS FISCAIS DE IMPORTAÇÃO*/
         IF V_NRDOCIMP IS NOT NULL THEN
            V_REG_C120 := '|C120|'   ||
                          '0'        ||'|'||
                          V_NRDOCIMP ||'|'||
                          REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(P_CDFILIAL,P_NRLANCTONF,P_PIS,'I','1'),2),'9999999999990.00')),'.',',')    ||'|'||
                          REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(P_CDFILIAL,P_NRLANCTONF,P_COFINS,'I','1'),2),'9999999999990.00')),'.',',') ||'|'||
                          V_NRDRAWBACK ||'|';
            V_CONTREGA := NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(P_CONTEST,'000'))||'01'||LPAD(RTRIM(V_CONTREGA),22,'0'),V_REG_C120);
         END IF;
      END IF;

      IF P_CDMODDOCFISC = '65' THEN /*Para NFC-e*/
         /*REGISTRO C175*/
         FOR REG_C175 IN (SELECT '|C175'                                                        ||'|'||
                                 CDCFOPPROD                                                     ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(VROPERACAO, '999999999990.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(VEDESCONTO, '999999999990.00')),'.',',') ||'|'||
                                 CDCSTPRODPC                                                    ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(VRBASECALC, '999999999990.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(VRPERPIS,   '999999999990.00')),'.',',') ||'|'||
                                 ''                                                             ||'|'||
                                 ''                                                             ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(TRUNC(VRPIS,2),      '999999999990.00')),'.',',') ||'|'||
                                 CDCSTPRODPC                                                    ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(VRBASECALC, '999999999990.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(VRPERCOFINS,'999999999990.00')),'.',',') ||'|'||
                                 ''                                                             ||'|'||
                                 ''                                                             ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(TRUNC(VRCOFINS,2),   '999999999990.00')),'.',',') ||'|'||
                                 CONTCTBL_SPED(P_IDENTRSAIDOP,'',P_CDTIPOOPER,P_CDFILIAL)       ||'|'||
                                 ''                                                             ||'|' AS REG0175,
                                 VROPERACAO, VRBASECALC, VRPERPIS, VRPIS, VRPERCOFINS, VRCOFINS, CDCFOPPROD, CDCSTPRODPC,
                                 CONTCTBL_SPED(P_IDENTRSAIDOP,'',P_CDTIPOOPER,P_CDFILIAL) AS COD_CTA
                            FROM (SELECT SUM(TRUNC((T.QTPRODVEND*(T.VRUNITVEND+NVL(T.VRUNITVENDCL,0)))-NVL(T.VRDESITVEND,0)+NVL(T.VRACRITVEND,0),2)) AS VROPERACAO,
                                         SUM(NVL(T.VRDESITVEND,0)) AS VEDESCONTO, I.CDCFOPPROD, I.CDCSTPRODPC, I.VRPERCOFINS, I.VRPERPIS,
                                         SUM(DECODE(I.VRPERPIS,0,0,TRUNC((T.QTPRODVEND*(T.VRUNITVEND+NVL(T.VRUNITVENDCL,0))),2)-NVL(T.VRDESITVEND,0)+NVL(T.VRACRITVEND,0))) AS VRBASECALC,
                                         SUM(I.VRIMPPIS)    AS VRPIS,
                                         SUM(I.VRIMPCOFINS) AS VRCOFINS
                                    FROM ITEMVENDA T, ITVENDAIMPOS I
                                   WHERE T.CDFILIAL     = P_CDFILIAL
                                     AND T.NRSEQVENDA   = P_NRLANCTONF
                                     AND T.CDCAIXA      = P_CDCAIXA
                                     AND T.CDFILIAL     = I.CDFILIAL
                                     AND T.CDCAIXA      = I.CDCAIXA
                                     AND T.NRSEQUITVEND = I.NRSEQUITVEND
                                     AND T.NRSEQVENDA   = I.NRSEQVENDA
                                     AND (I.VRPERPIS IS NOT NULL OR I.VRPERCOFINS IS NOT NULL)
                                   GROUP BY I.CDCFOPPROD, I.CDCSTPRODPC, I.VRPERCOFINS, I.VRPERPIS))LOOP

            /*RETIRADO PARA MELHORIA NA PERFORMANCE, CAMPOS NÃO SÃO NECESSÁRIOS PARA SAÍDA
            BEGIN
               SELECT MAX(DECODE(CDIMPOSTONFE,'50',CDTPCRPICOSTNFE,'')) AS CDTPCREDPIS,
                      MAX(DECODE(CDIMPOSTONFE,'60',CDTPCRPICOSTNFE,'')) AS CDTPCREDCOFINS,
                      MAX(DECODE(CDIMPOSTONFE,'50',CDNATUBCPCSTNFE,'')) AS CDNATBCPIS,
                      MAX(DECODE(CDIMPOSTONFE,'60',CDNATUBCPCSTNFE,'')) AS CDNATBCCOFINS
                 INTO V_CDTPCREDPIS, V_CDTPCREDCOFINS, V_CDNATBCPIS, V_CDNATBCCOFINS
                 FROM VENDA VE, ITEMVENOUTIMPOS IP, ITEMVENDA IT, IMPOSTO IM
                WHERE VE.CDFILIAL     = P_CDFILIAL
                  AND VE.NRSEQVENDA   = P_NRLANCTONF
                  AND VE.CDCAIXA      = P_CDCAIXA
                  AND VE.CDFILIAL     = IT.CDFILIAL
                  AND VE.NRSEQVENDA   = IT.NRSEQVENDA
                  AND VE.CDCAIXA      = IT.CDCAIXA
                  AND VE.CDFILIAL     = IP.CDFILIAL
                  AND VE.CDCAIXA      = IP.CDCAIXA
                  AND TRUNC(VE.DTEMISSAONFCE) = IP.DTREDUCAOZ
                  AND IT.CDPRODUTO    = IP.CDPRODUTO
                  AND IP.CDIMPOSTO    = IM.CDIMPOSTO;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  CDNATBCCOFINS  := NULL;
                  CDNATBCPIS     := NULL;
                  CDTPCREDPIS    := NULL;
                  CDTPCREDCOFINS := NULL;
            END;*/

            V_CONTREGA := NVL(V_CONTREGA,0)+1;
            INSERT INTO
               ARQMAGPISCOFINS(NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(P_CONTEST,'000'))||'01'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_C175.REG0175);

            V_COD_NAT := NULL;

            /* CODIGO DO CFOP*/
            SELECT MAX(CDCHAVEREG)
              INTO V_COD_NAT
              FROM TMP_REGDADOSSPED_PIS
             WHERE CDCHAVEREG = REG_C175.CDCFOPPROD
               AND CDREGISTRO = '0400';

            IF (V_COD_NAT IS NULL) AND (REG_C175.CDCFOPPROD IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1,CDESTAB,CDCAMPO2)
               VALUES
                 ('0400', V_SEQUPROD, REG_C175.CDCFOPPROD,NULL,LTRIM(TO_CHAR(P_CONTEST,'000')),P_IDENTRSAIDOP);
            END IF;

            /* CODIGO DA CONTA CONTÁBIL */
            BEGIN
               SELECT MAX(CDCHAVEREG)
                 INTO V_COD_CC
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = REG_C175.COD_CTA
                  AND CDREGISTRO = '0500';
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_COD_CC := NULL;
            END;

            IF (V_COD_CC IS NULL) AND (REG_C175.COD_CTA IS NOT NULL) THEN
               V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
               VALUES
                  ('0500', V_SEQCCTBL, REG_C175.COD_CTA, NULL);
            END IF;
         END LOOP;
         /*ALIMENTA A TABELA TEMPORÁRIA PARA GERAR O BLOCO M - FOI NECESSÁRIO UM SELECT A PARTE PARA GRAVAR AS INFORMAÇÕES
           DE NATUREZA DA RECEITA QUE PÉ POR PRODUTO, ENQUANTO QUE O REGISTRO C175 É POR CST E ALÍQUOTA*/
         /*PARA O CST 05 NÃO É NECESSÁRIO O DETALHAMENTO NAS VENDAS ECF, NFCE E SAT, A PARTIR DA VERSÃO 2.05 DO VALIDADOR, DE AGOSTO DE 2013*/
         FOR C_BLOCOMNFCE IN (SELECT SUM(TRUNC((T.QTPRODVEND*(T.VRUNITVEND+NVL(T.VRUNITVENDCL,0)))-NVL(T.VRDESITVEND,0)+NVL(T.VRACRITVEND,0),2)) AS VROPERACAO,
                                     SUM(DECODE(I.VRPERPIS,0,0,TRUNC((T.QTPRODVEND*(T.VRUNITVEND+NVL(T.VRUNITVENDCL,0))),2)-NVL(T.VRDESITVEND,0)+NVL(T.VRACRITVEND,0))) AS VRBASECALC,
                                     SUM(I.VRIMPPIS)    AS VRPIS,
                                     SUM(I.VRIMPCOFINS) AS VRCOFINS,
                                     I.CDCSTPRODPC, I.VRPERCOFINS, I.VRPERPIS, R.CDNATUREC, CONTCTBL_SPED(P_IDENTRSAIDOP,'',P_CDTIPOOPER,P_CDFILIAL) AS COD_CTA
                                FROM ITEMVENDA T, ITVENDAIMPOS I, RELACPRODITGEN R
                               WHERE T.CDFILIAL     = P_CDFILIAL
                                 AND T.NRSEQVENDA   = P_NRLANCTONF
                                 AND T.CDCAIXA      = P_CDCAIXA
                                 AND T.CDFILIAL     = I.CDFILIAL
                                 AND T.CDCAIXA      = I.CDCAIXA
                                 AND T.NRSEQUITVEND = I.NRSEQUITVEND
                                 AND T.NRSEQVENDA   = I.NRSEQVENDA
                                 AND (I.VRPERPIS IS NOT NULL OR I.VRPERCOFINS IS NOT NULL)
                                 AND ((CDCSTPRODPC <> '05') OR (CDCSTPRODPC = '05' AND P_DTEMISSAO < '01/08/2013'))
                                 AND T.CDPRODUTO     = R.CDPRODUTO(+)
                                 AND P_LIVROMAG      = R.CDLIVROMAG(+)
                               GROUP BY I.CDCFOPPROD, I.CDCSTPRODPC, I.VRPERCOFINS, I.VRPERPIS, R.CDNATUREC,
                                     CONTCTBL_SPED(P_IDENTRSAIDOP,'',P_CDTIPOOPER,P_CDFILIAL)) LOOP

            /*INSERE O VALOR REFERENTE AO PIS PARA SAÍDAS(DÉBITO)*/
            V_TMPBLCM:= NVL(V_TMPBLCM,0)+1;
            INSERT INTO TMP_REGBLOCOM_PIS
               (CHAVENOTA,CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT,VRIMPRETIDO,VRTOTNF,CDNATUREC,CDCONTCTBL)
            VALUES
               ('C175'||P_CDFILIAL||P_NRLANCTONF,'M200',V_TMPBLCM,V_CDTPCREDPIS,C_BLOCOMNFCE.VRBASECALC,C_BLOCOMNFCE.VRPERPIS,'P',C_BLOCOMNFCE.VRPIS,C_BLOCOMNFCE.CDCSTPRODPC,P_CDFILIAL,V_CDNATBCPIS,0,C_BLOCOMNFCE.VROPERACAO,C_BLOCOMNFCE.CDNATUREC,C_BLOCOMNFCE.COD_CTA);

            /*INSERE O VALOR REFERENTE AO COFINS SAÍDAS(DÉBITO)*/
            V_TMPBLCM:= NVL(V_TMPBLCM,0)+1;
            INSERT INTO TMP_REGBLOCOM_PIS
               (CHAVENOTA,CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT,VRIMPRETIDO,VRTOTNF,CDNATUREC,CDCONTCTBL)
            VALUES
               ('C175'||P_CDFILIAL||P_NRLANCTONF,'M600',V_TMPBLCM,V_CDTPCREDCOFINS,C_BLOCOMNFCE.VRBASECALC,C_BLOCOMNFCE.VRPERCOFINS,'P',C_BLOCOMNFCE.VRCOFINS,C_BLOCOMNFCE.CDCSTPRODPC,P_CDFILIAL,V_CDNATBCCOFINS,0,C_BLOCOMNFCE.VROPERACAO,C_BLOCOMNFCE.CDNATUREC,C_BLOCOMNFCE.COD_CTA);
         END LOOP;
      ELSE
         V_SEQITPROD:=NULL;
         /*REGISTRO C170*/
         FOR REG_C170 IN (SELECT P.CDARVPROD                                                       ||'|'||
                                 ''                                                                ||'|'|| /*DESCRIÇÃO COMPLEMENTAR*/
                                 REPLACE(LTRIM(TO_CHAR(ROUND(QTITEMPROD,5),'999999900.00000')),'.',',')     ||'|'||
                                 P.SGUNIDADE                                                       ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(I.VRCONTPIS,'9999999999900.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(IP.VRDESCITEM,'9999999999900.00')),'.',',') ||'|'||
                                 '0'                                                               ||'|'||/*MOVIMENTAÇÃO FÍSICA*/
                                 IT.CDSITUTRIBIT                                                   ||'|'||
                                 IT.CDFISCOPERIT                                                   ||'|'||
                                 IT.CDFISCOPERIT                                                   ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IT.CDFISCALIT, '1', IT.VRBASECALCIT, 0),2), '999999999990.00')), '.', ',')                                    || '|' ||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IT.CDFISCALIT, '1', IT.VRALIQITEM, 0),2), '999999999990.00')), '.', ',')                                      || '|' ||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IT.CDFISCALIT, '1', IT.VRIMPOSTOIT, 0),2), '999999999990.00')), '.', ',')                                     || '|' ||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,P_ICMS_ST,'B','1'),2), '999999999990.00')), '.', ',')|| '|' || --16
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,P_ICMS_ST,'A','1'),2), '999999999990.00')), '.', ',')|| '|' || --17
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,P_ICMS_ST,'I','1'),2), '999999999990.00')), '.', ',')|| '|' || --18
                                 ''                                                                || '|' || -- indicador de apurcao do IPI CAMPO 19
                                (SELECT CDSITUTRIBITNFE
                                   FROM ITEMPROIMPOS N, IMPOSTO IM
                                  WHERE IP.CDFILIAL    = N.CDFILIAL
                                    AND IP.NRLANCTONF  = N.NRLANCTONF
                                    AND IP.NRSEQITPROD = N.NRSEQITPROD
                                    AND N.NRITPROIMPOS   = '1'
                                    AND N.CDIMPOSTO    = IM.CDIMPOSTO
                                    AND IM.CDIMPOSTONFE   = P_IPI)                                 || '|' ||/*CST DO IPI*/
                                 ''                                                                || '|' || -- COdigo enquadramento IPI campo 21
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,P_IPI,'B','1'),2), '999999999990.00')), '.', ',')  || '|' ||/*BC DO IPI*/
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,P_IPI,'A','1'),2), '9990.00')), '.', ',')  || '|' ||/*ALI IPI*/
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,P_IPI,'I','1'),2), '999999999990.00')), '.', ',') /*VALOR DO IPI*/   AS PARTE1,                                 
								         REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NVL(I.IDUTVLRQTDEIMPO,'N'),'N',I.VRBASEPIS,''),2),'9999999999990.00')),'.',',') ||'|'||/*BASE CALCULO PIS*/
                                 REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NVL(I.IDUTVLRQTDEIMPO,'N'),'N',I.VRALIQPIS,''),4),'990.0000')),'.',',') ||'|'||/*ALIQUOTA PIS*/
                                 REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NVL(I.IDUTVLRQTDEIMPO,'N'),'S',I.VRBASEPIS,''),2),'9999999999990.00')),'.',',')  ||'|'|| /*QUANTIDADE BC PIS*/
                                 REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NVL(I.IDUTVLRQTDEIMPO,'N'),'S',I.VRALIQPIS,''),4),'990.0000')),'.',',')  ||'|'|| /*ALIQUOTA PIS EM REAIS*/                                 
								         REPLACE(LTRIM(TO_CHAR(ROUND(I.VRIMPPIS,2),'9999999999990.00')),'.',',') /*VR IMPOSTO PIS*/ AS PARTE2,
                                 REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NVL(I.IDUTVLRQTDEIMPO,'N'),'N',I.VRBASECOFINS,''),2),'9999999999990.00')),'.',',') ||'|'||/*BASE CALCULO COFINS*/
                                 REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NVL(I.IDUTVLRQTDEIMPO,'N'),'N',I.VRALICOFINS,''),4),'990.0000')),'.',',') ||'|'||/*ALIQUOTA COFINS*/
                                 REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NVL(I.IDUTVLRQTDEIMPO,'N'),'S',I.VRBASECOFINS,''),2),'9999999999990.00')),'.',',') ||'|'|| /*QUANTIDADE BC COFINS*/
                                 REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NVL(I.IDUTVLRQTDEIMPO,'N'),'S',I.VRALICOFINS,''),4),'990.0000')),'.',',') ||'|'|| /*ALIQOTA EM QUANTIDADE COFINS*/
                                 REPLACE(LTRIM(TO_CHAR(ROUND(I.VRIMPCOFINS,2),'9999999999990.00')),'.',',') ||'|'||/*VR IMPOSTO COFINS*/
                                 CONTCTBL_SPED(P_IDENTRSAIDOP,P.CDPRODUTO,P_CDTIPOOPER,DECODE(P_IDENTRSAIDOP,'E',P_CDFILIRECE,P_CDFILIEMIT)) ||'|' /*CÓDIGO DA CONTA ANALÍTICA CONTÁBIL */   AS PARTE3,
                                 P.CDPRODUTO, P.SGUNIDADE,CDFISCOPERIT,DSCDFISOPEIT,CDTPCREDPICOITE,IT.NRSEQITPROD,CDARVPROD, CDNATUREC, IP.VRTOTAITEM, I.VRCONTPIS, I.VRCONTCOFINS,
                                 CONTCTBL_SPED(P_IDENTRSAIDOP,P.CDPRODUTO,P_CDTIPOOPER,DECODE(P_IDENTRSAIDOP,'E',P_CDFILIRECE,P_CDFILIEMIT)) AS COD_CTA,
                                 IP.CDPRODNCMTRANS AS CDCLASFISC
                            FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, PRODUTO P, IMPOSTO IM, RELACPRODITGEN R,
                                 (SELECT SUM(DECODE(IM.CDIMPOSTONFE,P_PIS,I.VRCONTITIMP,0)) AS VRCONTPIS,
                                         SUM(DECODE(IM.CDIMPOSTONFE,P_COFINS,I.VRCONTITIMP,0)) AS VRCONTCOFINS,
                                         SUM(DECODE(IM.CDIMPOSTONFE,P_PIS,DECODE(I.CDFISCALIT,'1',I.VRBASECALCIT,0),0)) AS VRBASEPIS,
                                         SUM(DECODE(IM.CDIMPOSTONFE,P_COFINS,DECODE(I.CDFISCALIT,'1',I.VRBASECALCIT,0),0)) AS VRBASECOFINS,
                                         SUM(DECODE(IM.CDIMPOSTONFE,P_PIS,DECODE(I.CDFISCALIT,'1',I.VRIMPOSTOIT,0),0)) AS VRIMPPIS,
                                         SUM(DECODE(IM.CDIMPOSTONFE,P_COFINS,DECODE(I.CDFISCALIT,'1',I.VRIMPOSTOIT,0),0)) AS VRIMPCOFINS,
                                         MAX(DECODE(IM.CDIMPOSTONFE,P_PIS,DECODE(I.CDFISCALIT,'1',I.VRALIQITEM,0),'')) AS VRALIQPIS,
                                         MAX(DECODE(IM.CDIMPOSTONFE,P_COFINS,DECODE(I.CDFISCALIT,'1',I.VRALIQITEM,0),'')) AS VRALICOFINS,
                                         I.CDFILIAL, I.NRLANCTONF, I.NRSEQITPROD, IM.IDUTVLRQTDEIMPO
                                    FROM ITEMPROIMPOS I, IMPOSTO IM
                                   WHERE I.CDFILIAL     = P_CDFILIAL
                                     AND I.NRLANCTONF   = P_NRLANCTONF
                                     AND I.NRITPROIMPOS  = '1'
                                     AND I.CDIMPOSTO     = IM.CDIMPOSTO
                                     AND IM.CDIMPOSTONFE IN (P_PIS, P_COFINS)
                                   GROUP BY I.CDFILIAL, I.NRLANCTONF, I.NRSEQITPROD, IM.IDUTVLRQTDEIMPO) I
                           WHERE IT.NRLANCTONF   = IP.NRLANCTONF
                             AND IT.CDFILIAL     = IP.CDFILIAL
                             AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                             AND IT.CDFILIAL     = P_CDFILIAL
                             AND IT.NRLANCTONF   = P_NRLANCTONF
                             AND IT.CDIMPOSTO    = IM.CDIMPOSTO
                             AND IM.CDIMPOSTONFE = P_ICMS
                             AND IP.CDPRODUTO    = P.CDPRODUTO
                             AND P.CDPRODUTO     = R.CDPRODUTO(+)
                             AND P_LIVROMAG      = R.CDLIVROMAG(+)
                             AND IT.NRITPROIMPOS = '1'
                             AND ROUND(IP.QTITEMPROD,5)   > 0
                             AND IT.CDFILIAL     = I.CDFILIAL(+)
                             AND IT.NRLANCTONF   = I.NRLANCTONF(+)
                             AND IT.NRSEQITPROD  = I.NRSEQITPROD(+)
                             AND ((P_IDENTRSAIDOP = 'E' AND SUBSTR(IT.CDFISCOPERIT,2,3) NOT IN ('406','551','552','553','554','555','604') AND V_IDATIVO = 'S') OR
                                   V_IDATIVO = 'N')
                           ORDER BY IP.NRSEQITPROD)LOOP

            V_SEQITPROD     := NVL(V_SEQITPROD,0)+1;
            V_CDNATBCCOFINS := NULL;
            V_CDNATBCPIS    := NULL;
            V_CSTCOFINS     := NULL;
            V_CSTPIS        := NULL;
            V_VRBCPIS       := NULL;
            V_VRBCCOFINS    := NULL;
            V_VRCREDPIS     := NULL;
            V_VRCREDCOFINS  := NULL;
            V_VRALIQPIS     := NULL;
            V_VRALIQCOFINS  := NULL;
            V_VRPISRET      := NULL;
            V_VRCOFINSRET   := NULL;

            BEGIN
               SELECT MAX(DECODE(IM.CDIMPOSTONFE,P_COFINS,LPAD(I.CDNATUBCALPCIT,2,'0'),''))  AS CDNATUBCCOFINS,
                      MAX(DECODE(IM.CDIMPOSTONFE,P_PIS,LPAD(I.CDNATUBCALPCIT,2,'0'),''))  AS CDNATUBCPIS,
                      MAX(DECODE(IM.CDIMPOSTONFE,P_COFINS,I.CDSITUTRIBITNFE,'')) AS CSTCOFINS,
                      MAX(DECODE(IM.CDIMPOSTONFE,P_PIS,I.CDSITUTRIBITNFE,'')) AS CSTPIS,
                      MAX(DECODE(IM.CDIMPOSTONFE,P_PIS,I.CDTPCREDPICOITE,'')) AS TPCREDPIS,
                      MAX(DECODE(IM.CDIMPOSTONFE,P_COFINS,I.CDTPCREDPICOITE,'')) AS TPCREDCOFINS,
                      MAX(DECODE(IM.CDIMPOSTONFE,P_PIS,I.CDFISCALIT,'')) AS CDFISCALPIS,
                      MAX(DECODE(IM.CDIMPOSTONFE,P_PIS,I.CDFISCALIT,'')) AS CDFISCALCOFINS,
                      MAX(DECODE(IM.CDIMPOSTONFE,P_PIS,DECODE(I.CDFISCALIT,'1',VRBASECALCIT,0),'')) AS VRBCPIS,
                      MAX(DECODE(IM.CDIMPOSTONFE,P_COFINS,DECODE(I.CDFISCALIT,'1',VRBASECALCIT,0),'')) AS VRBCCOFINS,
                      MAX(DECODE(IM.CDIMPOSTONFE,P_PIS,DECODE(I.CDFISCALIT,'1',VRIMPOSTOIT,0),'')) AS VRCREDPIS,
                      MAX(DECODE(IM.CDIMPOSTONFE,P_COFINS,DECODE(I.CDFISCALIT,'1',VRIMPOSTOIT,0),'')) AS VRCREDCOFINS,
                      MAX(DECODE(IM.CDIMPOSTONFE,P_PIS,VRALIQITEM,'')) AS ALIQPIS,
                      MAX(DECODE(IM.CDIMPOSTONFE,P_COFINS,VRALIQITEM,'')) AS ALIQCOFINS,
                      0 AS VRPISRET,
                      0 AS VRCOFINSRET,
                      MAX(DECODE(NVL(IDUTVLRQTDEIMPO,'N'),'N','P','Q')) AS IDUTVLRQTDEIMPO
                 INTO V_CDNATBCCOFINS, V_CDNATBCPIS, V_CSTCOFINS, V_CSTPIS, V_CDTPCREDPIS,
                      V_CDTPCREDCOFINS, V_CDFISCALPIS, V_CDFISCALCOFINS, V_VRBCPIS, V_VRBCCOFINS,
                      V_VRCREDPIS, V_VRCREDCOFINS, V_VRALIQPIS, V_VRALIQCOFINS, V_VRPISRET, V_VRCOFINSRET, V_IDTPALIQ
                 FROM ITEMPROIMPOS I, IMPOSTO IM
                WHERE ((IM.CDIMPOSTONFE = P_PIS) OR (IM.CDIMPOSTONFE = P_PIS_RET_E) OR (IM.CDIMPOSTONFE = P_PIS_RET_S) OR
                       (IM.CDIMPOSTONFE = P_COFINS) OR (IM.CDIMPOSTONFE = P_COFINS_RET_E) OR (IM.CDIMPOSTONFE = P_COFINS_RET_S))
                  AND IM.CDIMPOSTO   = I.CDIMPOSTO
                  AND I.NRSEQITPROD  = REG_C170.NRSEQITPROD
                  AND I.CDFILIAL     = P_CDFILIAL
                  AND I.NRLANCTONF   = P_NRLANCTONF
                  AND I.NRITPROIMPOS = '1';
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                 IF P_IDENTRSAIDOP = 'S' THEN
                    V_CSTPIS    := '08';
                    V_CSTCOFINS := '08';
                 ELSE
                    V_CSTPIS    := '74';
                    V_CSTCOFINS := '74';
                 END IF;
                 V_CDNATBCCOFINS := NULL;
                 V_CDNATBCPIS    := NULL;
            END;

            V_REG:= '|C170|'||LPAD(V_SEQITPROD,3,'0')||'|'||REG_C170.PARTE1||'|'||V_CSTPIS||'|'||REG_C170.PARTE2||'|'||V_CSTCOFINS||'|'||REG_C170.PARTE3;
            V_CONTREGA := NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(P_CONTEST,'000'))||'01'||LPAD(RTRIM(V_CONTREGA),22,'0'),V_REG);

            /*INSERE OS VALORES DE CRÉDITO PARA AS NOTAS DE ENTRADA NA TABELA TEMPORARIA*/
            IF (P_IDENTRSAIDOP = 'E')  THEN
               /*INSERE O VALOR REFERENTE AO PIS ENTRADA*/
               IF (V_CSTPIS IN ('50','51','52','53','54','55','56','60','61','62','63','64','65','66','98')) AND (V_VRBCPIS>0)/*CDFISCALPIS = '1' AND VRALIQPIS > 0*/ THEN
                  V_TMPBLCM:= NVL(V_TMPBLCM,0)+1;
                  INSERT INTO TMP_REGBLOCOM_PIS
                     (CHAVENOTA,CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT)
                  VALUES
                     ('C170'||P_CDFILIAL||P_NRLANCTONF,'M100',V_TMPBLCM,V_CDTPCREDPIS,V_VRBCPIS,V_VRALIQPIS,V_IDTPALIQ,V_VRCREDPIS,V_CSTPIS,P_CDFILIRECE,V_CDNATBCPIS);
               END IF;

               /*INSERE O VALOR REFERENTE AO COFINS ENTRADA*/
               IF (V_CSTCOFINS IN ('50','51','52','53','54','55','56','60','61','62','63','64','65','66','98')) AND (V_VRBCCOFINS>0)/*CDFISCALCOFINS = '1' AND VRALIQCOFINS > 0*/ THEN
                  V_TMPBLCM:= NVL(V_TMPBLCM,0)+1;
                  INSERT INTO TMP_REGBLOCOM_PIS
                     (CHAVENOTA,CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT)
                  VALUES
                     ('C170'||P_CDFILIAL||P_NRLANCTONF,'M500',V_TMPBLCM,V_CDTPCREDCOFINS,V_VRBCCOFINS,V_VRALIQCOFINS,V_IDTPALIQ,V_VRCREDCOFINS,V_CSTCOFINS,P_CDFILIRECE,V_CDNATBCCOFINS);
               END IF;
            ELSE
               /*INSERE O VALOR REFERENTE AO PIS PARA SAÍDAS(DÉBITO)*/
               V_TMPBLCM:= NVL(V_TMPBLCM,0)+1;
               INSERT INTO TMP_REGBLOCOM_PIS
                  (CHAVENOTA,CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT,VRIMPRETIDO,VRTOTNF,CDNATUREC,CDESTAB,NRINSJUREST,CDCONTCTBL)
               VALUES
                  ('C170'||P_CDFILIAL||P_NRLANCTONF,'M200',V_TMPBLCM,V_CDTPCREDPIS,V_VRBCPIS,V_VRALIQPIS,V_IDTPALIQ,V_VRCREDPIS,V_CSTPIS,P_CDFILIEMIT,V_CDNATBCPIS,V_VRPISRET,REG_C170.VRCONTPIS,REG_C170.CDNATUREC,LTRIM(TO_CHAR(P_CONTEST,'000')),P_NRINSJUREST,REG_C170.COD_CTA);

               /*INSERE O VALOR REFERENTE AO COFINS SAÍDAS(DÉBITO)*/
               V_TMPBLCM:= NVL(V_TMPBLCM,0)+1;
               INSERT INTO TMP_REGBLOCOM_PIS
                  (CHAVENOTA,CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT,VRIMPRETIDO,VRTOTNF,CDNATUREC,CDESTAB,NRINSJUREST,CDCONTCTBL)
               VALUES
                  ('C170'||P_CDFILIAL||P_NRLANCTONF,'M600',V_TMPBLCM,V_CDTPCREDCOFINS,V_VRBCCOFINS,V_VRALIQCOFINS,V_IDTPALIQ,V_VRCREDCOFINS,V_CSTCOFINS,P_CDFILIEMIT,V_CDNATBCCOFINS,V_VRCOFINSRET,REG_C170.VRCONTCOFINS,REG_C170.CDNATUREC,LTRIM(TO_CHAR(P_CONTEST,'000')),P_NRINSJUREST,REG_C170.COD_CTA);
            END IF;

            V_UNID    := NULL;
            V_COD_NAT := NULL;
            V_PRODUTO := NULL;

            /* CODIGO DO CFOP*/
            SELECT MAX(CDCHAVEREG)
              INTO V_COD_NAT
              FROM TMP_REGDADOSSPED_PIS
             WHERE CDCHAVEREG = REG_C170.CDFISCOPERIT
               AND CDREGISTRO = '0400'
               AND CDESTAB    = LTRIM(TO_CHAR(P_CONTEST,'000'));
            IF (V_COD_NAT IS NULL) AND (REG_C170.CDFISCOPERIT IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1,CDESTAB,CDCAMPO2)
               VALUES
                  ('0400', V_SEQUPROD, REG_C170.CDFISCOPERIT,NULL,LTRIM(TO_CHAR(P_CONTEST,'000')),P_IDENTRSAIDOP);
            END IF;

            /* UNIDADE DE MEDIDA */
            SELECT MAX(CDCHAVEREG)
              INTO V_UNID
              FROM TMP_REGDADOSSPED_PIS
             WHERE CDCHAVEREG = REG_C170.SGUNIDADE
               AND CDREGISTRO = '0190'
               AND CDESTAB    = LTRIM(TO_CHAR(P_CONTEST,'000'));
            IF (V_UNID IS NULL) AND (REG_C170.SGUNIDADE IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
               VALUES
                  ('0190', V_SEQUPROD, REG_C170.SGUNIDADE,NULL,LTRIM(TO_CHAR(P_CONTEST,'000')));
            END IF;

            /* CODIGO DO PRODUTO */
            SELECT MAX(CDCHAVEREG)
              INTO V_PRODUTO
              FROM TMP_REGDADOSSPED_PIS
             WHERE CDCHAVEREG = REG_C170.CDARVPROD
               AND CDREGISTRO = '0200'
               AND CDESTAB    = LTRIM(TO_CHAR(P_CONTEST,'000'));
            IF (V_PRODUTO IS NULL) AND (REG_C170.CDARVPROD IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB,CDCAMPO4)
               VALUES
                  ('0200', V_SEQUPROD, REG_C170.CDARVPROD,NULL,LTRIM(TO_CHAR(P_CONTEST,'000')),REG_C170.CDCLASFISC);
            END IF;

            /* CODIGO DA CONTA CONTÁBIL */
            BEGIN
               SELECT MAX(CDCHAVEREG)
                 INTO V_COD_CC
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = REG_C170.COD_CTA
                  AND CDREGISTRO = '0500';
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_COD_CC := NULL;
            END;

            IF (V_COD_CC IS NULL) AND (REG_C170.COD_CTA IS NOT NULL) THEN
               V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
               VALUES
                  ('0500', V_SEQCCTBL, REG_C170.COD_CTA, NULL);
            END IF;
         END LOOP;
      END IF;
   END IF;

   /*INSERE AS NOTAS DE MODELO 02 PARA GERAR O REGISTRO C380 - REGISTRO GERADO NO BLOCO 0*/
   IF P_IDENTRSAIDOP = 'S' AND P_CDMODDOCFISC = '02' THEN
      V_SEQUPROD:= NVL(V_SEQUPROD,0) + 1;
      INSERT INTO TMP_REGDADOSSPED_PIS
         (CDREGISTRO,CDCONTREGI,CDCHAVEREG,CDCAMPO1,CDESTAB,CDCAMPO3,CDCAMPO4,CDCAMPO5,CDCAMPO6,CDCAMPO7,CDCAMPO8,CDCAMPO9,NRINSJUREST)
      VALUES
         ('C380',V_SEQUPROD,P_NRLANCTONF||P_CDFILIAL,P_DTEMISSAO,P_CONTEST,P_IDSTATUS,P_CDFILIAL, P_NRLANCTONF,P_NRNOTAFISC,P_CDFILIEMIT,P_VRNOTAFISC,P_CDTIPOOPER,P_NRINSJUREST);
   END IF;

   /*REGISTRO C500*/
   IF P_CDMODDOCFISC IN ('06','29','28') THEN
      FOR REG_C500 IN (SELECT ('|C500'                            ||'|'||
                              P_IDORIGDESTNF||DECODE(P_IDORIGDESTNF,'L',DECODE(P_IDENTRSAIDOP,'E',P_CDFILIEMIT,P_CDFILIRECE),NVL(P_CDCLIENTE,P_CDFORNECED))||'|'||
                              P_CDMODDOCFISC                     ||'|'||
                              DECODE(P_IDSTATUS,'C','02',DECODE(P_IDENTRSAIDOP,'S', (CASE WHEN P_DTEMISSAO < P_DTINICIAL THEN DECODE(P_CDTIPOOPER,'03','07',P_TIPOOPER_COMPL_S,'07','01')
                                      ELSE DECODE(P_CDTIPOOPER,'03','06',P_TIPOOPER_COMPL_S,'06','00')END),(CASE WHEN P_DTENTRSAID < P_DTINICIAL THEN DECODE(P_CDTIPOOPER,'03','07',P_TIPOOPER_COMPL_E,'07','01')
                                         ELSE DECODE(P_CDTIPOOPER,'03','06',P_TIPOOPER_COMPL_E,'06','00')END))) ||'|'||
                              P_CDSERIE                          ||'|'||
                              ''                                 ||'|'||/*SUBSERIE*/
                              SUBSTR(LPAD(NVL(P_NRNOTAFISC,P_NRACESSONFE),10,'0'),2,9)                      ||'|'||
                              TO_CHAR(P_DTEMISSAO,'ddmmyyyy')    ||'|'||
                              CASE WHEN P_DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL THEN TO_CHAR(P_DTENTRSAID,'ddmmyyyy') ELSE TO_CHAR(P_DTFINAL,'ddmmyyyy') END  ||'|'||
                              REPLACE(LTRIM(TO_CHAR(ROUND(P_VRNOTAFISC,2),'9999999999990.00')),'.',',') ||'|'||
                              REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NF(P_CDFILIAL,P_NRLANCTONF,P_ICMS,'I','1'),2),'9999999999990.00')),'.',',') ||'|'||
                              '' ||'|'|| /*CÓDIGO INFORMAÇÃO*/
                              REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NF(P_CDFILIAL,P_NRLANCTONF,P_PIS,'I','1'),2),'9999999999990.00')),'.',',') ||'|'||
                              REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NF(P_CDFILIAL,P_NRLANCTONF,P_COFINS,'I','1'),2),'9999999999990.00')),'.',',') ||'|') AS REGC500,
                              P_IDORIGDESTNF||DECODE(P_IDORIGDESTNF,'L',DECODE(P_IDENTRSAIDOP,'E',P_CDFILIEMIT,P_CDFILIRECE),NVL(P_CDCLIENTE,P_CDFORNECED)) AS CD_PARTC
                         FROM DUAL)LOOP

         V_CONTREGA := NVL(V_CONTREGA,0)+1;
         INSERT INTO ARQMAGPISCOFINS
            (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
            (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(P_CONTEST,'000'))||'04'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_C500.REGC500);

         V_COD_PAR:=NULL;
         /*CÓDIGO DO PARTICIPANTE*/
         SELECT MAX(CDCHAVEREG)
           INTO V_COD_PAR
           FROM TMP_REGDADOSSPED_PIS
          WHERE CDCHAVEREG = REG_C500.CD_PARTC
            AND CDREGISTRO = '0150'
            AND CDESTAB   = LTRIM(TO_CHAR(P_CONTEST,'000'));

         IF (V_COD_PAR IS NULL) AND (REG_C500.CD_PARTC IS NOT NULL) THEN
            V_SEQUPROD:= NVL(V_SEQUPROD,0)+1;
            INSERT INTO TMP_REGDADOSSPED_PIS
               (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
            VALUES
               ('0150', V_SEQUPROD, REG_C500.CD_PARTC, NULL, LTRIM(TO_CHAR(P_CONTEST,'000')));
         END IF;

         /*C501 COMPLEMENTO DO DOCUMENTO DE TRANSPORTE PIS*/
         FOR C_REG_C501 IN (SELECT '|C501'                                                               ||'|'||
                                    IT.CDSITUTRIBITNFE                                                   ||'|'||
                                    REPLACE(LTRIM(TO_CHAR(SUM(IP.VRTOTAITEM),'9999999999900.00')),'.',',')    ||'|'||
                                    IT.CDNATUBCALPCIT                                                  ||'|'||/*NATUREZA BASE DE CÁLCULO*/
                                    REPLACE(LTRIM(TO_CHAR(SUM(DECODE(IT.CDFISCALIT,'1',IT.VRBASECALCIT,0)),'9999999999900.00')),'.',',')||'|'||
                                    REPLACE(LTRIM(TO_CHAR(DECODE(IT.CDFISCALIT,'1',IT.VRALIQITEM,0),'9900.0000')),'.',',')||'|'||
                                    REPLACE(LTRIM(TO_CHAR(SUM(DECODE(IT.CDFISCALIT,'1',VRIMPOSTOIT,0)),'9999999999900.00')),'.',',')||'|'||
                                    CONTCTBL_SPED(P_IDENTRSAIDOP,IP.CDPRODUTO,P_CDTIPOOPER,DECODE(P_IDENTRSAIDOP,'E',P_CDFILIRECE,P_CDFILIEMIT)) ||'|'  /*CÓDIGO DA CONTA ANALÍTICA*/ AS DADOSPIS,
                                    IT.CDTPCREDPICOITE, SUM(DECODE(IT.CDFISCALIT,'1',IT.VRBASECALCIT,0)) AS VRBASECALCIT,
                                    DECODE(IT.CDFISCALIT,'1',IT.VRALIQITEM,0) AS VRALIQITEM,
                                    SUM(DECODE(IT.CDFISCALIT,'1',IT.VRIMPOSTOIT,0)) AS VRIMPOSTOIT,
                                    IT.CDSITUTRIBITNFE, IT.CDNATUBCALPCIT, CDFISCALIT,
                                    CONTCTBL_SPED(P_IDENTRSAIDOP,IP.CDPRODUTO,P_CDTIPOOPER,DECODE(P_IDENTRSAIDOP,'E',P_CDFILIRECE,P_CDFILIEMIT)) AS COD_CTA
                               FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, IMPOSTO IM
                              WHERE IT.NRLANCTONF   = P_NRLANCTONF
                                AND IT.CDFILIAL     = P_CDFILIAL
                                AND IM.CDIMPOSTONFE = P_PIS
                                AND IT.CDIMPOSTO    = IM.CDIMPOSTO
                                AND IT.NRLANCTONF   = IP.NRLANCTONF
                                AND IT.CDFILIAL     = IP.CDFILIAL
                                AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                                AND IT.NRITPROIMPOS = '1'
                               GROUP BY IT.CDSITUTRIBITNFE, IT.CDNATUBCALPCIT, IT.CDFISCALIT, DECODE(IT.CDFISCALIT,'1',IT.VRALIQITEM,0), IT.CDTPCREDPICOITE,
                                     CONTCTBL_SPED(P_IDENTRSAIDOP,IP.CDPRODUTO,P_CDTIPOOPER,DECODE(P_IDENTRSAIDOP,'E',P_CDFILIRECE,P_CDFILIEMIT)))LOOP

            V_CONTREGA := NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(P_CONTEST,'000'))||'04'||LPAD(RTRIM(V_CONTREGA),22,'0'),C_REG_C501.DADOSPIS);

            IF ((C_REG_C501.CDSITUTRIBITNFE BETWEEN '50' AND '67') OR (C_REG_C501.CDSITUTRIBITNFE='98')) AND (C_REG_C501.VRBASECALCIT > 0) THEN
               /*INSERE O VALOR REFERENTE AO PIS*/
               V_TMPBLCM:= NVL(V_TMPBLCM,0)+1;
               INSERT INTO TMP_REGBLOCOM_PIS
                  (CHAVENOTA,CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED, CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT)
               VALUES
                  ('C501'||P_CDFILIAL||P_NRLANCTONF,'M100',V_TMPBLCM,C_REG_C501.CDTPCREDPICOITE,C_REG_C501.VRBASECALCIT,C_REG_C501.VRALIQITEM,'P',C_REG_C501.VRIMPOSTOIT,C_REG_C501.CDSITUTRIBITNFE,P_CDFILIRECE,C_REG_C501.CDNATUBCALPCIT);
            END IF;

            /* CODIGO DA CONTA CONTÁBIL */
            BEGIN
               SELECT MAX(CDCHAVEREG)
                 INTO V_COD_CC
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = C_REG_C501.COD_CTA
                  AND CDREGISTRO = '0500';
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_COD_CC := NULL;
            END;

            IF (V_COD_CC IS NULL) AND (C_REG_C501.COD_CTA IS NOT NULL) THEN
               V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
               VALUES
                  ('0500', V_SEQCCTBL, C_REG_C501.COD_CTA, NULL);
            END IF;
         END LOOP;

         /*C505 COMPLEMENTO DO DOCUMENTO DE TRANSPORTE COFINS*/
         FOR C_REG_C505 IN (SELECT '|C505'                                                         ||'|'||
                                   IT.CDSITUTRIBITNFE                                             ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(IP.VRTOTAITEM),'9999999999900.00')),'.',',')  ||'|'||
                                   IT.CDNATUBCALPCIT                                                  ||'|'||/*NATUREZA BASE DE CÁLCULO*/
                                   REPLACE(LTRIM(TO_CHAR(SUM(DECODE(IT.CDFISCALIT,'1',IT.VRBASECALCIT,0)),'9999999999900.00')),'.',',')||'|'||
                                   REPLACE(LTRIM(TO_CHAR(DECODE(IT.CDFISCALIT,'1',IT.VRALIQITEM,0),'9900.0000')),'.',',')||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(DECODE(IT.CDFISCALIT,'1',IT.VRIMPOSTOIT,0)),'9999999999900.00')),'.',',')||'|'||
                                   CONTCTBL_SPED(P_IDENTRSAIDOP,IP.CDPRODUTO,P_CDTIPOOPER,DECODE(P_IDENTRSAIDOP,'E',P_CDFILIRECE,P_CDFILIEMIT)) ||'|' /*CODIGO DA CONTA ANALICA*/ AS DADOSCOFINS,
                                   IT.CDTPCREDPICOITE, SUM(DECODE(IT.CDFISCALIT,'1',IT.VRBASECALCIT,0)) AS VRBASECALCIT,
                                   DECODE(IT.CDFISCALIT,'1',IT.VRALIQITEM,0) AS VRALIQITEM,
                                   SUM(DECODE(IT.CDFISCALIT,'1',IT.VRIMPOSTOIT,0)) AS VRIMPOSTOIT,
                                   IT.CDSITUTRIBITNFE,IT.CDNATUBCALPCIT, CDFISCALIT,
                                   CONTCTBL_SPED(P_IDENTRSAIDOP,IP.CDPRODUTO,P_CDTIPOOPER,DECODE(P_IDENTRSAIDOP,'E',P_CDFILIRECE,P_CDFILIEMIT)) AS COD_CTA
                              FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, IMPOSTO IM
                             WHERE IT.NRLANCTONF   = P_NRLANCTONF
                               AND IT.CDFILIAL     = P_CDFILIAL
                               AND IM.CDIMPOSTONFE = P_COFINS
                               AND IT.CDIMPOSTO    = IM.CDIMPOSTO
                               AND IT.NRLANCTONF   = IP.NRLANCTONF
                               AND IT.CDFILIAL     = IP.CDFILIAL
                               AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                               AND IT.NRITPROIMPOS = '1'
                             GROUP BY IT.CDSITUTRIBITNFE, IT.CDNATUBCALPCIT, IT.CDFISCALIT, DECODE(IT.CDFISCALIT,'1',IT.VRALIQITEM,0),IT.VRALIQITEM,IT.CDTPCREDPICOITE,
                                   CONTCTBL_SPED(P_IDENTRSAIDOP,IP.CDPRODUTO,P_CDTIPOOPER,DECODE(P_IDENTRSAIDOP,'E',P_CDFILIRECE,P_CDFILIEMIT)))LOOP

            V_CONTREGA := NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(P_CONTEST,'000'))||'04'||LPAD(RTRIM(V_CONTREGA),22,'0'),C_REG_C505.DADOSCOFINS );

            IF ((C_REG_C505.CDSITUTRIBITNFE BETWEEN '50' AND '67') OR (C_REG_C505.CDSITUTRIBITNFE='98')) AND (C_REG_C505.VRBASECALCIT > 0) THEN
               /*INSERE O VALOR REFERENTE AO PIS*/
               V_TMPBLCM:= NVL(V_TMPBLCM,0)+1;
               INSERT INTO TMP_REGBLOCOM_PIS
                  (CHAVENOTA,CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT)
               VALUES
                  ('C505'||P_CDFILIAL||P_NRLANCTONF,'M500',V_TMPBLCM,C_REG_C505.CDTPCREDPICOITE,C_REG_C505.VRBASECALCIT,C_REG_C505.VRALIQITEM,'P',C_REG_C505.VRIMPOSTOIT,C_REG_C505.CDSITUTRIBITNFE,P_CDFILIRECE,C_REG_C505.CDNATUBCALPCIT);
            END IF;

            /* CODIGO DA CONTA CONTÁBIL */
            BEGIN
               SELECT MAX(CDCHAVEREG)
                 INTO V_COD_CC
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = C_REG_C505.COD_CTA
                  AND CDREGISTRO = '0500';
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_COD_CC := NULL;
            END;

            IF (V_COD_CC IS NULL) AND (C_REG_C505.COD_CTA IS NOT NULL) THEN
               V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
               VALUES
                  ('0500', V_SEQCCTBL, C_REG_C505.COD_CTA, NULL);
            END IF;
         END LOOP;
      END LOOP;
   END IF;

   /*VERIFICA SE O ESTABELECIMENTO JA FOI INSERIDO*/
   V_IDC010:= NULL;
   SELECT MAX(CDCHAVEREG)
     INTO V_IDC010
     FROM TMP_REGDADOSSPED_PIS
    WHERE CDREGISTRO = 'C010'
      AND CDCHAVEREG =  P_NRINSJUREST;

   /*IDENTIFICAÇAO DO ESTABELECIMENTO*/
   IF (V_IDC010 IS NULL) AND (P_NRINSJUREST IS NOT NULL) THEN
      V_REG_C010 := '|C010|'||P_NRINSJUREST||'|2|';
      V_CONTREGA := NVL(V_CONTREGA,0)+1;
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(P_CONTEST,'000')),V_REG_C010);

      INSERT INTO TMP_REGDADOSSPED_PIS
         (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
      VALUES
         ('C010', V_SEQUPROD, P_NRINSJUREST ,NULL,LTRIM(TO_CHAR(P_CONTEST,'000')));
   END IF;
   RETURN(LPAD(TO_CHAR(V_CONTREGA),20,'0')||'|'||LPAD(TO_CHAR(V_SEQUPROD),20,'0')||'|'||LPAD(TO_CHAR(V_TMPBLCM),20,'0'));
END;
/
CREATE OR REPLACE FUNCTION SPED_PIS_COFINS_BLOCO9(
   P_CONTREGA    IN FLOAT,
   P_CONTREGC    IN NUMBER,
   P_CONTREGD    IN NUMBER,
   P_CONTBLC0    IN NUMBER,
   P_GERABCLP    IN VARCHAR,
   P_LIVROMAG    IN RELACPRODITGEN.CDLIVROMAG%TYPE,
   P_NRSEQARQMAG IN ARQMAGPISCOFINS.NRSEQARQMAG%TYPE,
   P_DTINICIAL   IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DTFINAL     IN NOTAFISCAL.DTENTRSAID%TYPE) RETURN NUMBER
AS
   V_MOVIMENT     NUMBER;
   V_TOTREG9      NUMBER;
   V_CONTREG9     NUMBER;
   V_TOTREG       DOUBLE PRECISION;
   V_CONTREGA     DOUBLE PRECISION;
   V_0200         VARCHAR2(400);
   V_0150         VARCHAR2(4000);
   V_0145         VARCHAR2(500);
   V_UNID         VARCHAR2(400);
   V_PROD         VARCHAR2(400);
   V_CONTBLC0     NUMBER;
   V_ESTAB        NUMBER;
   V_CDCHAVEREG   VARCHAR2(4);
   V_DSCFOPPADRAO VARCHAR2(500);
BEGIN
   V_CONTBLC0 := P_CONTBLC0;
   V_CONTREGA := P_CONTREGA;
  /*--------------------------REGISTRO 0145 - BLOCO P IDENTIFICADOR DO REGIME ESPECIAL----------------------*/
   IF P_GERABCLP IN ('1','2') THEN
      SELECT MAX( '|0145'              ||'|'||
                  '1'                  ||'|'||
                  CDCAMPO1             ||'|'||
                  CDCAMPO2             ||'|'||
                  '0,00'               ||'|'||
                  ''                   ||'|') , CDESTAB
        INTO V_0145, V_ESTAB
        FROM TMP_REGDADOSSPED_PIS
       WHERE CDREGISTRO = '0145'
       GROUP BY CDESTAB;
      V_CONTBLC0 := NVL(V_CONTBLC0,0)+1;
      V_CONTREGA := NVL(V_CONTREGA,0)+1;
      INSERT INTO ARQMAGPISCOFINS
        (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('104'||LTRIM(TO_CHAR(V_ESTAB,'000'))||'00'||LPAD(RTRIM(V_CONTREGA),22, '0'), V_0145 ,P_NRSEQARQMAG);
   END IF;
  /*SELECIONA O BLOCO 0150 PARA O BLOCO A*/
  /*FOR C_REG0150A IN(SELECT CDCAMPO1, NVL(CDESTAB,0) AS CDESTAB
                      FROM TMP_REGDADOSSPED_PIS
                     WHERE CDREGISTRO = 0150
                       AND CDCAMPO3 = A
                       AND CDCHAVEREG IS NOT NULL)LOOP
        INSERT INTO ARQMAGPISCOFINS(NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
             VALUES(P_NRSEQARQMAG,104||C_REG0150A.CDESTAB||01||LPAD(RTRIM(V_CONTREGA),22,0),C_REG0150A.CDCAMPO1);
    V_CONTREGA:=NVL(V_CONTREGA,0)+1;
    V_CONTBLC0:= NVL(V_CONTBLC0,0)+1;
  END LOOP;*/
  /*SELECIONA O REGISTRO 0150 */
   FOR C_0150 IN (SELECT CDCHAVEREG, NVL(CDESTAB,0) AS CDESTAB
                    FROM TMP_REGDADOSSPED_PIS
                   WHERE CDREGISTRO = '0150'
                     AND CDCHAVEREG IS NOT NULL
                     AND LENGTH(CDCHAVEREG) > 3
                  ORDER BY CDESTAB, CDCHAVEREG) LOOP
                 SELECT MAX('|0150'                           || '|' ||
                        CODIGO                                || '|' ||
                        TRIM(REPLACE(REPLACE(NMRAZAO, CHR(10), ' ' ), CHR(9), ' '))  || '|' ||
                        LPAD(CDPAIS,5,'0')                    || '|' ||
                        CNPJ1                                 || '|' ||
                        CPF                                   || '|' ||
                        TRIM(REPLACE(REPLACE(INSCESTA, CHR(10), ' ' ), CHR(9), ' ')) || '|' ||
                        MUNICIPIO                             || '|' ||
                        SUFRAMA                               || '|' ||
                        TRIM(REPLACE(REPLACE(ENDERECO, CHR(10), ' ' ), CHR(9), ' ')) || '|' ||
                        NUMERO                                || '|' ||
                        TRIM(REPLACE(REPLACE(SUBSTR(COMPLEMENT,1,60), CHR(10), ' ' ), CHR(9), ' ')) || '|' ||
                        TRIM(REPLACE(REPLACE(BAIRRO, CHR(10), ' ' ), CHR(9), ' ')) || '|' )
                    INTO V_0150
                    FROM(SELECT 'L'||FI.CDFILIAL                    AS CODIGO,
                                FI.NMRAZSOCFILI                     AS NMRAZAO,
                                PA.CDPAISBACEN                      AS CDPAIS,
                                REPLACE(REPLACE(REPLACE(FI.NRINSJURFILI,'.',''),'/',''),'-','') AS CNPJ1,
                                ''                                  AS CPF,
                                ''                                  AS CEI,
                                ''                                  AS NIT,
                                EF.SGESTADO                         AS ESTADO,
                                DECODE(FI.CDINSCESTA, 'ISENTO', '', REPLACE(REPLACE(REPLACE(FI.CDINSCESTA,'.',''),'/',''),'-','')) AS INSCESTA,
                                ''                                  AS INSCESTST,
                                DECODE(PA.CDPAISBACEN,'1058',LPAD(NVL(M.CDMUNICIBGE,'0'),7,'0'),'') AS MUNICIPIO,
                                ''                                  AS INSCMUNI,
                                ''                                  AS SUFRAMA,
                                FI.CDFILIAL                         AS CNPJ,
                                NVL(EF.DSENDEFILISEP,EF.DSENDEFILI) AS ENDERECO,
                                EF.NRENDEFILISEP                    AS NUMERO,
                                EF.DSCOMPENDFIL                     AS COMPLEMENT,
                                EF.NMBAIRFILI                       AS BAIRRO
                           FROM FILIAL FI, ENDEFILI EF, MUNICIPIO M, PAIS PA
                          WHERE EF.CDFILIAL(+)    = FI.CDFILIAL
                            AND NVL(EF.IDTPENDEFILI,'P') = 'P'
                            AND EF.CDPAIS        = M.CDPAIS
                            AND EF.SGESTADO      = M.SGESTADO
                            AND EF.CDMUNICIPIO   = M.CDMUNICIPIO
                            AND EF.CDPAIS        = PA.CDPAIS
                            AND 'L'||FI.CDFILIAL = C_0150.CDCHAVEREG
                          UNION
                         SELECT 'C'||CL.CDCLIENTE                             AS CODIGO,
                                CL.NMRAZSOCCLIE                               AS NMRAZAO,
                                PA.CDPAISBACEN                                AS CDPAIS,
                                DECODE(LENGTH(REPLACE(REPLACE(REPLACE(CL.NRINSJURCLIE,'.',''),'/',''),'-','')), 14, REPLACE(REPLACE(REPLACE(CL.NRINSJURCLIE,'.',''),'/',''),'-','')) AS CNPJ1,
                                DECODE(LENGTH(REPLACE(REPLACE(REPLACE(CL.NRINSJURCLIE,'.',''),'/',''),'-','')), 11, REPLACE(REPLACE(REPLACE(CL.NRINSJURCLIE,'.',''),'/',''),'-','')) AS CPF,
                                ''                                            AS CEI,
                                ''                                            AS NIT,
                                EC.SGESTADO                                   AS ESTADO,
                                DECODE(CL.NRINSESTCLIE, 'ISENTO', '', REPLACE(REPLACE(REPLACE(CL.NRINSESTCLIE,'.',''),'/',''),'-','')) AS INSCESTA,
                                ''                                            AS INSCESTST,
                                DECODE(PA.CDPAISBACEN,'1058',LPAD(NVL(M.CDMUNICIBGE,'0'),7,'0'),'') AS MUNICIPIO,
                                ''                                            AS INSCMUNI,
                                ''                                            AS SUFRAMA,
                                CL.CDCLIENTE                                  AS CNPJ,
                                NVL(EC.DSENDECLIESEP,EC.DSENDECLIE)           AS ENDERECO,
                                EC.NRENDECLIESEP                              AS NUMERO,
                                EC.DSCOMPENDCLI                               AS COMPLEMENT,
                                EC.NMBAIRCLIE                                 AS BAIRRO
                           FROM CLIENTE CL, ENDECLIE EC, MUNICIPIO M, PAIS PA
                          WHERE EC.CDCLIENTE(+)    = CL.CDCLIENTE
                            AND EC.IDTPENDECLIE(+) = NVL(CL.IDENDEMISCLI,'P')
                            AND EC.CDPAIS          = M.CDPAIS
                            AND EC.SGESTADO        = M.SGESTADO
                            AND EC.CDMUNICIPIO     = M.CDMUNICIPIO
                            AND EC.CDPAIS          = PA.CDPAIS
                            AND 'C'||CL.CDCLIENTE  = C_0150.CDCHAVEREG
                         UNION
                         SELECT 'F'||FO.CDFORNECED                               AS CODIGO,
                                FO.NMRAZSOCFORN                                  AS NMRAZAO,
                                PA.CDPAISBACEN                                   AS CDPAIS,
                                DECODE(LENGTH(REPLACE(REPLACE(REPLACE(FO.NRINSJURFORN,'.',''),'/',''),'-','')), 14, REPLACE(REPLACE(REPLACE(FO.NRINSJURFORN,'.',''),'/',''),'-','')) AS CNPJ1,
                                DECODE(LENGTH(REPLACE(REPLACE(REPLACE(FO.NRINSJURFORN,'.',''),'/',''),'-','')), 11, REPLACE(REPLACE(REPLACE(FO.NRINSJURFORN,'.',''),'/',''),'-','')) AS CPF,
                                ''                                               AS CEI,
                                ''                                               AS NIT,
                                EF.SGESTADO                                      AS ESTADO,
                                DECODE(FO.NRINSESTFORN, 'ISENTO', '', REPLACE(REPLACE(REPLACE(FO.NRINSESTFORN,'.',''),'/',''),'-','')) AS INSCESTA,
                                ''                                               AS INSCESTST,
                                DECODE(PA.CDPAISBACEN,'1058',LPAD(NVL(M.CDMUNICIBGE,'0'),7,'0'),'') AS MUNICIPIO ,
                                REPLACE(REPLACE(FO.NRINSMUNFORN,'-',''),'/','')  AS INSCMUNI,
                                ''                                               AS SUFRAMA,
                                FO.CDFORNECED                                    AS CNPJ,
                                NVL(EF.DSENDEFORNSEP,EF.DSENDEFORN)              AS ENDERECO,
                                EF.NRENDEFORNSEP                                 AS NUMERO,
                                EF.DSCOMPENDFOR                                  AS COMPLEMENT,
                                EF.NMBAIRFORN                                    AS BAIRRO
                           FROM FORNECEDOR FO, ENDEFORN EF, MUNICIPIO M, PAIS PA
                          WHERE EF.CDFORNECED(+)   = FO.CDFORNECED
                            AND EF.IDTPENDEFORN(+) = NVL(FO.IDENDEMISFOR,'P')
                            AND EF.CDPAIS          = M.CDPAIS
                            AND EF.SGESTADO        = M.SGESTADO
                            AND EF.CDMUNICIPIO     = M.CDMUNICIPIO
                            AND EF.CDPAIS          = PA.CDPAIS
                            AND 'F'||FO.CDFORNECED = C_0150.CDCHAVEREG);
     V_CONTBLC0 := NVL(V_CONTBLC0,0 ) + 1;
     V_CONTREGA := NVL(V_CONTREGA,0) + 1;
     INSERT INTO ARQMAGPISCOFINS
       (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
     VALUES
       ('104'||C_0150.CDESTAB||'01'||LPAD(RTRIM(V_CONTREGA),22, '0'), NVL(V_0150,'REGISTRO 0150 VAZIO -'||C_0150.CDCHAVEREG),P_NRSEQARQMAG);
   END LOOP;
   FOR C_0190 IN (SELECT '|0190'        || '|' ||
                         U.SGUNIDADE    || '|' ||
                         U.DSUNIDADE    || '|' AS UNID, CDESTAB
                    FROM TMP_REGDADOSSPED_PIS R, UNIDMEDIDA U
                   WHERE R.CDREGISTRO = '0190'
                     AND R.CDCHAVEREG = U.SGUNIDADE) LOOP
      V_CONTBLC0:= NVL(V_CONTBLC0,0)+1;
      V_CONTREGA := NVL(V_CONTREGA,0) + 1;
      INSERT INTO ARQMAGPISCOFINS
        (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('104'||C_0190.CDESTAB||'02'||LPAD(RTRIM(V_CONTREGA), 22, '0'), NVL(C_0190.UNID,'REGISTRO 0190 VAZIO'), P_NRSEQARQMAG);
   END LOOP;
   /*Atualiza a tabela de alteração dos produtos, para gravar a referência de envio no SPED*/
   UPDATE ALTERAPRODSPED
      SET DTENVEFDCONTR = P_DTINICIAL
    WHERE DTENVEFDCONTR IS NULL
      AND CDPRODUTO     IN (SELECT P.CDPRODUTO
                              FROM TMP_REGDADOSSPED_PIS T, PRODUTO P
                             WHERE T.CDREGISTRO = '0200'
                               AND T.CDCHAVEREG = P.CDARVPROD)
      AND DTALTERACAO   <= LAST_DAY(P_DTINICIAL);
   COMMIT;
   /* REGISTRO 0200 */
   FOR C_0200 IN (SELECT CDCHAVEREG, CDESTAB, CDCAMPO4 AS CDCLASFISC
                    FROM TMP_REGDADOSSPED_PIS
                   WHERE CDREGISTRO = '0200') LOOP
      SELECT MAX('|0200'     || '|' ||
             P.CDARVPROD     || '|' ||
             TRIM(REPLACE(REPLACE(REPLACE(P.NMPRODUTO,'|','/'), CHR(10), ' ' ), CHR(9), ' ')) || '|' ||
             ''              || '|' ||
             ''              || '|' || /* COD_ANT_ITEM */
             P.SGUNIDADE     || '|' ||
             R.CDTPITEMPROD  || '|' || /* TIPO ITEM */
             REPLACE(REPLACE(NVL(C_0200.CDCLASFISC,P.CDCLASFISC),'.',''),',','') || '|' ||
             ''              || '|' ||
             R.CDGENPROD     || '|' ||
             ''              || '|' ||
             ''              || '|'  ), MAX(P.SGUNIDADE), MAX(P.CDARVPROD)
        INTO V_0200, V_UNID, V_PROD
        FROM RELACPRODITGEN R, PRODUTO P
       WHERE P.CDARVPROD     = C_0200.CDCHAVEREG
         AND R.CDPRODUTO(+)  = P.CDPRODUTO
         AND R.CDLIVROMAG(+) = P_LIVROMAG;
      IF V_0200 IS NOT NULL THEN
         V_CONTBLC0:= NVL(V_CONTBLC0,0)+1;
         V_CONTREGA := NVL(V_CONTREGA,0) + 1;
         INSERT INTO ARQMAGPISCOFINS
           (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
         VALUES
           ('104'||C_0200.CDESTAB||'03'||LPAD(RTRIM(V_CONTREGA),22,'0'), NVL(V_0200,'REGISTRO 0200 VAZIO -'||C_0200.CDCHAVEREG),P_NRSEQARQMAG);
      END IF;
      /*REGISTRO 0205: Alteração do Item*/
      FOR C_REG0205 IN (SELECT MAX('|0205'                                 ||'|'||
                               RETIRA_CARACTER_ESPECIAL(DSCONTEUDOANT,'S') ||'|'||
                               TO_CHAR(DTINICIAL,'DDMMYYYY')               ||'|'||
                               TO_CHAR(DTALTERACAO,'DDMMYYYY')             ||'|'||
                               ''  ||'|') AS ARQ_0205, A.CDPRODUTO
                          FROM ALTERAPRODSPED A, PRODUTO P
                         WHERE A.DTENVEFDCONTR = P_DTINICIAL
                           AND A.CDPRODUTO     = P.CDPRODUTO
                           AND P.CDARVPROD     = C_0200.CDCHAVEREG
                           AND A.DTALTERACAO  <= LAST_DAY(P_DTINICIAL)
                         GROUP BY A.CDPRODUTO) LOOP
         V_CONTBLC0:= NVL(V_CONTBLC0,0)+1;
         V_CONTREGA := NVL(V_CONTREGA,0) + 1;
         INSERT INTO ARQMAGPISCOFINS
           (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
         VALUES
           ('104'||C_0200.CDESTAB||'03'||LPAD(RTRIM(V_CONTREGA),22,'0'), C_REG0205.ARQ_0205,P_NRSEQARQMAG);
      END LOOP;
   END LOOP;
   FOR C_0400 IN (SELECT SUBSTR(CDCHAVEREG,2,3) AS CDFISO,
                         CDCHAVEREG, CDESTAB, CDCAMPO2 AS IDENTRSAIDOP
                    FROM TMP_REGDADOSSPED_PIS
                   WHERE CDREGISTRO = '0400'
                     AND SUBSTR(CDCHAVEREG,2,3) IS NOT NULL
                     AND CDCONTREGI IS NOT NULL
                   ORDER BY CDCHAVEREG) LOOP
      SELECT MAX(CDCFOPPADRAO), MAX(DSCFOPPADRAO)
        INTO V_CDCHAVEREG, V_DSCFOPPADRAO
        FROM CFOPPADRAO
       WHERE CDCFOPPADRAO = C_0400.CDCHAVEREG;
      IF V_CDCHAVEREG IS NULL THEN
         SELECT C_0400.CDCHAVEREG, MAX(DSCDFISCOPER)
           INTO V_CDCHAVEREG, V_DSCFOPPADRAO
           FROM CODFISCOPER
          WHERE CDFISCOPER = C_0400.CDFISO
            AND IDENTRSAIDOP = C_0400.IDENTRSAIDOP;
      END IF;
      V_CONTREGA := NVL(V_CONTREGA,0) + 1;
      V_CONTBLC0 := NVL(V_CONTBLC0,0)+1;
      INSERT INTO ARQMAGPISCOFINS
        (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('104'||C_0400.CDESTAB||'04'||LPAD(RTRIM(V_CONTREGA), 22, '0'), '|0400|'||NVL(V_CDCHAVEREG,'0000')||'|'||NVL(V_DSCFOPPADRAO,'REGISTRO VAZIO')||'|', P_NRSEQARQMAG);
   END LOOP;
   FOR C_0500 IN (SELECT CDCHAVEREG, CDESTAB
                    FROM TMP_REGDADOSSPED_PIS
                   WHERE CDREGISTRO = '0500'
                     AND CDCONTREGI IS NOT NULL) LOOP
      FOR C_REG0500 IN (SELECT ('|0500'            || '|' ||
                                TO_CHAR((CASE 
                                   WHEN DTULTATUCCTB > P_DTFINAL
                                     THEN P_DTFINAL
                                   ELSE DTULTATUCCTB END),'ddmmyyyy')|| '|' ||
                                IDNATUCONT         || '|' ||
                                IDTIPOCONT         || '|' ||
                                CDNVCONTCTBL       || '|' ||
                                C_0500.CDCHAVEREG  || '|' ||
                                NMCONTCTBL         || '|' ||
                                ''                 || '|' ||
                                ''                 || '|'  ) ARQ_0500
                        FROM CONTCTBL
                        WHERE CDCONTCTBL = C_0500.CDCHAVEREG) LOOP
         V_CONTREGA := NVL(V_CONTREGA,0) + 1;
         V_CONTBLC0 := NVL(V_CONTBLC0,0)+1;
         INSERT INTO ARQMAGPISCOFINS
           (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
         VALUES
           ('105'||C_0500.CDESTAB||'04'||LPAD(RTRIM(V_CONTREGA), 22, '0'), NVL(C_REG0500.ARQ_0500,'REGISTRO 0500 VAZIO -'||C_0500.CDCHAVEREG), P_NRSEQARQMAG);
      END LOOP;
   END LOOP;
   /*INSERE O BLOCO 0990 - ENCERRAMENTO*/
   V_CONTBLC0 := NVL(V_CONTBLC0,0)+1;
   INSERT INTO ARQMAGPISCOFINS(NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
       VALUES(P_NRSEQARQMAG,'118','|0990|'||TO_CHAR(V_CONTBLC0)||'|');
  /*GERAÇÃO DO BLOCO 9*/
  /*BLOCO 9900 REGISTROS DO BLOCO 0*/
  FOR REG_C IN (SELECT SUBSTR(DSREGARQMAG,2,4) AS BLOCO, COUNT(*) AS QTDE
                   FROM ARQMAGPISCOFINS
                  WHERE SUBSTR(DSREGARQMAG,2,1) = '0'
                    AND NRSEQARQMAG = P_NRSEQARQMAG
                  GROUP BY SUBSTR(DSREGARQMAG,2,4)
                  ORDER BY SUBSTR(DSREGARQMAG,2,4) ) LOOP
      V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
      INSERT INTO ARQMAGPISCOFINS
        (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('902'||LPAD(RTRIM(V_CONTREG9), 27, '0'), '|9900'|| '|' ||REG_C.BLOCO||'|' ||REG_C.QTDE|| '|', P_NRSEQARQMAG);
   END LOOP;
   /*BLOCO 9900 REGOSTROS DO BLOCO A*/
   FOR REG_C IN (SELECT SUBSTR(DSREGARQMAG,2,4) AS BLOCO, COUNT(*) AS QTDE
                   FROM ARQMAGPISCOFINS
                  WHERE SUBSTR(DSREGARQMAG,2,1) = 'A'
                    AND NRSEQARQMAG = P_NRSEQARQMAG
                  GROUP BY SUBSTR(DSREGARQMAG,2,4)
                  ORDER BY SUBSTR(DSREGARQMAG,2,4) ) LOOP
      V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
      INSERT INTO ARQMAGPISCOFINS
        (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('902'||LPAD(RTRIM(V_CONTREG9),27, '0'), '|9900'|| '|' ||REG_C.BLOCO||'|' ||REG_C.QTDE|| '|', P_NRSEQARQMAG);
   END LOOP;
   /*BLOCO 9900 REGOSTROS DO BLOCO C*/
   FOR REG_C IN (SELECT SUBSTR(DSREGARQMAG,2,4) AS BLOCO, COUNT(*) AS QTDE
                   FROM ARQMAGPISCOFINS
                  WHERE SUBSTR(DSREGARQMAG,2,1) = 'C'
                    AND NRSEQARQMAG = P_NRSEQARQMAG
                  GROUP BY SUBSTR(DSREGARQMAG,2,4)
                  ORDER BY SUBSTR(DSREGARQMAG,2,4) ) LOOP
      V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
      INSERT INTO ARQMAGPISCOFINS
        (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('902'||LPAD(RTRIM(V_CONTREG9), 8, '0'), '|9900'|| '|' ||REG_C.BLOCO||'|' ||REG_C.QTDE|| '|', P_NRSEQARQMAG);
   END LOOP;
   /*BLOCO 9900 REGISTROS DO BLOCO D*/
   FOR REG_C IN (SELECT SUBSTR(DSREGARQMAG,2,4) AS BLOCO, COUNT(*) AS QTDE
                   FROM ARQMAGPISCOFINS
                  WHERE SUBSTR(DSREGARQMAG,2,1) = 'D'
                    AND NRSEQARQMAG = P_NRSEQARQMAG
                  GROUP BY SUBSTR(DSREGARQMAG,2,4)
                  ORDER BY SUBSTR(DSREGARQMAG,2,4) ) LOOP
      V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
      INSERT INTO ARQMAGPISCOFINS
        (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('902'||LPAD(RTRIM(V_CONTREG9), 8, '0'), '|9900'|| '|' ||REG_C.BLOCO||'|' ||REG_C.QTDE|| '|', P_NRSEQARQMAG);
   END LOOP;
   /*BLOCO 9900 REGISTROS DO BLOCO F*/
   FOR REG_C IN (SELECT SUBSTR(DSREGARQMAG,2,4) AS BLOCO, COUNT(*) AS QTDE
                   FROM ARQMAGPISCOFINS
                  WHERE SUBSTR(DSREGARQMAG,2,1) = 'F'
                    AND NRSEQARQMAG = P_NRSEQARQMAG
                  GROUP BY SUBSTR(DSREGARQMAG,2,4)
                  ORDER BY SUBSTR(DSREGARQMAG,2,4) ) LOOP
      V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
      INSERT INTO ARQMAGPISCOFINS
        (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('902'||LPAD(RTRIM(V_CONTREG9), 8, '0'), '|9900'|| '|' ||REG_C.BLOCO||'|' ||REG_C.QTDE|| '|', P_NRSEQARQMAG);
   END LOOP;
   /*BLOCO 9900 REGISTROS DO BLOCO M*/
   FOR REG_C IN (SELECT SUBSTR(DSREGARQMAG,2,4) AS BLOCO, COUNT(*) AS QTDE
                   FROM ARQMAGPISCOFINS
                  WHERE SUBSTR(DSREGARQMAG,2,1) = 'M'
                    AND NRSEQARQMAG = P_NRSEQARQMAG
                  GROUP BY SUBSTR(DSREGARQMAG,2,4)
                  ORDER BY SUBSTR(DSREGARQMAG,2,4)) LOOP
      V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
      INSERT INTO ARQMAGPISCOFINS
        (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('902'||LPAD(RTRIM(V_CONTREG9), 8, '0'), '|9900'|| '|' ||REG_C.BLOCO||'|' ||REG_C.QTDE|| '|', P_NRSEQARQMAG);
   END LOOP;
   /*BLOCO 9900 REGISTROS DO BLOCO P*/
   FOR REG_C IN (SELECT SUBSTR(DSREGARQMAG,2,4) AS BLOCO, COUNT(*) AS QTDE
                   FROM ARQMAGPISCOFINS
                  WHERE SUBSTR(DSREGARQMAG,2,1) = 'P'
                    AND NRSEQARQMAG = P_NRSEQARQMAG
                  GROUP BY SUBSTR(DSREGARQMAG,2,4)
                  ORDER BY SUBSTR(DSREGARQMAG,2,4)) LOOP
      V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
      INSERT INTO ARQMAGPISCOFINS
        (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('902'||LPAD(RTRIM(V_CONTREG9), 8, '0'), '|9900'|| '|' ||REG_C.BLOCO||'|' ||REG_C.QTDE|| '|', P_NRSEQARQMAG);
   END LOOP;
   /*BLOCO 9900 REGISTROS DO BLOCO 1*/
   /*V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
   INSERT INTO ARQMAGPISCOFINS
     (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     (902||LPAD(RTRIM(V_CONTREG9), 8, 0), |9900|| | ||1001|| | ||1|| |, P_NRSEQARQMAG);
   V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
   INSERT INTO ARQMAGPISCOFINS
     (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     (902||LPAD(RTRIM(V_CONTREG9), 8, 0), |9900|| | ||1990|| | ||1|| |, P_NRSEQARQMAG);
   V_CONTREG9 := NVL(V_CONTREG9,0) + 1;*/
   FOR REG_C IN (SELECT SUBSTR(DSREGARQMAG,2,4) AS BLOCO, COUNT(*) AS QTDE
                   FROM ARQMAGPISCOFINS
                  WHERE SUBSTR(DSREGARQMAG,2,1) = '1'
                    AND NRSEQARQMAG = P_NRSEQARQMAG
                  GROUP BY SUBSTR(DSREGARQMAG,2,4)
                  ORDER BY SUBSTR(DSREGARQMAG,2,4)) LOOP
      V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
      INSERT INTO ARQMAGPISCOFINS
        (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('902'||LPAD(RTRIM(V_CONTREG9), 8, '0'), '|9900'|| '|' ||REG_C.BLOCO||'|' ||REG_C.QTDE|| '|', P_NRSEQARQMAG);
   END LOOP;
   V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
   INSERT INTO ARQMAGPISCOFINS
     (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     ('902'||LPAD(RTRIM(V_CONTREG9), 8, '0'), '|9900'|| '|' ||'9001'|| '|' ||'1'|| '|', P_NRSEQARQMAG);
   V_TOTREG := 0;
   SELECT COUNT(*)
     INTO V_TOTREG
     FROM ARQMAGPISCOFINS
    WHERE SUBSTR(DSREGARQMAG,2,4) = '9900'
      AND NRSEQARQMAG = P_NRSEQARQMAG;
   IF V_TOTREG IS NOT NULL THEN
      V_TOTREG := NVL(V_TOTREG,0) + 3;
      V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
      INSERT INTO ARQMAGPISCOFINS
        (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('902'||LPAD(RTRIM(V_CONTREG9), 8, '0'), '|9900'|| '|' ||'9900'|| '|' ||V_TOTREG|| '|', P_NRSEQARQMAG);
   END IF;
   V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
   INSERT INTO ARQMAGPISCOFINS
     (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     ('902'||LPAD(RTRIM(V_CONTREG9), 8, '0'), '|9900'|| '|' ||'9990'|| '|' ||'1'|| '|', P_NRSEQARQMAG);
   V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
   INSERT INTO ARQMAGPISCOFINS
     (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     ('902'||LPAD(RTRIM(V_CONTREG9), 8, '0'), '|9900'|| '|' ||'9999'|| '|' ||'1'|| '|', P_NRSEQARQMAG);
   IF V_CONTREG9 <> 0 THEN
      V_MOVIMENT := 0;
   ELSE
      V_MOVIMENT := 1;
   END IF;
   V_CONTREG9 := NVL(V_CONTREG9,0) + 1;
   INSERT INTO ARQMAGPISCOFINS
     (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     ('901'||LPAD(RTRIM(V_CONTREG9), 8, '0'),'|9001|'||V_MOVIMENT||'|', P_NRSEQARQMAG);
   BEGIN
      SELECT COUNT(*) AS QTDE
         INTO V_TOTREG
        FROM ARQMAGPISCOFINS
       WHERE  NRSEQARQMAG = P_NRSEQARQMAG;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_TOTREG := 0;
   END;
   V_TOTREG:= NVL(V_TOTREG,0)+2;/*INSERÇÃO DE +2 DEVIDO AO REGISTRO 9999 E 9990*/
   INSERT INTO ARQMAGPISCOFINS
     (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     ('904'||LPAD(RTRIM(V_CONTREG9), 8, '0'),'|9999|'||V_TOTREG||'|', P_NRSEQARQMAG);
     V_CONTREG9 := NVL(V_CONTREG9,0) + 2;/*INSERERE +2 DEVIDO O REGISTRO 9990*/
   INSERT INTO ARQMAGPISCOFINS
     (NRORDREGARQMAG, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     ('903'||LPAD(RTRIM(V_CONTREG9), 8, '0'),'|9990|'||V_CONTREG9||'|', P_NRSEQARQMAG);
   RETURN(V_CONTREGA);
END;
/

CREATE OR REPLACE FUNCTION SPED_PIS_COFINS_BLOCOM(
   P_CONTEST       IN NUMBER,
   P_CDEMPRESA     IN EMPRESA.CDEMPRESA%TYPE,
   P_NRSEQARQMAG   IN ARQMAGPISCOFINS.NRSEQARQMAG%TYPE,
   P_DTINICIAL     IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DTFINAL       IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_LIVROMAG      IN LIVROMAGNETICO.CDLIVROMAG%TYPE,
   P_CDINCTRIB     IN VARCHAR2,
   P_GERABCLP      IN VARCHAR2,
   P_PIS           IN IMPOSTO.CDIMPOSTO%TYPE,
   P_COFINS        IN IMPOSTO.CDIMPOSTO%TYPE,
   P_GERADEVOLVEND IN VARCHAR2,
   P_VERSAO        IN VARCHAR2,
   P_COUNTBLC0     OUT NUMBER) RETURN NUMBER
AS
   V_CONTREGA            NUMBER;
   V_SEQAJUST            NUMBER;  
   V_CONT                NUMBER;
   V_REGM100             VARCHAR2(1000);
   V_REGM110             VARCHAR2(1000);
   V_REGM210             VARCHAR2(1000);
   V_REGM500             VARCHAR2(1000);
   V_REGM510             VARCHAR2(1000);
   V_REGM610             VARCHAR2(1000);
   V_REGM205_C           VARCHAR2(1000);
   V_REGM205_NC          VARCHAR2(1000);
   V_REGM605_C           VARCHAR2(1000);
   V_REGM605_NC          VARCHAR2(1000); 
   V_NRMAPAPIS           VARCHAR2(10);
   V_NRMAPACOFINS        VARCHAR2(10);
   V_CDRECEPISCUMU       VARCHAR2(6);
   V_CDRECEPISNCUMU      VARCHAR2(6);
   V_CDRECECOFINSCUMU    VARCHAR2(6);
   V_CDRECECOFINSNCUMU   VARCHAR2(6);
   V_IDUTICRED           VARCHAR2(01);
   V_VRCREDPIS           NUMBER;
   V_VRCREDCOFINS        NUMBER;
   V_VRCREDITO           FLOAT;
   V_VRTOTACRED          FLOAT;
   V_CREDUTLIZADO        FLOAT;
   V_VRSALDOFUTURO       FLOAT;
   V_CREDANTERIOR        FLOAT;
   V_IMPRETIDONCUM       FLOAT;
   V_IMPRETIDOCUM        FLOAT;
   V_VRDEDUCAONCUM       FLOAT;
   V_VRDEDUCAOCUMU       FLOAT;
   V_GERAAJUSTEAUTO      VARCHAR2(01);
   V_VRAJUSTEAUTO        FLOAT;
   V_DESCAJUSTEAUTO      VARCHAR2(250);
   V_CDAJUSTEAUTO        VARCHAR2(02);
   V_VRAJUSTEACRES       FLOAT;
   V_VRBCAJUSTEACRES     FLOAT;
   V_VRAJUSTEREDUC       FLOAT;
   V_VRBCAJUSTEREDUC     FLOAT;
   V_VRAJUSTENCUM        FLOAT;
   V_VRAJUSTECUMU        FLOAT;
   V_VRACRESAJUSAUTO     FLOAT;
   V_VRREDUZAJUSAUTO     FLOAT;
   V_TIPOCREDITO         VARCHAR2(04);
   V_CDCONTRIB           VARCHAR2(02);
   V_CONTEST             NUMBER;
   V_COUNTBCL0           NUMBER;
   V_NRINSJUR            VARCHAR2(20);
   V_REG                 VARCHAR2(1000);
   V_SEQUPROD            NUMBER;
   V_COD_CC              VARCHAR2(20);
   V_SEQCCTBL            NUMBER;
   V_VRCREDDIFERIDO      FLOAT;
   V_VRCONTRIBDIF        FLOAT;
   V_VRCONTRIBDIFANT     FLOAT;
   V_VRDIFERIMENTONCUM   FLOAT;
   V_VRDIFERIMENTOCUMU   FLOAT;
   V_VRAJUSTEACRESBC     FLOAT;
   V_VRAJUSTEREDUCBC     FLOAT;
BEGIN
   /*INICIALIZA AS VARIÁVEIS COM 0 PARA QUE AS MESMAS NÃO FIQUEM NULAS*/
   V_VRCREDPIS    := 0;
   V_VRCREDCOFINS := 0;

   V_CONTEST := P_CONTEST;

   SELECT MAX(CDCONTREGI)
     INTO V_SEQUPROD
     FROM TMP_REGDADOSSPED_PIS;

   /*OBSERVAÇÃO: O CAMPO IDCUMUPISCOFIL DEFINE SE A FILIAL É CUMULATIVA OU NÃO CUMULATIVA. N PARA CUMULATIVA E S PARA NÃO-CUMULATIVA*/
   /*BUSCA OS AJUSTES DE ACRESCIMO E REDUCAO - AJUSTES E DEVOLUCOES*/
   FOR C_AJUS IN (SELECT DECODE(P.CDIMPOSTONFE,P_PIS,I.CDTPCREDPICOITE,'') AS CDTPCREDPIS,
                         DECODE(P.CDIMPOSTONFE,P_COFINS,I.CDTPCREDPICOITE,'') AS CDTPCREDCOFINS,
                         DECODE(P.CDIMPOSTONFE,P_PIS,I.VRALIQITEM,'') AS VRALIQPIS,
                         DECODE(P.CDIMPOSTONFE,P_COFINS,I.VRALIQITEM,'') AS VRALIQCOFINS,
                         DECODE(P.CDIMPOSTONFE,P_PIS,I.CDSITUTRIBITNFE,'') AS CSTPIS,
                         DECODE(P.CDIMPOSTONFE,P_COFINS,I.CDSITUTRIBITNFE,'') AS CSTCOFINS,
                         DECODE(P.CDIMPOSTONFE,P_PIS,I.CDNATUBCALPCIT,'') AS CDNATUBCPIS,
                         DECODE(P.CDIMPOSTONFE,P_COFINS,I.CDNATUBCALPCIT,'') AS CDNATUBCCOFINS,
                         N.IDENTRSAIDOP AS IDAJUSTE,
                         '05' AS CDAJUSTE,
                         SUM(DECODE(P.CDIMPOSTONFE,P_PIS,DECODE(I.CDFISCALIT,'1',I.VRBASECALCIT,0),0)) AS VRBASEPIS,
                         SUM(DECODE(P.CDIMPOSTONFE,P_COFINS,DECODE(I.CDFISCALIT,'1',I.VRBASECALCIT,0),0)) AS VRBASECOFINS,
                         SUM(DECODE(P.CDIMPOSTONFE,P_PIS,DECODE(I.CDFISCALIT,'1',I.VRIMPOSTOIT,0),0)) AS VRAJUSTEPIS,
                         SUM(DECODE(P.CDIMPOSTONFE,P_COFINS,DECODE(I.CDFISCALIT,'1',I.VRIMPOSTOIT,0),0)) AS VRAJUSTECOFINS,
                         I.CDFILIAL||I.NRLANCTONF AS CHVNOTA,
                         DECODE(N.IDENTRSAIDOP,'E',N.CDFILIRECE,N.CDFILIEMIT) AS FILIAL,
                         SUM(I.VRCONTITIMP) AS VRCONTITIMP
                    FROM ITEMPROIMPOS I, IMPOSTO P, NOTAFISCAL N, CFOPPADRAO C, ITEMPRODUTO D, RELACPRODITGEN G, FILIAL F,
                         (SELECT DISTINCT I.CDFILIAL, I.NRLANCTONF
                            FROM MAPAAPURAC M, IMPOSTONF I
                           WHERE M.CDEMPRESA    = P_CDEMPRESA
                             AND M.CDIMPOSTO    IN (P_PIS,P_COFINS)
                             AND M.DTINIPERIODO = P_DTINICIAL
                             AND M.DTFIMPERIODO = P_DTFINAL
                             AND M.NRSEQUMAPAPU = I.NRSEQUMAPAPU) NF
                   WHERE NF.CDFILIAL    = I.CDFILIAL
                     AND NF.NRLANCTONF  = I.NRLANCTONF
                     AND I.CDIMPOSTO    = P.CDIMPOSTO
                     AND P.CDIMPOSTONFE IN (P_PIS,P_COFINS)
                     AND I.CDFILIAL     = N.CDFILIAL
                     AND I.NRLANCTONF   = N.NRLANCTONF
                     AND C.CDCFOPPADRAO = I.CDFISCOPERIT
                     AND C.IDTIPOCFOP   = 'D'
                     AND I.CDFILIAL     = D.CDFILIAL
                     AND I.NRLANCTONF   = D.NRLANCTONF
                     AND I.NRSEQITPROD  = D.NRSEQITPROD
                     AND D.CDPRODUTO    = G.CDPRODUTO(+)
                     AND G.CDLIVROMAG(+)= P_LIVROMAG
                     AND I.CDFISCALIT   = '1'
                     AND F.CDFILIAL     = DECODE(N.IDENTRSAIDOP,'E',N.CDFILIRECE,N.CDFILIEMIT)
                     AND ((F.IDCUMUPISCOFIL = 'N' AND N.IDENTRSAIDOP = 'E') OR /*APENAS DEVOL. VENDA PARA CUMULATIVO*/
                          (F.IDCUMUPISCOFIL = 'S' AND N.IDENTRSAIDOP IN ('E','S')))
                   GROUP BY N.IDENTRSAIDOP, I.CDFILIAL||I.NRLANCTONF, DECODE(N.IDENTRSAIDOP,'E',N.CDFILIRECE,N.CDFILIEMIT),
                            DECODE(P.CDIMPOSTONFE,P_PIS,I.CDTPCREDPICOITE,''),
                            DECODE(P.CDIMPOSTONFE,P_COFINS,I.CDTPCREDPICOITE,''),
                            DECODE(P.CDIMPOSTONFE,P_PIS,I.VRALIQITEM,''),
                            DECODE(P.CDIMPOSTONFE,P_COFINS,I.VRALIQITEM,''),
                            DECODE(P.CDIMPOSTONFE,P_PIS,I.CDSITUTRIBITNFE,''),
                            DECODE(P.CDIMPOSTONFE,P_COFINS,I.CDSITUTRIBITNFE,''),
                            DECODE(P.CDIMPOSTONFE,P_PIS,I.CDNATUBCALPCIT,''),
                            DECODE(P.CDIMPOSTONFE,P_COFINS,I.CDNATUBCALPCIT,'')
                   UNION ALL
                  SELECT DECODE(P.CDIMPOSTONFE,P_PIS,I.CDTPCREDPICOITE,'') AS CDTPCREDPIS,
                         DECODE(P.CDIMPOSTONFE,P_COFINS,I.CDTPCREDPICOITE,'') AS CDTPCREDCOFINS,
                         DECODE(P.CDIMPOSTONFE,P_PIS,I.VRALIQNF,'') AS VRALIQPIS,
                         DECODE(P.CDIMPOSTONFE,P_COFINS,I.VRALIQNF,'') AS VRALIQCOFINS,
                         DECODE(P.CDIMPOSTONFE,P_PIS,I.CDSITUTRIBITNFE,'') AS CSTPIS,
                         DECODE(P.CDIMPOSTONFE,P_COFINS,I.CDSITUTRIBITNFE,'') AS CSTCOFINS,
                         '' AS CDNATUBCPIS,
                         '' AS CDNATUBCCOFINS,
                         N.IDENTRSAIDOP AS IDAJUSTE,
                         '05' AS CDAJUSTE,
                         SUM(DECODE(P.CDIMPOSTONFE,P_PIS,DECODE(I.CDFISCALNF,'1',I.VRPROPRECBC,0),0)) AS VRBASEPIS,
                         SUM(DECODE(P.CDIMPOSTONFE,P_COFINS,DECODE(I.CDFISCALNF,'1',I.VRPROPRECBC,0),0)) AS VRBASECOFINS,
                         SUM(ROUND(DECODE(P.CDIMPOSTONFE,P_PIS,(I.VRPROPRECBC * I.VRALIQNF/100),0),2)) AS VRAJUSTEPIS,
                         SUM(ROUND(DECODE(P.CDIMPOSTONFE,P_COFINS,(I.VRPROPRECBC * I.VRALIQNF/100),0),2)) AS VRAJUSTECOFINS,
                         I.CDFILIAL||I.NRLANCTONF AS CHVNOTA,
                         DECODE(N.IDENTRSAIDOP,'E',N.CDFILIRECE,N.CDFILIEMIT) AS FILIAL,
                         SUM(I.VRPROPREC) AS VRCONTITIMP
                    FROM IMPBAIXAREC I, IMPOSTO P, NOTAFISCAL N, CFOPPADRAO C, FILIAL F, MAPAAPURAC M
                   WHERE M.CDEMPRESA    = P_CDEMPRESA
                     AND M.CDIMPOSTO    IN (P_PIS,P_COFINS)
                     AND M.DTINIPERIODO = P_DTINICIAL
                     AND M.DTFIMPERIODO = P_DTFINAL
                     AND M.NRSEQUMAPAPU = I.NRSEQUMAPAPU
                     AND I.CDIMPOSTO    = P.CDIMPOSTO
                     AND P.CDIMPOSTONFE IN (P_PIS,P_COFINS)
                     AND I.CDFILIAL     = N.CDFILIAL
                     AND I.NRLANCTONF   = N.NRLANCTONF
                     AND C.CDCFOPPADRAO = I.CDFISCOPERnf
                     AND C.IDTIPOCFOP   = 'D'
                     AND I.CDFISCALNF   = '1'
                     AND F.CDFILIAL     = DECODE(N.IDENTRSAIDOP,'E',N.CDFILIRECE,N.CDFILIEMIT)
                     AND ((F.IDCUMUPISCOFIL = 'N' AND N.IDENTRSAIDOP = 'E') OR /*APENAS DEVOL. VENDA PARA CUMULATIVO*/
                          (F.IDCUMUPISCOFIL = 'S' AND N.IDENTRSAIDOP IN ('E','S')))
                   GROUP BY DECODE(P.CDIMPOSTONFE,P_PIS,I.CDTPCREDPICOITE,''),
                         DECODE(P.CDIMPOSTONFE,P_COFINS,I.CDTPCREDPICOITE,''),
                         DECODE(P.CDIMPOSTONFE,P_PIS,I.VRALIQNF,''),
                         DECODE(P.CDIMPOSTONFE,P_COFINS,I.VRALIQNF,''),
                         DECODE(P.CDIMPOSTONFE,P_PIS,I.CDSITUTRIBITNFE,''),
                         DECODE(P.CDIMPOSTONFE,P_COFINS,I.CDSITUTRIBITNFE,''),
                         N.IDENTRSAIDOP,
                         I.CDFILIAL||I.NRLANCTONF,
                         DECODE(N.IDENTRSAIDOP,'E',N.CDFILIRECE,N.CDFILIEMIT)) LOOP
      IF C_AJUS.VRAJUSTEPIS > 0 THEN
         IF C_AJUS.IDAJUSTE = 'E' THEN
            IF NVL(P_GERADEVOLVEND,'A') = 'A' THEN
               V_SEQAJUST := NVL(V_SEQAJUST,0) + 1;
               INSERT INTO TMP_REGBLOCOM_PIS
                  (CHAVENOTA,CDREGISTRO, CDCONTREGI, CDTPCRED, VRALIQCRED, IDTPALIQ, CSTPISCOFINS, CDNATUBCALPCIT, IDAJUSTE, CDAJUSTE, VRBCCRED, VRAJUSTE, VRTOTNF, CDFILIAL)
               VALUES
                  (C_AJUS.CHVNOTA||'M220', 'M220', V_SEQAJUST, C_AJUS.CDTPCREDPIS, C_AJUS.VRALIQPIS, 'P', C_AJUS.CSTPIS, C_AJUS.CDNATUBCPIS, C_AJUS.IDAJUSTE, C_AJUS.CDAJUSTE, C_AJUS.VRBASEPIS, C_AJUS.VRAJUSTEPIS, C_AJUS.VRCONTITIMP, C_AJUS.FILIAL);
            END IF;
         ELSE
            IF P_CDINCTRIB = '2' THEN /*CUMULATIVO GERA APENAS M200*/
               V_SEQAJUST := NVL(V_SEQAJUST,0) + 1;
               INSERT INTO TMP_REGBLOCOM_PIS
                  (CHAVENOTA,CDREGISTRO, CDCONTREGI, CDTPCRED, VRALIQCRED, IDTPALIQ, CSTPISCOFINS, CDNATUBCALPCIT, IDAJUSTE, CDAJUSTE, VRBCCRED, VRAJUSTE, VRTOTNF, CDFILIAL)
               VALUES
                  (C_AJUS.CHVNOTA||'M220', 'M220', V_SEQAJUST, C_AJUS.CDTPCREDPIS, C_AJUS.VRALIQPIS, 'P', C_AJUS.CSTPIS, C_AJUS.CDNATUBCPIS, C_AJUS.IDAJUSTE, C_AJUS.CDAJUSTE, C_AJUS.VRBASEPIS, C_AJUS.VRAJUSTEPIS, C_AJUS.VRCONTITIMP, C_AJUS.FILIAL);
            ELSE /*NÃO-CUMULATIVO GERA COMO ACRÉSCIMO NO M100 PARA BATER COM A APURAÇÃO*/
               V_SEQAJUST := NVL(V_SEQAJUST,0) + 1;
               INSERT INTO TMP_REGBLOCOM_PIS
                  (CHAVENOTA,CDREGISTRO, CDCONTREGI, CDTPCRED, VRALIQCRED, IDTPALIQ, CSTPISCOFINS, CDNATUBCALPCIT, IDAJUSTE, CDAJUSTE, VRBCCRED, VRAJUSTE, VRTOTNF, CDFILIAL)
               VALUES
                  (C_AJUS.CHVNOTA||'M110', 'M110', V_SEQAJUST, C_AJUS.CDTPCREDPIS, C_AJUS.VRALIQPIS, 'P', C_AJUS.CSTPIS, C_AJUS.CDNATUBCPIS, C_AJUS.IDAJUSTE, C_AJUS.CDAJUSTE, C_AJUS.VRBASEPIS, C_AJUS.VRAJUSTEPIS, C_AJUS.VRCONTITIMP, C_AJUS.FILIAL);
            END IF;
         END IF;
      END IF;
      IF C_AJUS.VRAJUSTECOFINS > 0 THEN
         IF C_AJUS.IDAJUSTE = 'E' THEN
            IF NVL(P_GERADEVOLVEND,'A') = 'A' THEN
               V_SEQAJUST := NVL(V_SEQAJUST,0) + 1;
               INSERT INTO TMP_REGBLOCOM_PIS
                  (CHAVENOTA,CDREGISTRO, CDCONTREGI, CDTPCRED, VRALIQCRED, IDTPALIQ, CSTPISCOFINS, CDNATUBCALPCIT, IDAJUSTE, CDAJUSTE, VRBCCRED, VRAJUSTE, VRTOTNF, CDFILIAL)
               VALUES
                  (C_AJUS.CHVNOTA||'M620', 'M620', V_SEQAJUST, C_AJUS.CDTPCREDCOFINS, C_AJUS.VRALIQCOFINS, 'P', C_AJUS.CSTCOFINS, C_AJUS.CDNATUBCCOFINS, C_AJUS.IDAJUSTE, C_AJUS.CDAJUSTE, C_AJUS.VRBASECOFINS, C_AJUS.VRAJUSTECOFINS, C_AJUS.VRCONTITIMP, C_AJUS.FILIAL);
            END IF;
         ELSE
            IF P_CDINCTRIB = '2' THEN /*CUMULATIVO GERA APENAS M600*/
               V_SEQAJUST := NVL(V_SEQAJUST,0) + 1;
               INSERT INTO TMP_REGBLOCOM_PIS
                  (CHAVENOTA,CDREGISTRO, CDCONTREGI, CDTPCRED, VRALIQCRED, IDTPALIQ, CSTPISCOFINS, CDNATUBCALPCIT, IDAJUSTE, CDAJUSTE, VRBCCRED, VRAJUSTE, VRTOTNF, CDFILIAL)
               VALUES
                  (C_AJUS.CHVNOTA||'M620', 'M620', V_SEQAJUST, C_AJUS.CDTPCREDCOFINS, C_AJUS.VRALIQCOFINS, 'P', C_AJUS.CSTCOFINS, C_AJUS.CDNATUBCCOFINS, C_AJUS.IDAJUSTE, C_AJUS.CDAJUSTE, C_AJUS.VRBASECOFINS, C_AJUS.VRAJUSTECOFINS, C_AJUS.VRCONTITIMP, C_AJUS.FILIAL);
            ELSE /*NÃO-CUMULATIVO GERA COMO ACRÉSCIMO NO M500 PARA BATER COM A APURAÇÃO*/
               V_SEQAJUST := NVL(V_SEQAJUST,0) + 1;
               INSERT INTO TMP_REGBLOCOM_PIS
                  (CHAVENOTA,CDREGISTRO, CDCONTREGI, CDTPCRED, VRALIQCRED, IDTPALIQ, CSTPISCOFINS, CDNATUBCALPCIT, IDAJUSTE, CDAJUSTE, VRBCCRED, VRAJUSTE, VRTOTNF, CDFILIAL)
               VALUES
                  (C_AJUS.CHVNOTA||'M510', 'M510', V_SEQAJUST, C_AJUS.CDTPCREDCOFINS, C_AJUS.VRALIQCOFINS, 'P', C_AJUS.CSTCOFINS, C_AJUS.CDNATUBCCOFINS, C_AJUS.IDAJUSTE, C_AJUS.CDAJUSTE, C_AJUS.VRBASECOFINS, C_AJUS.VRAJUSTECOFINS, C_AJUS.VRCONTITIMP, C_AJUS.FILIAL);
            END IF;
         END IF;
      END IF;
   END LOOP;

   /*BUSCA A PARAMETRIZAÇÃO PARA GERAR AJUSTE AUTOMÁTICO COM A DIFERENÇA DE ARREDONDAMENTO NO CÁLCULO DO CRÉDITO PELO VALIDADOR*/
   BEGIN
      SELECT IDGERAJUSAUTSPED, DSGERAJUSAUTSPED, CDAJUSTE
        INTO V_GERAAJUSTEAUTO, V_DESCAJUSTEAUTO, V_CDAJUSTEAUTO
        FROM PARAMFISCAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_GERAAJUSTEAUTO := 'N';
         V_DESCAJUSTEAUTO := '';
         V_CDAJUSTEAUTO   := '';
   END;

   /*BUSCA O MAPA DO PIS DO PERÍODO*/
   BEGIN
      SELECT NRSEQUMAPAPU
        INTO V_NRMAPAPIS
        FROM MAPAAPURAC
       WHERE DTINIPERIODO = P_DTINICIAL
         AND DTFIMPERIODO = P_DTFINAL
         AND CDEMPRESA    = P_CDEMPRESA
         AND CDIMPOSTO    = P_PIS;
   EXCEPTION
        WHEN NO_DATA_FOUND
        THEN V_NRMAPAPIS := '';
   END;

   /*BUSCA OS VALORES DA TABELA QUE GRAVA SALDO PARA O PRÓXIMO PERÍODO, PARA SABER SE O CRÉDITO FOI TOTALMENTE UTILIZADO,
     OU, CASO CONTRÁRIO, QUANTO RESTOU PARA O PERÍODO SEGUINTE, PARA PREENCHER O REGISTRO M100*/
   V_VRSALDOFUTURO := 0;
   BEGIN
      SELECT DISTINCT NVL(VRSALDOCREDOR,0)
        INTO V_VRSALDOFUTURO
        FROM CREDANTSPED C
       WHERE C.NRSEQUMAPAPU = V_NRMAPAPIS
         AND C.CDEMPRESA    = P_CDEMPRESA
         AND C.IDTPCREDANT  = 'CA';
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_VRSALDOFUTURO := 0;
   END;
   
   /*INICIALIZA AS VARIÁVEIS COM VALOR ZERO PARA QUE AS MESMAS NÃO FIQUEM NULAS*/
   V_TIPOCREDITO     := NULL;
   V_VRACRESAJUSAUTO := 0;
   V_VRREDUZAJUSAUTO := 0;
   V_CREDUTLIZADO    := 0;

   /*REGISTRO M100*/
   FOR C_M100 IN (SELECT '|M100'                                                                                  ||'|'||
                         CDTPCRED                                                                                 ||'|'|| /*TIPO DE CREDITO*/
                         '0'                                                                                      ||'|'|| /*INDICADOR CREDITO = OP. PROPRIAS*/
                         REPLACE(LTRIM(TO_CHAR(SUM(DECODE(IDTPALIQ,'P',VRBCCRED,0)),'999999999990.00')),'.',',')  ||'|'|| /*BC PIS*/
                         REPLACE(LTRIM(TO_CHAR(DECODE(IDTPALIQ,'P',VRALIQCRED,0),'990.0000')),'.',',')            ||'|'|| /*ALIQ PIS*/
                         REPLACE(LTRIM(TO_CHAR(SUM(DECODE(IDTPALIQ,'Q',VRBCCRED,0)),'999999999990.000')),'.',',') ||'|'|| /*QTDE BC PIS*/
                         REPLACE(LTRIM(TO_CHAR(DECODE(IDTPALIQ,'Q',VRALIQCRED,''),'990.0000')),'.',',')           ||'|' AS REGM100,/*ALIQ PIS QTDE*/
                         CDTPCRED, SUM(VRCREDPIS) AS VRCREDPIS, SUM(VRCRED) AS VRCRED,
                         DECODE(IDTPALIQ,'P',VRALIQCRED, 0) AS VRALIQ_P,
                         DECODE(IDTPALIQ,'Q',VRALIQCRED,'') AS VRALIQ_Q
                    FROM (SELECT VRBCCRED*VRALIQCRED/100 AS VRCREDPIS, CDTPCRED, VRBCCRED, VRALIQCRED, IDTPALIQ, VRCRED
                            FROM (SELECT CDTPCRED, SUM(VRBCCRED) AS VRBCCRED, VRALIQCRED, SUM(VRCRED) AS VRCRED, IDTPALIQ
                                    FROM TMP_REGBLOCOM_PIS
                                   WHERE CDREGISTRO = 'M100'
                                   GROUP BY CDTPCRED, VRALIQCRED, IDTPALIQ))
                   GROUP BY CDTPCRED, IDTPALIQ, VRALIQCRED) LOOP

      /*BUSCA OS VALORES DOS AJUSTES DE CRÉDITO PARA GERAR O REGISTRO M100*/
      V_VRAJUSTEACRES  := 0;
      V_VRAJUSTEREDUC  := 0;
      V_VRCREDDIFERIDO := 0;

      /*NO CASO DE EXISTIR MAIS DE UMA ALÍQUOTA PARA O MESMO TIPO DE CRÉDITO, OS AJUSTES SERÃO GERADOS APENAS PARA A PRIMEIRA ALÍQUOTA*/
      BEGIN
         SELECT NVL(SUM(VL_AJUS_ACRES),0) AS VL_AJUS_ACRES, NVL(SUM(VL_AJUS_REDUC),0) AS VL_AJUS_REDUC
           INTO V_VRAJUSTEACRES, V_VRAJUSTEREDUC
           FROM (SELECT SUM(DECODE(A.IDTPAJUSTE,'1',A.VRAJUSTE,0)) AS VL_AJUS_ACRES,
                        SUM(DECODE(A.IDTPAJUSTE,'0',A.VRAJUSTE,0)) AS VL_AJUS_REDUC
                   FROM AJUSTEAPURCONTR A
                  WHERE A.NRSEQUMAPAPU    = V_NRMAPAPIS
                    AND A.IDINDICAJUSTE   = 'C'
                    AND A.CDTPCREDPICOITE = C_M100.CDTPCRED
                    AND ((V_TIPOCREDITO IS NULL) OR (V_TIPOCREDITO <> C_M100.CDTPCRED))
                  UNION ALL
                 SELECT SUM(DECODE(T.IDAJUSTE,'E',T.VRAJUSTE,0)) AS VL_AJUS_ACRES,
                        SUM(DECODE(T.IDAJUSTE,'S',T.VRAJUSTE,0)) AS VL_AJUS_REDUC
                   FROM TMP_REGBLOCOM_PIS T
                  WHERE T.CDREGISTRO = 'M110'
                    AND T.CDTPCRED   = C_M100.CDTPCRED
                    AND DECODE(T.IDTPALIQ,'P',T.VRALIQCRED,0)    = C_M100.VRALIQ_P
                    AND ((DECODE(T.IDTPALIQ,'Q',T.VRALIQCRED,'') = C_M100.VRALIQ_Q) OR (DECODE(T.IDTPALIQ,'Q',T.VRALIQCRED,'') IS NULL AND C_M100.VRALIQ_Q IS NULL)));
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRAJUSTEACRES := 0;
            V_VRAJUSTEREDUC := 0;
      END;

      /*BUSCA O VALOR DE CRÉDITO DIFERIDO NO PERÍODO*/
      BEGIN
         SELECT SUM(VRCREDDIFERIDO)
           INTO V_VRCREDDIFERIDO
           FROM CONTROLCREDDIF
          WHERE CDTPCREDITO  = C_M100.CDTPCRED
            AND NRSEQMAPADIF = V_NRMAPAPIS;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRCREDDIFERIDO := 0;
      END;

      IF ABS(C_M100.VRCRED - C_M100.VRCREDPIS) > 0.5 THEN
         V_VRCREDITO := C_M100.VRCREDPIS;
         IF V_GERAAJUSTEAUTO = 'S' THEN
            V_VRAJUSTEAUTO := C_M100.VRCRED-C_M100.VRCREDPIS;

            IF V_VRAJUSTEAUTO > 0 THEN
               V_VRAJUSTEACRES   := NVL(V_VRAJUSTEACRES,  0) + NVL(V_VRAJUSTEAUTO,0);
               V_VRACRESAJUSAUTO := NVL(V_VRACRESAJUSAUTO,0) + NVL(V_VRAJUSTEAUTO,0);
            ELSE
               V_VRAJUSTEREDUC   := NVL(V_VRAJUSTEREDUC,  0) + ABS(NVL(V_VRAJUSTEAUTO,0));
               V_VRREDUZAJUSAUTO := NVL(V_VRREDUZAJUSAUTO,0) + ABS(NVL(V_VRAJUSTEAUTO,0));
            END IF;
         END IF;
      ELSE
         V_VRCREDITO := C_M100.VRCRED;
      END IF;

      V_VRTOTACRED := NVL(V_VRCREDITO,0) + NVL(V_VRAJUSTEACRES,0) - NVL(V_VRAJUSTEREDUC,0) - NVL(V_VRCREDDIFERIDO,0);

      /*VERIFICA SE O CRÉDITO FOI TOTALMENTE UTILIZADO OU FOI UTILIZADO PARCIALMENTE*/
      IF V_VRSALDOFUTURO > 0 THEN
         IF V_VRSALDOFUTURO >= V_VRTOTACRED THEN
            V_CREDUTLIZADO  := 0;
            V_VRSALDOFUTURO := V_VRSALDOFUTURO - NVL(V_VRTOTACRED,0);
         ELSE
            V_CREDUTLIZADO  := NVL(V_VRTOTACRED,0) - V_VRSALDOFUTURO;
            V_VRSALDOFUTURO := 0;
         END IF;
      ELSE
         V_CREDUTLIZADO := NVL(V_VRTOTACRED,0);
      END IF;

      IF V_CREDUTLIZADO = V_VRTOTACRED THEN
         V_IDUTICRED := 0;
      ELSE
         V_IDUTICRED := 1;
      END IF;

      /*SOMA O VALOR DO CRÉDITO APLICADO O PERCENTUAL PARA GERAR O MESMO VALOR DE CREDITO NO REGISTRO M200*/
      V_VRCREDPIS := NVL(V_VRCREDPIS,0) + NVL(V_CREDUTLIZADO,0);

      /*MONTA  O RESTANTE DO REGISTRO M100 COM OS VALORES APÓS O CÁLCULO*/
      V_REGM100 := REPLACE(LTRIM(TO_CHAR(V_VRCREDITO,'999999999990.00')),'.',',')                 ||'|'|| /*08-CREDITO PIS*/
                   REPLACE(LTRIM(TO_CHAR(V_VRAJUSTEACRES,'999999999990.00')),'.',',')             ||'|'|| /*09-AJUSTE ACRESCIMO*/
                   REPLACE(LTRIM(TO_CHAR(V_VRAJUSTEREDUC,'999999999990.00')),'.',',')             ||'|'|| /*10-AJUSTE REDUCAO*/
                   REPLACE(LTRIM(TO_CHAR(NVL(V_VRCREDDIFERIDO,0),'999999999990.00')),'.',',')      ||'|'|| /*11-CREDITO DIFERIDO*/
                   REPLACE(LTRIM(TO_CHAR(V_VRTOTACRED,'999999999990.00')),'.',',')                ||'|'|| /*CREDITO (08+09-10-11)*/
                   NVL(V_IDUTICRED,'0')                                                           ||'|'|| /*INDICADOR UTILIZAÇÃO DO CRÉDITO*/
                   REPLACE(LTRIM(TO_CHAR(V_CREDUTLIZADO,'999999999990.00')),'.',',')              ||'|'|| /*VALOR DO CRÉDITO UTILIZADO*/
                   REPLACE(LTRIM(TO_CHAR(V_VRTOTACRED-V_CREDUTLIZADO,'999999999990.00')),'.',',') ||'|';  /*VALOR DO CRÉDITO PARA PERÍODO FUTURO*/
      V_CONTREGA := NVL(V_CONTREGA,0)+1;

      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'610'||LPAD(RTRIM(V_CONTREGA),22,'0'),C_M100.REGM100||V_REGM100);

      /*REGISTRO M105(APENAS PARA NÃO CUMULATIVO)*/
      IF P_CDINCTRIB <> '2' THEN
         FOR REG_M105 IN (SELECT '|M105'                                                                           ||'|'||
                                 CDNATUBCALPCIT                                                                    ||'|'||
                                 CSTPISCOFINS                                                                      ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRBCCRED),'999999999990.00')),'.',',')                  ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRBCCRECUM),'999999999990.00')),'.',',')                ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRBCCRED)-SUM(VRBCCRECUM),'999999999990.00')),'.',',')  ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRBCCRED)-SUM(VRBCCRECUM),'999999999990.00')),'.',',')  ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRBCCREDQT),'999999999990.000')),'.',',')               ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRBCCREDQT),'999999999990.000')),'.',',')               ||'|'||
                                 DECODE(CDNATUBCALPCIT,'13','OUTRAS OPERAÇÕES COM DIREITO A CRÉDITO','')           ||'|' AS REGM105,
                                 SUM(VRBCCRED) AS VRBCCRED, SUM(VRBCCRECUM) AS VRBCCRECUM
                            FROM (SELECT CDNATUBCALPCIT, CSTPISCOFINS, ROUND(SUM(VRBCCRED),2) AS VRBCCRED, IDTPALIQ,
                                         DECODE(P_CDINCTRIB,'3',DECODE(NVL(NVL(F.IDCUMUPISCOFIL,T.CDFILIAL),'S'),'N',ROUND(SUM(VRBCCRED),2),0),0) AS VRBCCRECUM,
                                         DECODE(IDTPALIQ,'Q',SUM(VRBCCRED),'') AS VRBCCREDQT
                                    FROM TMP_REGBLOCOM_PIS T, FILIAL F
                                   WHERE T.CDFILIAL          = F.CDFILIAL(+)
                                     AND NVL(T.CDTPCRED,'T') = NVL(C_M100.CDTPCRED,'T') /*CASO OS CAMPOS ESTEJAM NULOS COMPARO T COM T PARA QUE O REGISTRO SEJA GERADO MESMO ASSIM*/
                                     AND DECODE(T.IDTPALIQ,'P',T.VRALIQCRED,0)    = C_M100.VRALIQ_P
                                     AND ((DECODE(T.IDTPALIQ,'Q',T.VRALIQCRED,'') = C_M100.VRALIQ_Q) OR (DECODE(T.IDTPALIQ,'Q',T.VRALIQCRED,'') IS NULL AND C_M100.VRALIQ_Q IS NULL))
                                     AND T.CDREGISTRO        = 'M100'
                                   GROUP BY CDNATUBCALPCIT, CSTPISCOFINS, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), IDTPALIQ)
                           GROUP BY CDNATUBCALPCIT,CSTPISCOFINS,DECODE(CDNATUBCALPCIT,'13','OUTRAS OPERAÇÕES COM DIREITO A CRÉDITO',''))LOOP

            V_CONTREGA:= NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'610'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M105.REGM105);
         END LOOP;
      END IF;

      /*REGISTRO M110*/
      IF (ABS(C_M100.VRCRED - C_M100.VRCREDPIS) > 0.5) AND (V_GERAAJUSTEAUTO = 'S') THEN
         V_REGM110 := '|M110'                                                                ||'|'||
                      CASE WHEN V_VRAJUSTEAUTO > 0 THEN 1 ELSE 0 END                         ||'|'||
                      REPLACE(LTRIM(TO_CHAR(ABS(V_VRAJUSTEAUTO),'999999999990.00')),'.',',') ||'|'||
                      V_CDAJUSTEAUTO                                                         ||'|'||
                      ''                                                                     ||'|'||
                      V_DESCAJUSTEAUTO                                                       ||'|'||
                      ''                                                                     ||'|';
         V_CONTREGA:= NVL(V_CONTREGA,0)+1;
         INSERT INTO ARQMAGPISCOFINS
            (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
            (P_NRSEQARQMAG,'610'||LPAD(RTRIM(V_CONTREGA),22,'0'),V_REGM110);
      END IF;

      FOR C_M110 IN (SELECT '|M110'                                                          ||'|'||
                            IDAJUSTE                                                         ||'|'||
                            REPLACE(LTRIM(TO_CHAR(SUM(VRAJUSTE),'999999999990.00')),'.',',') ||'|'||
                            CDAJUSTE                                                         ||'|'||
                            NUMDOC                                                           ||'|'||
                            DSAJUSTE                                                         ||'|'||
                            TO_CHAR(DTAJUSTE,'DDMMYYYY')                                     ||'|' AS REGM110
                       FROM (SELECT DECODE(R.IDAJUSTE,'S','0','1') AS IDAJUSTE, R.VRAJUSTE, R.CDAJUSTE,
                                    N.NRNOTAFISC AS NUMDOC, T.NMTIPOOPER||' - '||N.NRINSJURNF AS DSAJUSTE,
                                    DECODE(N.IDENTRSAIDOP,'E',N.DTENTRSAID,N.DTEMISSAO) AS DTAJUSTE
                               FROM TMP_REGBLOCOM_PIS R, NOTAFISCAL N, TIPOOPERAC T
                              WHERE R.CDREGISTRO   = 'M110'
                                AND NVL(R.CDTPCRED,'T') = NVL(C_M100.CDTPCRED,'T') /*CASO OS CAMPOS ESTEJAM NULOS COMPARO T COM T PARA QUE O REGISTRO SEJA GERADO MESMO ASSIM*/
                                AND DECODE(R.IDTPALIQ,'P',R.VRALIQCRED,0)    = C_M100.VRALIQ_P
                                AND ((DECODE(R.IDTPALIQ,'Q',R.VRALIQCRED,'') = C_M100.VRALIQ_Q) OR (DECODE(R.IDTPALIQ,'Q',R.VRALIQCRED,'') IS NULL AND C_M100.VRALIQ_Q IS NULL))
                                AND N.CDFILIAL     = SUBSTR(R.CHAVENOTA,1,4)
                                AND N.NRLANCTONF   = SUBSTR(R.CHAVENOTA,5,10)
                                AND N.CDTIPOOPER   = T.CDTIPOOPER
                                AND N.IDENTRSAIDOP = T.IDENTRSAIDOP
                              UNION ALL
                             SELECT A.IDTPAJUSTE AS IDAJUSTE, A.VRAJUSTE, A.CDAJUSTE,
                                    A.NRPROCESSO AS NUMDOC, A.DSAJUSTE, A.DTAJUSTE
                               FROM AJUSTEAPURCONTR A
                              WHERE A.NRSEQUMAPAPU    = V_NRMAPAPIS
                                AND A.IDINDICAJUSTE   = 'C'
                                AND A.CDTPCREDPICOITE = C_M100.CDTPCRED
                                AND ((V_TIPOCREDITO IS NULL) OR (V_TIPOCREDITO <> C_M100.CDTPCRED)))
                      GROUP BY IDAJUSTE, CDAJUSTE, NUMDOC, DSAJUSTE, DTAJUSTE) LOOP

         V_CONTREGA:= NVL(V_CONTREGA,0)+1;
         INSERT INTO ARQMAGPISCOFINS
            (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
            (P_NRSEQARQMAG,'610'||LPAD(RTRIM(V_CONTREGA),22,'0'),C_M110.REGM110);
      END LOOP;

      V_TIPOCREDITO := C_M100.CDTPCRED;
   END LOOP;

   /*REGISTRO 1100 - CREDITO DE PERIODO ANTERIOR*/
   FOR C_1100 IN (SELECT '|1100'                                                      ||'|'||
                         TO_CHAR(M.DTINIPERIODO,'MMYYYY')                             ||'|'||
                         '01'                                                         ||'|'||
                         ''                                                           ||'|'||
                         '199'                                                        ||'|'||
                         REPLACE(LTRIM(TO_CHAR(C.VRSALDOCREDOR,'999999999990.00')),'.',',') ||'|'||
                         '0'                                                          ||'|'||
                         REPLACE(LTRIM(TO_CHAR(C.VRSALDOCREDOR,'999999999990.00')),'.',',') ||'|'||
                         REPLACE(LTRIM(TO_CHAR(C.VRSALDOCREDUTANT,'999999999990.00')),'.',',')        ||'|'||
                         '0'                                                          ||'|'||
                         '0'                                                          ||'|'||
                         REPLACE(LTRIM(TO_CHAR(NVL(C.VRSALDOCREDORUT,0) + NVL(C.VRSALDOCREDFIN,0),'999999999990.00')),'.',',') ||'|'||
                         REPLACE(LTRIM(TO_CHAR(C.VRSALDOCREDORUT,'999999999990.00')),'.',',')  ||'|'||
                         '0'                                                          ||'|'||
                         '0'                                                          ||'|'||
                         '0'                                                          ||'|'||
                         '0'                                                          ||'|'||
                         REPLACE(LTRIM(TO_CHAR(C.VRSALDOCREDFIN,'999999999990.00')),'.',',') ||'|' AS REG_1100
                    FROM CREDANTSPED C, MAPAAPURAC M
                   WHERE C.DTUTILIZACRED = P_DTINICIAL
                     AND C.CDEMPRESA     = P_CDEMPRESA
                     AND C.IDTPCREDANT   = 'CA'
                     AND C.CDREGISTRO    = '1100'
                     AND C.NRSEQUMAPAPU  = M.NRSEQUMAPAPU
                   ORDER BY M.NRSEQUMAPAPU) LOOP

      V_CONT := NVL(V_CONT,0) +1;
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'8011'||LPAD(V_CONT,10,'0'),C_1100.REG_1100);
   END LOOP;

   V_CDCONTRIB         := NULL;
   V_VRAJUSTENCUM      := 0;
   V_VRAJUSTECUMU      := 0;
   V_VRDIFERIMENTONCUM := 0;
   V_VRDIFERIMENTOCUMU := 0;

   /*REGISTRO M210*/
   FOR REGM210 IN (SELECT '|M210'   AS REG,
                          CDCONTRI  AS COD_CONT,
                          NVL(SUM(VRRECEITA),0) AS VL_REC_BRT,
                          NVL(DECODE(IDTPALIQ,'P',SUM(VRBCCONTRI),''),0) AS VL_BC_CONT,
                          NVL(DECODE(IDTPALIQ,'P',VRALIQCRED,''),'') AS ALIQ_PIS,
                          NVL(DECODE(IDTPALIQ,'Q',SUM(VRBCCONTRI),''),'') AS QUANT_BC_PIS, /*BC POR QUANTIDADE*/
                          NVL(DECODE(IDTPALIQ,'Q',VRALIQCRED,''),'') AS ALIQ_PIS_QUANT, /*ALIQUOTA POR QUANTIDADE*/
                          NVL(SUM(VRCONTRI),0) AS VL_CONT_APUR,
                          CDCONTRI, IDTPALIQ, VRALIQCRED, IDCUMUPISCOFIL, SUM(VRCONTRI) AS VRCONTRIBUICAO
                     FROM (/*ALÍQUOTA BÁSICA NÃO-CUMULATIVA*/
                           SELECT '01' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                  NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                             FROM TMP_REGBLOCOM_PIS T, FILIAL F
                            WHERE T.CDREGISTRO   = 'M200'
                              AND T.CDFILIAL     = F.CDFILIAL(+)
                              AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'S'
                              AND T.CSTPISCOFINS = '01'
                            GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                            UNION ALL /*ALIQUOTAS DIFERENCIADAS NÃO-CUMULATIVA*/
                           SELECT '02' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                  NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                             FROM TMP_REGBLOCOM_PIS T, FILIAL F
                            WHERE T.CDREGISTRO   = 'M200'
                              AND T.CDFILIAL     = F.CDFILIAL(+)
                              AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'S'
                              AND T.CSTPISCOFINS =  '02'
                            GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                            UNION ALL /*ALÍQUOTA BÁSICA CUMULATIVA*/
                           SELECT '51' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                  NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                             FROM TMP_REGBLOCOM_PIS T, FILIAL F
                            WHERE T.CDREGISTRO   = 'M200'
                              AND T.CDFILIAL     = F.CDFILIAL(+)
                              AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'N'
                              AND T.CSTPISCOFINS = '01'
                            GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                            UNION ALL /*ALÍQUOTA DIFERENCIADA CUMULATIVA*/
                           SELECT '52' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                  NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                             FROM TMP_REGBLOCOM_PIS T, FILIAL F
                            WHERE T.CDREGISTRO   = 'M200'
                              AND T.CDFILIAL     = F.CDFILIAL(+)
                              AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'N'
                              AND T.CSTPISCOFINS = '02'
                            GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                            UNION ALL /*CONTRIBUIÇÃO NÃO-CUMULATIVA APURADA A ALÍQUOTA POR UNIDADE DE MEDIDA DE PRODUTO*/
                           SELECT '03' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                   NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                             FROM TMP_REGBLOCOM_PIS T, FILIAL F
                            WHERE T.CDREGISTRO   = 'M200'
                              AND T.CDFILIAL     = F.CDFILIAL(+)
                              AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'S'
                              AND T.CSTPISCOFINS = '03'
                            GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                            UNION ALL /*CONTRIBUIÇÃO CUMULATIVA APURADA POR SUBSTITUIÇÃO TRIBUTÁRIA*/
                           SELECT '31' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                  NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                             FROM TMP_REGBLOCOM_PIS T, FILIAL F
                            WHERE T.CDREGISTRO   = 'M200'
                              AND T.CDFILIAL     = F.CDFILIAL(+)
                              AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'N'
                              AND T.CSTPISCOFINS = '05'
                            GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                            UNION ALL /*CONTRIBUIÇÃO NÃO-CUMULATIVA APURADA POR SUBSTITUIÇÃO TRIBUTÁRIA*/
                           SELECT '32' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                  NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                             FROM TMP_REGBLOCOM_PIS T, FILIAL F
                            WHERE T.CDREGISTRO   = 'M200'
                              AND T.CDFILIAL     = F.CDFILIAL(+)
                              AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'S'
                              AND T.CSTPISCOFINS = '05'
                            GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                            UNION ALL /*CONTRIBUIÇÃO CUMULATIVA APURADA A ALÍQUOTA POR UNIDADE DE MEDIDA DE PRODUTO*/
                           SELECT '53' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                  NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                             FROM TMP_REGBLOCOM_PIS T, FILIAL F
                            WHERE T.CDREGISTRO   = 'M200'
                              AND T.CDFILIAL     = F.CDFILIAL(+)
                              AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'N'
                              AND T.CSTPISCOFINS = '03'
                            GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS)
                    GROUP BY IDTPALIQ, VRALIQCRED, CDCONTRI, IDCUMUPISCOFIL) LOOP

      V_VRBCAJUSTEACRES := 0;
      V_VRAJUSTEACRESBC := 0;
      V_VRAJUSTEACRES   := 0;
      V_VRBCAJUSTEREDUC := 0;
      V_VRAJUSTEREDUCBC := 0;
      V_VRAJUSTEREDUC   := 0;

      BEGIN
         SELECT SUM(VRBCACRESCIMO) AS VRBCACRESCIMO, SUM(VRACRESCIMOBC) AS VRACRESCIMOBC, SUM(VRACRESCIMO) AS VRACRESCIMO, 
                SUM(VRBCREDUCAO) AS VRBCREDUCAO, SUM(VRREDUCAOBC) AS VRREDUCAOBC, SUM(VRREDUCAO) AS VRREDUCAO 
           INTO V_VRBCAJUSTEACRES, V_VRAJUSTEACRESBC, V_VRAJUSTEACRES, V_VRBCAJUSTEREDUC, V_VRAJUSTEREDUCBC, V_VRAJUSTEREDUC 
           FROM (SELECT CASE WHEN P_VERSAO >= '005' THEN SUM(DECODE(IDAJUSTE,'S',VRBCCRED,0)) ELSE 0 END AS VRBCACRESCIMO,
                        CASE WHEN P_VERSAO >= '005' THEN SUM(DECODE(IDAJUSTE,'S',VRAJUSTE,0)) ELSE 0 END AS VRACRESCIMOBC,
                        CASE WHEN P_VERSAO >= '005' THEN 0 ELSE SUM(DECODE(IDAJUSTE,'S',VRAJUSTE,0)) END AS VRACRESCIMO,
                        CASE WHEN P_VERSAO >= '005' THEN SUM(DECODE(IDAJUSTE,'E',VRBCCRED,0)) ELSE 0 END AS VRBCREDUCAO,
                        CASE WHEN P_VERSAO >= '005' THEN SUM(DECODE(IDAJUSTE,'E',VRAJUSTE,0)) ELSE 0 END AS VRREDUCAOBC,
                        CASE WHEN P_VERSAO >= '005' THEN 0 ELSE SUM(DECODE(IDAJUSTE,'E',VRAJUSTE,0)) END AS VRREDUCAO
                   FROM TMP_REGBLOCOM_PIS T, FILIAL F
                  WHERE T.CDREGISTRO   = 'M220'
                    AND T.CDFILIAL     = F.CDFILIAL(+)
                    AND T.CSTPISCOFINS IN ('49','98','99')
                    AND ((DECODE(VRALIQCRED,1.65,'01','02') = REGM210.CDCONTRI) OR
                         (DECODE(VRALIQCRED,0.65,'51','52') = REGM210.CDCONTRI))
                    AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL)  = REGM210.IDCUMUPISCOFIL
                    AND T.IDTPALIQ     = REGM210.IDTPALIQ
                    AND T.VRALIQCRED   = REGM210.VRALIQCRED
                  UNION ALL
                 SELECT SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRACRESCIMOBC,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCREDUCAO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRREDUCAOBC,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRREDUCAO
                   FROM AJUSTEAPURCONTR A
                  WHERE A.NRSEQUMAPAPU    = V_NRMAPAPIS
                    AND SUBSTR(A.IDINDICAJUSTE,1,1) = 'D'
                    AND A.IDCUMUPISCOFIL  = REGM210.IDCUMUPISCOFIL
                    AND A.CDSITUTRIBITNFE IN ('01','49','98','99')
                    AND REGM210.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','51','01')
                    AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM210.CDCONTRI))
                  UNION ALL
                 SELECT SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRACRESCIMOBC,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCREDUCAO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRREDUCAOBC,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRREDUCAO
                   FROM AJUSTEAPURCONTR A
                  WHERE A.NRSEQUMAPAPU    = V_NRMAPAPIS
                    AND SUBSTR(A.IDINDICAJUSTE,1,1) = 'D'
                    AND A.IDCUMUPISCOFIL  = REGM210.IDCUMUPISCOFIL
                    AND A.CDSITUTRIBITNFE = '02'
                    AND REGM210.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','52','02')
                    AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM210.CDCONTRI))
                  UNION ALL
                 SELECT SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRACRESCIMOBC,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCREDUCAO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRREDUCAOBC,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRREDUCAO
                   FROM AJUSTEAPURCONTR A
                  WHERE A.NRSEQUMAPAPU    = V_NRMAPAPIS
                    AND SUBSTR(A.IDINDICAJUSTE,1,1) = 'D'
                    AND A.IDCUMUPISCOFIL  = REGM210.IDCUMUPISCOFIL
                    AND A.CDSITUTRIBITNFE = '03'
                    AND REGM210.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','53','03')
                    AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM210.CDCONTRI))
                  UNION ALL
                 SELECT SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRACRESCIMOBC,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCREDUCAO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRREDUCAOBC,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRREDUCAO
                   FROM AJUSTEAPURCONTR A
                  WHERE A.NRSEQUMAPAPU    = V_NRMAPAPIS
                    AND SUBSTR(A.IDINDICAJUSTE,1,1) = 'D'
                    AND A.IDCUMUPISCOFIL  = REGM210.IDCUMUPISCOFIL
                    AND A.CDSITUTRIBITNFE = '05'
                    AND REGM210.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','31','32')
                    AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM210.CDCONTRI)));
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRBCAJUSTEACRES := 0;
            V_VRAJUSTEACRESBC := 0;
            V_VRAJUSTEACRES   := 0;
            V_VRBCAJUSTEREDUC := 0;
            V_VRAJUSTEREDUCBC := 0;
            V_VRAJUSTEREDUC   := 0;
      END;

      IF REGM210.IDCUMUPISCOFIL = 'N' THEN
         V_VRAJUSTECUMU := NVL(V_VRAJUSTECUMU,0) + NVL(V_VRAJUSTEACRES,0) - NVL(V_VRAJUSTEREDUC,0) + NVL(V_VRAJUSTEACRESBC,0) - NVL(V_VRAJUSTEREDUCBC,0);
      ELSE
         V_VRAJUSTENCUM := NVL(V_VRAJUSTENCUM,0) + NVL(V_VRAJUSTEACRES,0) - NVL(V_VRAJUSTEREDUC,0) + NVL(V_VRAJUSTEACRESBC,0) - NVL(V_VRAJUSTEREDUCBC,0);
      END IF;

      V_VRCONTRIBDIF    := 0;
      V_VRCONTRIBDIFANT := 0;

      FOR C_DIF IN (SELECT SUM(C.VRCONTRIBDIF) AS VRCONTRIBDIF, SUM(C.VRCONTRIBDIFANT) AS VRCONTRIBDIFANT, F.IDCUMUPISCOFIL
                      FROM CONTRIBDIFERIDA C, NOTAFISCAL N, FILIAL F
                     WHERE C.NRSEQMAPADIF  = V_NRMAPAPIS
                       AND C.CDFILIAL      = N.CDFILIAL
                       AND C.NRLANCTONF    = N.NRLANCTONF
                       AND N.CDFILIEMIT    = F.CDFILIAL
                       AND C.CDCONTRIBAPUR = REGM210.CDCONTRI
                     GROUP BY F.IDCUMUPISCOFIL) LOOP

         V_VRCONTRIBDIF    := NVL(V_VRCONTRIBDIF,   0) + C_DIF.VRCONTRIBDIF;
         V_VRCONTRIBDIFANT := NVL(V_VRCONTRIBDIFANT,0) + C_DIF.VRCONTRIBDIFANT;

         IF C_DIF.IDCUMUPISCOFIL = 'N' THEN
            V_VRDIFERIMENTOCUMU := NVL(V_VRDIFERIMENTOCUMU,0) - NVL(C_DIF.VRCONTRIBDIF,0) + NVL(C_DIF.VRCONTRIBDIFANT,0);
         ELSE
            V_VRDIFERIMENTONCUM := NVL(V_VRDIFERIMENTONCUM,0) - NVL(C_DIF.VRCONTRIBDIF,0) + NVL(C_DIF.VRCONTRIBDIFANT,0);
         END IF;
      END LOOP;

      V_REGM210 := REGM210.REG      ||'|'||
                   REGM210.COD_CONT ||'|'||
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM210.VL_REC_BRT,0),'999999999990.00')),'.',',')       ||'|'||
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM210.VL_BC_CONT,0),'999999999990.00')),'.',',')       ||
                   CASE WHEN P_VERSAO >= '005' THEN
                      '|'||REPLACE(LTRIM(TO_CHAR(NVL(V_VRBCAJUSTEACRES,0),'999999999990.00')),'.',',')||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(V_VRBCAJUSTEREDUC,0),'999999999990.00')),'.',',')     ||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(REGM210.VL_BC_CONT,0) + NVL(V_VRBCAJUSTEACRES,0) - NVL(V_VRBCAJUSTEREDUC,0),'999999999990.00')),'.',',')
                   ELSE '' END      ||'|'||
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM210.ALIQ_PIS,''),'990.0000')),'.',',')               ||'|'||
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM210.QUANT_BC_PIS,''),'999999999990.000')),'.',',')   ||'|'||/*BC POR QUANTIDADE*/
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM210.ALIQ_PIS_QUANT,''),'990.0000')),'.',',')         ||'|'||/*ALIQUOTA POR QUANTIDADE*/
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM210.VL_CONT_APUR,0) + NVL(V_VRAJUSTEACRESBC,0) - NVL(V_VRAJUSTEREDUCBC,0),'999999999990.00')),'.',',')     ||'|'||
                   REPLACE(LTRIM(TO_CHAR(NVL(V_VRAJUSTEACRES,0),'999999999990.00')),'.',',')          ||'|'||/*AJUSTE A ACRESCIMO*/
                   REPLACE(LTRIM(TO_CHAR(NVL(V_VRAJUSTEREDUC,0),'999999999990.00')),'.',',')          ||'|'||/*AJUSTE A REDUÇÃO*/
                   REPLACE(LTRIM(TO_CHAR(NVL(V_VRCONTRIBDIF,0),'999999999990.00')),'.',',')           ||'|'||/*VALOR CONTRI. A DIFERIR*/
                   REPLACE(LTRIM(TO_CHAR(NVL(V_VRCONTRIBDIFANT,0),'999999999990.00')),'.',',')        ||'|'||/*VALOR CONTRI. DIFERIDA PER. ANT*/
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM210.VRCONTRIBUICAO,0)+NVL(V_VRAJUSTEACRESBC,0)-NVL(V_VRAJUSTEREDUCBC,0)+NVL(V_VRAJUSTEACRES,0)-NVL(V_VRAJUSTEREDUC,0)-NVL(V_VRCONTRIBDIF,0)+NVL(V_VRCONTRIBDIFANT,0),'999999999990.00')),'.',',')||'|';

      V_CONTREGA := NVL(V_CONTREGA,0)+1;
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'622'||LPAD(RTRIM(V_CONTREGA),22,'0'),V_REGM210);

      IF P_VERSAO >= '005' THEN
         /*REGISTRO M215*/
         FOR REG_M215 IN (SELECT '|M215'                                                            ||'|'||
                                 IND_AJ_BC                                                          ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(NVL(VL_AJ_BC,0),'999999999990.00')),'.',',') ||'|'||
                                 COD_AJ_BC                                                          ||'|'||
                                 NUM_DOC                                                            ||'|'||
                                 DESCR_AJ_BC                                                        ||'|'||
                                 TO_CHAR(DT_REF,'DDMMYYYY')                                         ||'|'||
                                 COD_CTA                                                            ||'|'||
                                 CNPJ                                                               ||'|'||
                                 INFO_COMPL                                                         ||'|' AS REGM215,
                                 CNPJ, COD_CTA
                            FROM (SELECT DECODE(T.IDAJUSTE,'S','1','0') AS IND_AJ_BC,
                                         NVL(T.VRBCCRED,0) AS VL_AJ_BC,
                                         '02' AS COD_AJ_BC,
                                         N.NRNOTAFISC AS NUM_DOC,
                                         'NF de Devolução: '|| N.NRNOTAFISC || ' - ' || N.NRINSJURNF AS DESCR_AJ_BC,
                                         DECODE(N.IDENTRSAIDOP,'E',N.DTENTRSAID,N.DTEMISSAO) AS DT_REF,
                                         MAX(CONTCTBL_SPED(N.IDENTRSAIDOP, IT.CDPRODUTO, N.CDTIPOOPER, DECODE(N.IDENTRSAIDOP,'E',N.CDFILIRECE,N.CDFILIEMIT))) AS COD_CTA, 
                                         REPLACE(REPLACE(REPLACE(IE.NRINSJURIEST,'/'),'.'),'-') AS CNPJ,
                                         '' AS INFO_COMPL,
                                         T.CHAVENOTA 
                                    FROM TMP_REGBLOCOM_PIS T, FILIAL F, NOTAFISCAL N, ITEMPRODUTO IT, INSCRESTAD IE
                                   WHERE T.CDREGISTRO   = 'M220'
                                     AND T.CDFILIAL     = F.CDFILIAL(+)
                                     AND T.CSTPISCOFINS IN ('49','98','99')
                                     AND ((DECODE(VRALIQCRED,1.65,'01','02') = REGM210.CDCONTRI) OR
                                          (DECODE(VRALIQCRED,0.65,'51','52') = REGM210.CDCONTRI))
                                     AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL)  = REGM210.IDCUMUPISCOFIL
                                     AND T.IDTPALIQ     = REGM210.IDTPALIQ 
                                     AND T.VRALIQCRED   = REGM210.VRALIQCRED
                                     AND N.CDFILIAL     = SUBSTR(T.CHAVENOTA,1,4)
                                     AND N.NRLANCTONF   = SUBSTR(T.CHAVENOTA,5,10) 
                                     AND N.CDFILIAL     = IT.CDFILIAL
                                     AND N.NRLANCTONF   = IT.NRLANCTONF
                                     AND N.CDINSCESTA   = IE.CDINSCESTA
                                     AND N.CDEMPRESA    = IE.CDEMPRESA
                                     AND P_VERSAO      >= '005'
                                   GROUP BY T.IDAJUSTE, T.VRBCCRED, N.NRNOTAFISC, N.NRINSJURNF, N.IDENTRSAIDOP,
                                         N.DTENTRSAID, N.DTEMISSAO, IE.NRINSJURIEST, T.CHAVENOTA
                                   UNION ALL
                                   SELECT A.IDTPAJUSTE AS IND_AJ_BC,
                                         NVL(A.VRBASECALCAJ,0) AS VL_AJ_BC,
                                         A.CDAJUSTEBC AS COD_AJ_BC,
                                         A.NRPROCESSO AS NUM_DOC,
                                         A.DSAJUSTE AS DESCR_AJ_BC,
                                         NVL(A.DTAJUSTE,P_DTFINAL) AS DT_REF,
                                         A.CDCONTCTBL AS COD_CTA,
                                         REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'/'),'.'),'-') AS CNPJ,
                                         '' AS INFO_COMPL,
                                         A.NRSEQAJUSTE AS CHAVENOTA
                                    FROM AJUSTEAPURCONTR A, FILIAL F, INSCRESTAD I
                                   WHERE A.NRSEQUMAPAPU    = V_NRMAPAPIS
                                     AND A.IDINDICAJUSTE   = 'DB'
                                     AND A.IDCUMUPISCOFIL  = REGM210.IDCUMUPISCOFIL
                                     AND A.CDSITUTRIBITNFE IN ('01','49','98','99')
                                     AND REGM210.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','51','01')
                                     AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM210.CDCONTRI))
                                     AND A.CDFILIAL        = F.CDFILIAL
                                     AND F.CDEMPRESA       = I.CDEMPRESA
                                     AND F.CDINSCESTA      = I.CDINSCESTA
                                   UNION ALL
                                  SELECT A.IDTPAJUSTE AS IND_AJ_BC,
                                         NVL(A.VRBASECALCAJ,0) AS VL_AJ_BC,
                                         A.CDAJUSTEBC AS COD_AJ_BC,
                                         A.NRPROCESSO AS NUM_DOC,
                                         A.DSAJUSTE AS DESCR_AJ_BC,
                                         NVL(A.DTAJUSTE,P_DTFINAL) AS DT_REF,
                                         A.CDCONTCTBL AS COD_CTA,
                                         REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'/'),'.'),'-') AS CNPJ,
                                         '' AS INFO_COMPL,
                                         A.NRSEQAJUSTE AS CHAVENOTA
                                    FROM AJUSTEAPURCONTR A, FILIAL F, INSCRESTAD I
                                   WHERE A.NRSEQUMAPAPU    = V_NRMAPAPIS
                                     AND A.IDINDICAJUSTE   = 'DB'
                                     AND A.IDCUMUPISCOFIL  = REGM210.IDCUMUPISCOFIL
                                     AND A.CDSITUTRIBITNFE = '02'
                                     AND REGM210.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','52','02')
                                     AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM210.CDCONTRI))
                                     AND A.CDFILIAL        = F.CDFILIAL
                                     AND F.CDEMPRESA       = I.CDEMPRESA
                                     AND F.CDINSCESTA      = I.CDINSCESTA
                                   UNION ALL
                                  SELECT A.IDTPAJUSTE AS IND_AJ_BC,
                                         NVL(A.VRBASECALCAJ,0) AS VL_AJ_BC,
                                         A.CDAJUSTEBC AS COD_AJ_BC,
                                         A.NRPROCESSO AS NUM_DOC,
                                         A.DSAJUSTE AS DESCR_AJ_BC,
                                         NVL(A.DTAJUSTE,P_DTFINAL) AS DT_REF,
                                         A.CDCONTCTBL AS COD_CTA,
                                         REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'/'),'.'),'-') AS CNPJ,
                                         '' AS INFO_COMPL,
                                         A.NRSEQAJUSTE AS CHAVENOTA
                                    FROM AJUSTEAPURCONTR A, FILIAL F, INSCRESTAD I
                                   WHERE A.NRSEQUMAPAPU    = V_NRMAPAPIS
                                     AND A.IDINDICAJUSTE   = 'DB'
                                     AND A.IDCUMUPISCOFIL  = REGM210.IDCUMUPISCOFIL
                                     AND A.CDSITUTRIBITNFE = '03'
                                     AND REGM210.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','53','03')
                                     AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM210.CDCONTRI))
                                     AND A.CDFILIAL        = F.CDFILIAL
                                     AND F.CDEMPRESA       = I.CDEMPRESA
                                     AND F.CDINSCESTA      = I.CDINSCESTA
                                   UNION ALL
                                  SELECT A.IDTPAJUSTE AS IND_AJ_BC,
                                         NVL(A.VRBASECALCAJ,0) AS VL_AJ_BC,
                                         A.CDAJUSTEBC AS COD_AJ_BC,
                                         A.NRPROCESSO AS NUM_DOC,
                                         A.DSAJUSTE AS DESCR_AJ_BC,
                                         NVL(A.DTAJUSTE,P_DTFINAL) AS DT_REF,
                                         A.CDCONTCTBL AS COD_CTA,
                                         REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'/'),'.'),'-') AS CNPJ,
                                         '' AS INFO_COMPL,
                                         A.NRSEQAJUSTE AS CHAVENOTA
                                    FROM AJUSTEAPURCONTR A, FILIAL F, INSCRESTAD I
                                   WHERE A.NRSEQUMAPAPU    = V_NRMAPAPIS
                                     AND A.IDINDICAJUSTE   = 'DB'
                                     AND A.IDCUMUPISCOFIL  = REGM210.IDCUMUPISCOFIL
                                     AND A.CDSITUTRIBITNFE = '05'
                                     AND REGM210.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','31','32')
                                     AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM210.CDCONTRI))
                                     AND A.CDFILIAL        = F.CDFILIAL
                                     AND F.CDEMPRESA       = I.CDEMPRESA
                                     AND F.CDINSCESTA      = I.CDINSCESTA)) LOOP

            V_CONTREGA := NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'622'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M215.REGM215);

            /*VERIFICA SE O ESTABELECIMENTO JÁ FOI INSERIDO ANTERIORMENTE*/
            V_NRINSJUR := NULL;

            SELECT MAX(CDCHAVEREG) AS CNPJ
              INTO V_NRINSJUR
              FROM TMP_REGDADOSSPED_PIS
             WHERE CDREGISTRO = '0140'
               AND CDCHAVEREG = REG_M215.CNPJ;

            IF V_NRINSJUR IS NULL THEN
               V_CONTEST  := NVL(V_CONTEST,0)+1;
               V_REG      := NULL;
               BEGIN
                  SELECT '|0140'             ||'|'||
                         LTRIM(TO_CHAR(V_CONTEST,'000')) ||'|'||
                         MAX(E.NMRAZSOCEMPR) ||'|'||
                         REPLACE(REPLACE(REPLACE(REPLACE(MAX(IE.NRINSJURIEST),'.',''),'/',''),'-',''),'\','') ||'|'||
                         MAX(IE.SGESTADO)    ||'|'||
                         ''                  ||'|'||
                         MAX(M.CDMUNICIBGE)  ||'|'||
                         ''                  ||'|'||
                         ''                  ||'|'
                    INTO V_REG
                    FROM INSCRESTAD IE, MUNICIPIO M, EMPRESA E
                   WHERE IE.NRINSJURIEST = REG_M215.CNPJ
                     AND IE.CDPAIS       = M.CDPAIS
                     AND IE.SGESTADO     = M.SGESTADO
                     AND IE.CDMUNICIPIO  = M.CDMUNICIPIO
                     AND IE.CDEMPRESA    = P_CDEMPRESA
                     AND E.CDEMPRESA     = IE.CDEMPRESA
                   GROUP BY '0140';
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_REG:= NULL;
               END;

               V_COUNTBCL0:= NVL(V_COUNTBCL0,0)+1;
               INSERT INTO ARQMAGPISCOFINS
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
               VALUES
                  (P_NRSEQARQMAG,'104'||LTRIM(TO_CHAR(V_CONTEST,'000')),NVL(V_REG,'VAZIO'));

               V_SEQUPROD := NVL(V_SEQUPROD,0)+1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
                VALUES
                 ('0140', V_SEQUPROD, REG_M215.CNPJ ,NULL, LTRIM(TO_CHAR(V_CONTEST,'000')));
            END IF;

            /* CODIGO DA CONTA CONTÁBIL */
            BEGIN
               SELECT MAX(CDCHAVEREG)
                 INTO V_COD_CC
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = REG_M215.COD_CTA
                  AND CDREGISTRO = '0500';
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_COD_CC := NULL;
            END;

            IF (V_COD_CC IS NULL) AND (REG_M215.COD_CTA IS NOT NULL) THEN
               V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
               VALUES
                  ('0500', V_SEQCCTBL, REG_M215.COD_CTA, NULL);
            END IF;
         END LOOP;
      END IF;

      /*REGISTRO M220 - REGISTRO DE AJUSTES*/
      FOR REG_M220 IN (SELECT '|M220'                                                                 ||'|'||
                              IDAJUSTE                                                                ||'|'||
                              REPLACE(LTRIM(TO_CHAR(SUM(NVL(VRAJUSTE,0)),'999999999990.00')),'.',',') ||'|'||
                              CDAJUSTE                                                                ||'|'||
                              NUMDOC                                                                  ||'|'||
                              DSAJUSTE                                                                ||'|'||
                              TO_CHAR(DTAJUSTE,'DDMMYYYY')                                            ||'|' AS REGM220
                              /*DEVOLUÇÕES VENDA(ENTRADAS) REDUZEM - DEVOLUÇÕES COMPRA(SAÍDAS) ACRESCEM*/
                         FROM (SELECT DECODE(R.IDAJUSTE,'S','1','0') AS IDAJUSTE, R.VRAJUSTE, R.CDAJUSTE,
                                      N.NRNOTAFISC AS NUMDOC, T.NMTIPOOPER||' - '||N.NRINSJURNF AS DSAJUSTE,
                                      DECODE(N.IDENTRSAIDOP,'E',N.DTENTRSAID,N.DTEMISSAO) AS DTAJUSTE
                                 FROM TMP_REGBLOCOM_PIS R, FILIAL F, NOTAFISCAL N, TIPOOPERAC T
                                WHERE R.CDREGISTRO     = 'M220'
                                  AND R.CSTPISCOFINS   IN ('49','98','99')
                                  AND R.CDFILIAL       = F.CDFILIAL
                                  AND F.IDCUMUPISCOFIL = REGM210.IDCUMUPISCOFIL
                                  AND REGM210.CDCONTRI IN ('01','02','51','52')
                                  AND N.CDFILIAL       = SUBSTR(R.CHAVENOTA,1,4)
                                  AND N.NRLANCTONF     = SUBSTR(R.CHAVENOTA,5,10)
                                  AND N.CDTIPOOPER     = T.CDTIPOOPER
                                  AND N.IDENTRSAIDOP   = T.IDENTRSAIDOP
                                  AND R.IDTPALIQ       = REGM210.IDTPALIQ
                                  AND R.VRALIQCRED     = REGM210.VRALIQCRED
                                  AND P_VERSAO         < '005'
                                  AND ((DECODE(VRALIQCRED,1.65,'01','02') = REGM210.CDCONTRI) OR
                                       (DECODE(VRALIQCRED,0.65,'51','52') = REGM210.CDCONTRI))
                                UNION ALL
                               SELECT A.IDTPAJUSTE AS IDAJUSTE, A.VRAJUSTE, A.CDAJUSTE,
                                      A.NRPROCESSO AS NUMDOC, A.DSAJUSTE, A.DTAJUSTE
                                 FROM AJUSTEAPURCONTR A
                                WHERE A.NRSEQUMAPAPU    = V_NRMAPAPIS
                                  AND A.IDINDICAJUSTE   = 'DI'
                                  AND A.IDCUMUPISCOFIL = REGM210.IDCUMUPISCOFIL
                                  AND DECODE(A.CDSITUTRIBITNFE,'05',DECODE(A.IDCUMUPISCOFIL,'N','31','32'),
                                                               '03',DECODE(A.IDCUMUPISCOFIL,'N','53','03'),
                                                               '02',DECODE(A.IDCUMUPISCOFIL,'N','52','02'),
                                                               DECODE(A.IDCUMUPISCOFIL,'N','51','01')) = REGM210.CDCONTRI
                                  AND A.CDSITUTRIBITNFE IN ('01','02','03','05','49','98','99')
                                  AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM210.CDCONTRI)))
                        GROUP BY IDAJUSTE, CDAJUSTE, NUMDOC, DSAJUSTE, DTAJUSTE) LOOP

          V_CONTREGA:= NVL(V_CONTREGA,0)+1;
          INSERT INTO ARQMAGPISCOFINS
             (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
          VALUES
             (P_NRSEQARQMAG,'622'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M220.REGM220);
      END LOOP;

      /*REGISTRO M230: INFORMAÇÕES ADICIONAIS DE DIFERIMENTO*/
      FOR REG_M230 IN (SELECT '|M230'                                                                     ||'|'||
                              REPLACE(REPLACE(REPLACE(CNPJ,'.'),'/'),'-')                                 ||'|'||
                              REPLACE(LTRIM(TO_CHAR(SUM(NVL(VL_VEND,0)),'999999999990.00')),'.',',')      ||'|'||
                              REPLACE(LTRIM(TO_CHAR(SUM(NVL(VL_NAO_RECEB,0)),'999999999990.00')),'.',',') ||'|'||
                              REPLACE(LTRIM(TO_CHAR(SUM(NVL(VL_CONT_DIF,0)),'999999999990.00')),'.',',')  ||'|'||
                              REPLACE(LTRIM(TO_CHAR(SUM(NVL(VL_CRED_DIF,0)),'999999999990.00')),'.',',')  ||'|'||
                              CDTPCREDITO  ||'|' AS REGM230
                         FROM (SELECT CL.NRINSJURCLIE AS CNPJ,
                                      CD.VRCONTABIL AS VL_VEND, CD.VRCONTNAOREC AS VL_NAO_RECEB,
                                      SUM(NVL(CC.VRCONTRIBDIF,CD.VRCONTRIBDIF)) AS VL_CONT_DIF,
                                      SUM(NVL(CC.VRCREDDIFERIDO,CD.VRCREDDIFERIDO)) AS VL_CRED_DIF,
                                      CC.CDTPCREDITO, CD.NRSEQCONTRDIF
                                 FROM CONTRIBDIFERIDA CD, CLIENTE CL, NOTAFISCAL NF, FILIAL FL,
                                      (SELECT SUM(VRCREDDIFERIDO) AS VRCREDDIFERIDO, SUM(VRCONTRIBDIF) AS  VRCONTRIBDIF,
                                              CDTPCREDITO, NRSEQCONTRDIF
                                         FROM CONTROLCREDDIF
                                        WHERE NRSEQMAPADIF = V_NRMAPAPIS
                                        GROUP BY CDTPCREDITO, NRSEQCONTRDIF) CC
                                WHERE CD.NRSEQMAPADIF  = V_NRMAPAPIS
                                  AND CD.CDFILIAL      = NF.CDFILIAL
                                  AND CD.NRLANCTONF    = NF.NRLANCTONF
                                  AND NF.CDFILIEMIT    = FL.CDFILIAL
                                  AND CD.CDCONTRIBAPUR = REGM210.CDCONTRI
                                  AND CD.CDCLIENTE     = CL.CDCLIENTE
                                  AND CD.NRSEQCONTRDIF = CC.NRSEQCONTRDIF(+)
                                GROUP BY CL.NRINSJURCLIE, CD.VRCONTABIL, CD.VRCONTNAOREC, CC.VRCREDDIFERIDO, CC.CDTPCREDITO, CD.NRSEQCONTRDIF)
                         GROUP BY CNPJ, CDTPCREDITO)LOOP

          V_CONTREGA:= NVL(V_CONTREGA,0)+1;
          INSERT INTO ARQMAGPISCOFINS
             (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
          VALUES
             (P_NRSEQARQMAG,'622'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M230.REGM230);
      END LOOP;

      V_CDCONTRIB := REGM210.CDCONTRI;
   END LOOP;

   /*GERA OS REGISTROS M210 E M220 PARA ITENS DE AJUSTES QUE POSSUEM CST PARA O QUAL NÃO EXISTEM NOTAS NO PERÍODO*/
   FOR REG_M210A IN (SELECT DECODE(A.CDSITUTRIBITNFE,'05',DECODE(A.IDCUMUPISCOFIL,'N','31','32'),
                                                     '03',DECODE(A.IDCUMUPISCOFIL,'N','53','03'),
                                                     '02',DECODE(A.IDCUMUPISCOFIL,'N','52','02'),
                                                          DECODE(A.IDCUMUPISCOFIL,'N','51','01')) AS CDCONTRI,
                            SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBASECALCAJREDUC,
                            SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRAJUSTEREDUCBC,
                            SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRAJUSTEREDUC,
                            SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBASECALCAJACRES,
                            SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRAJUSTEACRESBC,
                            SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRAJUSTEACRES,
                            A.IDCUMUPISCOFIL
                       FROM AJUSTEAPURCONTR A
                      WHERE A.NRSEQUMAPAPU   = V_NRMAPAPIS
                        AND SUBSTR(A.IDINDICAJUSTE,1,1) = 'D'
                        AND A.CDSITUTRIBITNFE IN ('01','02','03','05','49','98','99')
                        AND DECODE(A.CDSITUTRIBITNFE,'05',DECODE(A.IDCUMUPISCOFIL,'N','31','32'),
                                                     '03',DECODE(A.IDCUMUPISCOFIL,'N','53','03'),
                                                     '02',DECODE(A.IDCUMUPISCOFIL,'N','52','02'),
                                                          DECODE(A.IDCUMUPISCOFIL,'N','51','01')) NOT IN (SELECT DECODE(T.CSTPISCOFINS,'05',DECODE(F.IDCUMUPISCOFIL,'N','31','32'),
                                                                                                                                       '03',DECODE(F.IDCUMUPISCOFIL,'N','53','03'),
                                                                                                                                       '02',DECODE(F.IDCUMUPISCOFIL,'N','52','02'),
                                                                                                                                            DECODE(F.IDCUMUPISCOFIL,'N','51','01')) AS COD_CONTR
                                                                                                            FROM TMP_REGBLOCOM_PIS T, FILIAL F
                                                                                                           WHERE T.CDREGISTRO IN ('M200','M220')
                                                                                                             AND T.CDFILIAL   = F.CDFILIAL(+))
                      GROUP BY DECODE(A.CDSITUTRIBITNFE,'05',DECODE(A.IDCUMUPISCOFIL,'N','31','32'),
                                                        '03',DECODE(A.IDCUMUPISCOFIL,'N','53','03'),
                                                        '02',DECODE(A.IDCUMUPISCOFIL,'N','52','02'),
                                                             DECODE(A.IDCUMUPISCOFIL,'N','51','01')), A.IDCUMUPISCOFIL) LOOP

      IF NVL(REG_M210A.VRAJUSTEACRES,0) - NVL(REG_M210A.VRAJUSTEREDUC,0) + NVL(REG_M210A.VRAJUSTEACRESBC,0) - NVL(REG_M210A.VRAJUSTEREDUCBC,0) > 0 THEN
         IF REG_M210A.IDCUMUPISCOFIL = 'N' THEN
            V_VRAJUSTECUMU := NVL(V_VRAJUSTECUMU,0) + NVL(REG_M210A.VRAJUSTEACRES,0) - NVL(REG_M210A.VRAJUSTEREDUC,0) + NVL(REG_M210A.VRAJUSTEACRESBC,0) - NVL(REG_M210A.VRAJUSTEREDUCBC,0);
         ELSE
            V_VRAJUSTENCUM := NVL(V_VRAJUSTENCUM,0) + NVL(REG_M210A.VRAJUSTEACRES,0) - NVL(REG_M210A.VRAJUSTEREDUC,0) + NVL(REG_M210A.VRAJUSTEACRESBC,0) - NVL(REG_M210A.VRAJUSTEREDUCBC,0);
         END IF;

         V_REGM210 := '|M210'            ||'|'||
                      REG_M210A.CDCONTRI ||'|'||
                      '0,00'             ||'|'||
                      '0,00'             ||
                      CASE WHEN P_VERSAO >= '005' THEN
                         '|'||REPLACE(LTRIM(TO_CHAR(NVL(REG_M210A.VRBASECALCAJACRES,0),'999999999990.00')),'.',',')||'|'||
                         REPLACE(LTRIM(TO_CHAR(NVL(REG_M210A.VRBASECALCAJREDUC,0),'999999999990.00')),'.',',')     ||'|'||
                         REPLACE(LTRIM(TO_CHAR(NVL(REG_M210A.VRBASECALCAJACRES,0) - NVL(REG_M210A.VRBASECALCAJREDUC,0),'999999999990.00')),'.',',')
                      ELSE '' END        ||'|'||
                      ''                 ||'|'||
                      ''                 ||'|'||
                      ''                 ||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(REG_M210A.VRAJUSTEACRESBC,0) - NVL(REG_M210A.VRAJUSTEREDUCBC,0),'999999999990.00')),'.',',')  ||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(REG_M210A.VRAJUSTEACRES,0),'999999999990.00')),'.',',') ||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(REG_M210A.VRAJUSTEREDUC,0),'999999999990.00')),'.',',') ||'|'||
                      ''                 ||'|'||
                      ''                 ||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(REG_M210A.VRAJUSTEACRES,0)-NVL(REG_M210A.VRAJUSTEREDUC,0)+NVL(REG_M210A.VRAJUSTEACRESBC,0)-NVL(REG_M210A.VRAJUSTEREDUCBC,0),'999999999990.00')),'.',',')||'|';

         V_CONTREGA := NVL(V_CONTREGA,0)+1;
         INSERT INTO ARQMAGPISCOFINS
            (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
            (P_NRSEQARQMAG,'622'||LPAD(RTRIM(V_CONTREGA),22,'0'),V_REGM210);

         IF P_VERSAO >= '005' THEN
            FOR REG_M215A IN (SELECT '|M215'                                                                  ||'|'||
                                     A.IDTPAJUSTE                                                             ||'|'||
                                     REPLACE(LTRIM(TO_CHAR(NVL(A.VRBASECALCAJ,0),'999999999990.00')),'.',',') ||'|'||
                                     A.CDAJUSTEBC                                                             ||'|'||
                                     A.NRPROCESSO                                                             ||'|'||
                                     A.DSAJUSTE                                                               ||'|'||
                                     TO_CHAR(NVL(A.DTAJUSTE,P_DTFINAL),'DDMMYYYY')                            ||'|'||
                                     A.CDCONTCTBL                                                             ||'|'||
                                     REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'/'),'.'),'-')                    ||'|'||
                                     ''                                                                       ||'|' AS REGM215,
                                     REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'/'),'.'),'-') AS CNPJ, A.CDCONTCTBL AS COD_CTA
                                FROM AJUSTEAPURCONTR A, FILIAL F, INSCRESTAD I
                               WHERE A.NRSEQUMAPAPU    = V_NRMAPAPIS
                                 AND A.IDINDICAJUSTE   = 'DB'
                                 AND A.CDSITUTRIBITNFE IN ('01','02','03','05','49','98','99')
                                 AND A.IDCUMUPISCOFIL  = REG_M210A.IDCUMUPISCOFIL
                                 AND DECODE(A.CDSITUTRIBITNFE,'05',DECODE(A.IDCUMUPISCOFIL,'N','31','32'),
                                                              '03',DECODE(A.IDCUMUPISCOFIL,'N','53','03'),
                                                              '02',DECODE(A.IDCUMUPISCOFIL,'N','52','02'),
                                                                   DECODE(A.IDCUMUPISCOFIL,'N','51','01')) = REG_M210A.CDCONTRI
                                 AND A.CDFILIAL        = F.CDFILIAL
                                 AND F.CDEMPRESA       = I.CDEMPRESA
                                 AND F.CDINSCESTA      = I.CDINSCESTA) LOOP

                V_CONTREGA := NVL(V_CONTREGA,0)+1;
               INSERT INTO ARQMAGPISCOFINS
                  (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
               VALUES
                  (P_NRSEQARQMAG,'622'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M215A.REGM215);

               /*VERIFICA SE O ESTABELECIMENTO JÁ FOI INSERIDO ANTERIORMENTE*/
               V_NRINSJUR := NULL;

               SELECT MAX(CDCHAVEREG) AS CNPJ
                 INTO V_NRINSJUR
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDREGISTRO = '0140'
                  AND CDCHAVEREG = REG_M215A.CNPJ;

               IF V_NRINSJUR IS NULL THEN
                  V_CONTEST  := NVL(V_CONTEST,0)+1;
                  V_REG      := NULL;
                  BEGIN
                     SELECT '|0140'             ||'|'||
                            LTRIM(TO_CHAR(V_CONTEST,'000')) ||'|'||
                            MAX(E.NMRAZSOCEMPR) ||'|'||
                            REPLACE(REPLACE(REPLACE(REPLACE(MAX(IE.NRINSJURIEST),'.',''),'/',''),'-',''),'\','') ||'|'||
                            MAX(IE.SGESTADO)    ||'|'||
                            ''                  ||'|'||
                            MAX(M.CDMUNICIBGE)  ||'|'||
                            ''                  ||'|'||
                            ''                  ||'|'
                       INTO V_REG
                       FROM INSCRESTAD IE, MUNICIPIO M, EMPRESA E
                      WHERE IE.NRINSJURIEST = REG_M215A.CNPJ
                        AND IE.CDPAIS       = M.CDPAIS
                        AND IE.SGESTADO     = M.SGESTADO
                        AND IE.CDMUNICIPIO  = M.CDMUNICIPIO
                        AND IE.CDEMPRESA    = P_CDEMPRESA
                        AND E.CDEMPRESA     = IE.CDEMPRESA
                      GROUP BY '0140';
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_REG:= NULL;
                  END;

                  V_COUNTBCL0:= NVL(V_COUNTBCL0,0)+1;
                  INSERT INTO ARQMAGPISCOFINS
                     (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
                  VALUES
                     (P_NRSEQARQMAG,'104'||LTRIM(TO_CHAR(V_CONTEST,'000')),NVL(V_REG,'VAZIO'));

                  V_SEQUPROD := NVL(V_SEQUPROD,0)+1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                    (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
                   VALUES
                    ('0140', V_SEQUPROD, REG_M215A.CNPJ ,NULL, LTRIM(TO_CHAR(V_CONTEST,'000')));
               END IF;

               /* CODIGO DA CONTA CONTÁBIL */
               BEGIN
                  SELECT MAX(CDCHAVEREG)
                    INTO V_COD_CC
                    FROM TMP_REGDADOSSPED_PIS
                   WHERE CDCHAVEREG = REG_M215A.COD_CTA
                     AND CDREGISTRO = '0500';
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_COD_CC := NULL;
               END;

               IF (V_COD_CC IS NULL) AND (REG_M215A.COD_CTA IS NOT NULL) THEN
                  V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
                  VALUES
                     ('0500', V_SEQCCTBL, REG_M215A.COD_CTA, NULL);
               END IF;
            END LOOP;
         END IF;

         FOR REG_M220A IN (SELECT '|M220'                                                                 ||'|'||
                                  IDTPAJUSTE                                                              ||'|'||
                                  REPLACE(LTRIM(TO_CHAR(SUM(NVL(VRAJUSTE,0)),'999999999990.00')),'.',',') ||'|'||
                                  CDAJUSTE                                                                ||'|'||
                                  NRPROCESSO                                                              ||'|'||
                                  DSAJUSTE                                                                ||'|'||
                                  TO_CHAR(DTAJUSTE,'DDMMYYYY')                                            ||'|' AS REGM220
                             FROM AJUSTEAPURCONTR A
                            WHERE A.NRSEQUMAPAPU    = V_NRMAPAPIS
                              AND A.IDINDICAJUSTE   = 'DI'
                              AND A.CDSITUTRIBITNFE IN ('01','02','03','05','49','98','99')
                              AND A.IDCUMUPISCOFIL  = REG_M210A.IDCUMUPISCOFIL
                              AND DECODE(A.CDSITUTRIBITNFE,'05',DECODE(A.IDCUMUPISCOFIL,'N','31','32'),
                                                           '03',DECODE(A.IDCUMUPISCOFIL,'N','53','03'),
                                                           '02',DECODE(A.IDCUMUPISCOFIL,'N','52','02'),
                                                                DECODE(A.IDCUMUPISCOFIL,'N','51','01')) = REG_M210A.CDCONTRI
                            GROUP BY IDTPAJUSTE, CDAJUSTE, NRPROCESSO, DSAJUSTE, DTAJUSTE) LOOP

            V_CONTREGA:= NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'622'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M220A.REGM220);
         END LOOP;
      END IF;
   END LOOP;

   /*BUSCA O CRÉDITO ANTERIOR UTILIZADO NO PERÍODO*/
   V_CREDANTERIOR := 0;
   BEGIN
      SELECT NVL(SUM(VRSALDOCREDORUT),0)
        INTO V_CREDANTERIOR
        FROM CREDANTSPED C
       WHERE C.NRSEQUMAPAPU  <> V_NRMAPAPIS
         AND C.CDEMPRESA     = P_CDEMPRESA
         AND C.DTUTILIZACRED = P_DTINICIAL
         AND C.IDTPCREDANT   = 'CA'
         AND C.CDREGISTRO    = '1100';
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_CREDANTERIOR := 0;
   END;

   /*BUSCA O VALOR DO IMPOSTO RETIDO UTILIZADO NO PERÍODO*/
   V_IMPRETIDONCUM := 0;
   V_IMPRETIDOCUM  := 0;
   BEGIN
      SELECT NVL(SUM(DECODE(IDCUMUPISCOFIL,'S',VRSALDOCREDORUT,0)),0),
             NVL(SUM(DECODE(IDCUMUPISCOFIL,'N',VRSALDOCREDORUT,0)),0)
        INTO V_IMPRETIDONCUM, V_IMPRETIDOCUM
        FROM CREDANTSPED C
       WHERE C.DTUTILIZACRED = P_DTINICIAL
         AND C.CDEMPRESA     = P_CDEMPRESA
         AND C.IDTPCREDANT   = 'CO'
         AND C.CDREGISTRO    = '1300';
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IMPRETIDONCUM := 0;
         V_IMPRETIDOCUM  := 0;
   END;

   /*BUSCA O VALOR DAS DEDUÇÕES CUMULATIVO E NÃO CUMULATIVO NO PERÍODO*/
   V_VRDEDUCAONCUM := 0;
   V_VRDEDUCAOCUMU := 0;
   BEGIN
      SELECT NVL(SUM(DECODE(I.IDCUMUPISCOFIL,'S',I.VRITEMDETAPU,0)),0) AS VRDEDUCAONCUM,
             NVL(SUM(DECODE(I.IDCUMUPISCOFIL,'N',I.VRITEMDETAPU,0)),0) AS VRDEDUCAOCUMU
        INTO V_VRDEDUCAONCUM, V_VRDEDUCAOCUMU
        FROM ITDETAPUCONTR I
       WHERE I.NRSEQUMAPAPU = V_NRMAPAPIS
         AND I.IDTIPODETAPU = 'DD'
       GROUP BY I.IDCUMUPISCOFIL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_VRDEDUCAONCUM := 0;
         V_VRDEDUCAOCUMU := 0;
   END;

   /*REGISTRO M200(UM POR ARQUIVO)*/
   FOR REG_M200 IN (SELECT '|M200'                                                            ||'|'||
                           REPLACE(LTRIM(TO_CHAR(VRDEBITONCUM,   '999999999990.00')),'.',',') ||'|'|| /*CONTRIB. NÃO CUMULATIVA*/
                           REPLACE(LTRIM(TO_CHAR(VRCREDNCUM,     '999999999990.00')),'.',',') ||'|'|| /*CRÉDITO UTILIZADO DO PRÓPRIO PERÍODO - NÃO CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(VRCREDANTNCUM,  '999999999990.00')),'.',',') ||'|'|| /*CRÉDITO UTILIZADO DE PERÍODOS ANTERIORES - NÃO CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(VRIMPDEVIDONCUM,'999999999990.00')),'.',',') ||'|'|| /*VR. DEVIDO NÃO CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(VRIMPRETIDONCUM,'999999999990.00')),'.',',') ||'|'|| /*RETENÇÃO NA FONTE NÃO CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(V_VRDEDUCAONCUM,'999999999990.00')),'.',',') ||'|'|| /*DEDUÇÕES NÃO CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(CASE WHEN VRIMPDEVIDONCUM - VRIMPRETIDONCUM - V_VRDEDUCAONCUM > 0 THEN VRIMPDEVIDONCUM - VRIMPRETIDONCUM - V_VRDEDUCAONCUM ELSE 0 END,'999999999990.00')),'.',',') ||'|'|| /*VR. NÃO CUMULATIVO A PAGAR*/
                           REPLACE(LTRIM(TO_CHAR(VRDEBITOCUMU,   '999999999990.00')),'.',',') ||'|'|| /*CONTRIB. CUMULATIVA*/
                           REPLACE(LTRIM(TO_CHAR(VRIMPRETIDOCUMU,'999999999990.00')),'.',',') ||'|'|| /*RETENÇÃO NA FONTE CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(V_VRDEDUCAOCUMU,'999999999990.00')),'.',',') ||'|'|| /*DEDUÇÕES CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(CASE WHEN VRDEBITOCUMU - VRIMPRETIDOCUMU - V_VRDEDUCAOCUMU > 0 THEN VRDEBITOCUMU - VRIMPRETIDOCUMU - V_VRDEDUCAOCUMU ELSE 0 END,'999999999990.00')),'.',',')       ||'|'|| /*VR. CUMULATIVO A PAGAR*/
                           REPLACE(LTRIM(TO_CHAR(CASE WHEN (CASE WHEN VRIMPDEVIDONCUM-VRIMPRETIDONCUM-V_VRDEDUCAONCUM > 0 THEN VRIMPDEVIDONCUM-VRIMPRETIDONCUM-V_VRDEDUCAONCUM ELSE 0 END + CASE WHEN VRDEBITOCUMU-VRIMPRETIDOCUMU-V_VRDEDUCAOCUMU > 0 THEN VRDEBITOCUMU-VRIMPRETIDOCUMU-V_VRDEDUCAOCUMU ELSE 0 END) > 0
                                                      THEN (CASE WHEN VRIMPDEVIDONCUM-VRIMPRETIDONCUM-V_VRDEDUCAONCUM > 0 THEN VRIMPDEVIDONCUM-VRIMPRETIDONCUM-V_VRDEDUCAONCUM ELSE 0 END + CASE WHEN VRDEBITOCUMU-VRIMPRETIDOCUMU-V_VRDEDUCAOCUMU > 0 THEN VRDEBITOCUMU-VRIMPRETIDOCUMU-V_VRDEDUCAOCUMU ELSE 0 END) ELSE 0 END,'999999999990.00')),'.',',') ||'|' AS REGM200,
                           /*BUSCA OS VALORES DE DÉBITO NÃO CUMULATIVO E CUMULATIVO PARA GERAR O REGISTRO M205*/
                           CASE WHEN VRIMPDEVIDONCUM - VRIMPRETIDONCUM - V_VRDEDUCAONCUM > 0 THEN VRIMPDEVIDONCUM - VRIMPRETIDONCUM - V_VRDEDUCAONCUM ELSE 0 END AS VRIMPRECOLNCUM,
                           CASE WHEN VRDEBITOCUMU - VRIMPRETIDOCUMU - V_VRDEDUCAOCUMU > 0 THEN VRDEBITOCUMU - VRIMPRETIDOCUMU - V_VRDEDUCAOCUMU ELSE 0 END AS VRIMPRECOLCUM
                      FROM (SELECT CASE WHEN NVL(VRDEBITONCUM,0) + V_VRAJUSTENCUM + V_VRDIFERIMENTONCUM > 0
                                        THEN NVL(VRDEBITONCUM,0) + V_VRAJUSTENCUM + V_VRDIFERIMENTONCUM
                                        ELSE 0 END AS VRDEBITONCUM,
                                   DECODE(P_CDINCTRIB,'2',0,NVL(V_VRCREDPIS, 0)) AS VRCREDNCUM,
                                   DECODE(P_CDINCTRIB,'2',0,NVL(V_CREDANTERIOR,0)) AS VRCREDANTNCUM,
                                   CASE WHEN NVL(VRDEBITONCUM,0) + V_VRAJUSTENCUM + V_VRDIFERIMENTONCUM - DECODE(P_CDINCTRIB,'2',0,NVL(V_VRCREDPIS, 0)) -  DECODE(P_CDINCTRIB,'2',0,NVL(V_CREDANTERIOR,0)) > 0
                                        THEN NVL(VRDEBITONCUM,0) + V_VRAJUSTENCUM + V_VRDIFERIMENTONCUM - DECODE(P_CDINCTRIB,'2',0,NVL(V_VRCREDPIS, 0)) -  DECODE(P_CDINCTRIB,'2',0,NVL(V_CREDANTERIOR,0)) ELSE 0 END AS VRIMPDEVIDONCUM,
                                   CASE WHEN NVL(VRDEBITOCUM,0)  + V_VRAJUSTECUMU + V_VRDIFERIMENTOCUMU > 0
                                        THEN NVL(VRDEBITOCUM,0)  + V_VRAJUSTECUMU + V_VRDIFERIMENTOCUMU
                                        ELSE 0 END AS VRDEBITOCUMU,
                                   V_IMPRETIDONCUM AS VRIMPRETIDONCUM, V_IMPRETIDOCUM AS VRIMPRETIDOCUMU
                              FROM (SELECT SUM(DECODE(NVL(F.IDCUMUPISCOFIL,T.CDFILIAL),'S',NVL(VRCRED,0),0)) AS VRDEBITONCUM,
                                           SUM(DECODE(NVL(F.IDCUMUPISCOFIL,T.CDFILIAL),'N',NVL(VRCRED,0),0)) AS VRDEBITOCUM
                                      FROM TMP_REGBLOCOM_PIS T, FILIAL F
                                     WHERE T.CDREGISTRO = 'M200'
                                       AND T.CDFILIAL   = F.CDFILIAL(+)))  /*USA ALTER JOIN NA FILIAL DEVIDO AS RECEITAS FINANCEIRAS, QUE NÃO TEM FILIAL, E O PRÓPRIO CAMPO JÁ TRAZ O REGIME*/
                     UNION
                    SELECT '|M200|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|' AS REGM200,
                           0 AS VRIMPRECOLCUM,
                           0 AS VRIMPRECOLNCUM
                      FROM DUAL
                     WHERE P_GERABCLP = '2')LOOP

      V_CONTREGA:= NVL(V_CONTREGA,0)+1;
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'620'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M200.REGM200);

      /*REGISTRO M205 - OBRIGATÓRIO A PARTIR DE ABRIL DE 2014*/
	   /*GERA O REGISTRO CASO TENHA VALOR DE IMPOSTO A RECOLHER PARA CUMULATIVO OU NÃO CUMULATIVO DE ACORDO COM OS CÓDIGOS DA RECEITA INFORMADOS NO MAPA*/
      BEGIN
         SELECT NVL(NVL(CDRECECUMU, CDRECEITACONTR||CDVARIACAO),CDRECEGUIA||NVL(CDVARIACAO,'02')), /*CASO OS ARQUIVOS GERADOS SEJAM DE MAPAS ANTIGOS PEGA O CÓDIGO DA RECEITA DO CAMPO CDRECEITACONTR CONCATENADO COM A VARIAÇÃO*/
                NVL(NVL(CDRECENCUMU,CDRECEITACONTR||CDVARIACAO),CDRECEGUIA||NVL(CDVARIACAO,'01'))
           INTO V_CDRECEPISCUMU, V_CDRECEPISNCUMU
           FROM MAPAAPURAC
          WHERE CDEMPRESA    = P_CDEMPRESA
            AND CDIMPOSTO    = P_PIS
            AND DTINIPERIODO = P_DTINICIAL
            AND DTFIMPERIODO = P_DTFINAL;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_CDRECEPISCUMU  := NULL;
            V_CDRECEPISNCUMU := NULL;
      END;

      IF ((NVL(REG_M200.VRIMPRECOLCUM,0) > 0) OR (NVL(REG_M200.VRIMPRECOLNCUM,0) > 0)) AND ((P_DTINICIAL > '31/03/2014')) THEN  /*VERIFICA SE TEVE IMPOSTO A RECOLHER SE O MÊS É MAIOR QUE MARÇO DE 2014, PARA GERAR O RESGISTRO M205*/
         IF NVL(REG_M200.VRIMPRECOLCUM,0) > 0 THEN /*VERIFICA SE TEVE DÉBITO CUMULATIVO*/
            V_REGM205_C := '|M205'         ||'|'||
                           '12'            ||'|'||
                           V_CDRECEPISCUMU ||'|'||
                           REPLACE(LTRIM(TO_CHAR(REG_M200.VRIMPRECOLCUM,'999999999990.00')),'.',',') ||'|';

            V_CONTREGA:= NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'621'||LPAD(RTRIM(V_CONTREGA),22,'0'),V_REGM205_C);

         END IF;
         IF NVL(REG_M200.VRIMPRECOLNCUM,0) > 0 THEN /*VERIFICA SE TEVE DÉBITO NÃO CUMULATIVO*/
            V_REGM205_NC := '|M205'          ||'|'||
                            '08'             ||'|'||
                            V_CDRECEPISNCUMU ||'|'||
                            REPLACE(LTRIM(TO_CHAR(REG_M200.VRIMPRECOLNCUM,'999999999990.00')),'.',',') ||'|';

            V_CONTREGA:= NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'621'||LPAD(RTRIM(V_CONTREGA),22,'0'),V_REGM205_NC);

         END IF;
      END IF;
   END LOOP;

   /*REGISTRO M300: CONTRIBUIÇÃO DE PIS/PASEP DIFERIDA EM PERÍODOS ANTERIORES – VALORES A PAGAR NO PERÍODO.*/
   FOR REG_M300 IN (SELECT '|M300'            ||'|'||
                           CD.CDCONTRIBAPUR   ||'|'||
                           REPLACE(LTRIM(TO_CHAR(SUM(NVL(CC.VRCONTRIBDIFAT, CD.VRCONTRIBDIFAT)),  '999999999990.00')),'.',',') ||'|'||
                           CC.CDNATUCREDDIF   ||'|'||
                           REPLACE(LTRIM(TO_CHAR(SUM(NVL(CC.VRCREDDIFAT, CD.VRCREDDIFAT)),        '999999999990.00')),'.',',') ||'|'||
                           REPLACE(LTRIM(TO_CHAR(SUM(NVL(CC.VRCONTRIBDIFANT, CD.VRCONTRIBDIFANT)),'999999999990.00')),'.',',') ||'|'||
                           TO_CHAR(MP.DTINIPERIODO,'MMYYYY')    ||'|'||
                           TO_CHAR(CD.DTRECEBIMENTO,'DDMMYYYY') ||'|' AS REGM300
                      FROM CONTRIBDIFERIDA CD, MAPAAPURAC MP,
                           (SELECT C.VRCONTRIBDIFAT, C.CDNATUCREDDIF, C.VRCREDDIFAT, C.VRCONTRIBDIFANT, C.NRSEQCONTRDIF
                              FROM CONTROLCREDDIF C
                             WHERE C.NRSEQMAPADIF = V_NRMAPAPIS
                               AND C.VRCONTRIBDIFANT > 0) CC
                     WHERE CD.NRSEQMAPADIF  = V_NRMAPAPIS
                       AND CD.NRSEQUMAPAPU  = MP.NRSEQUMAPAPU
                       AND CD.VRCONTRIBDIFANT > 0
                       AND CD.NRSEQCONTRDIF = CC.NRSEQCONTRDIF(+)
                     GROUP BY CD.CDCONTRIBAPUR, CC.CDNATUCREDDIF, MP.DTINIPERIODO, CD.DTRECEBIMENTO) LOOP

       V_CONTREGA:= NVL(V_CONTREGA,0)+1;
       INSERT INTO ARQMAGPISCOFINS
          (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
       VALUES
          (P_NRSEQARQMAG,'630'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M300.REGM300);
   END LOOP;

   /*REGISTRO M400*/
   FOR REGM400 IN (SELECT '|M400'       ||'|'||
                          CSTPISCOFINS  ||'|'||
                          REPLACE(LTRIM(TO_CHAR(SUM(VRTOTNF),'999999999990.00')),'.',',')||'|'||
                          CDCONTCTBL    ||'|'||
                          ''            ||'|' AS REGISTRO, CSTPISCOFINS, CDCONTCTBL
                     FROM TMP_REGBLOCOM_PIS
                    WHERE CDREGISTRO   = 'M200'
                      AND CSTPISCOFINS IN ('04','05','06','07','08','09')
                    GROUP BY 'M400', CSTPISCOFINS, CDCONTCTBL)LOOP

      V_CONTREGA:= NVL(V_CONTREGA,0)+1;
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'640'||LPAD(RTRIM(V_CONTREGA),22,'0'),REGM400.REGISTRO);

      /*REGISTRO M410*/
      FOR REGM410 IN (SELECT '|M410'      ||'|'||
                             CDNATUREC    ||'|'||
                             REPLACE(LTRIM(TO_CHAR(SUM(VRTOTNF),'999999999990.00')),'.',',')||'|'||
                             CDCONTCTBL   ||'|'||
                             ''           ||'|' AS REGISTRO
                        FROM TMP_REGBLOCOM_PIS
                       WHERE CDREGISTRO   = 'M200'
                         AND CSTPISCOFINS = REGM400.CSTPISCOFINS
                         AND CDCONTCTBL   = REGM400.CDCONTCTBL
                       GROUP BY 'M410', CDNATUREC, CDCONTCTBL)LOOP

         V_CONTREGA:= NVL(V_CONTREGA,0)+1;
         INSERT INTO ARQMAGPISCOFINS
            (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
            (P_NRSEQARQMAG,'640'||LPAD(RTRIM(V_CONTREGA),22,'0'),REGM410.REGISTRO);
      END LOOP;
   END LOOP;

   /*BUSCA O MAPA DO COFINS DO PERÍODO*/
   BEGIN
      SELECT NRSEQUMAPAPU
        INTO V_NRMAPACOFINS
        FROM MAPAAPURAC
       WHERE DTINIPERIODO = P_DTINICIAL
         AND DTFIMPERIODO = P_DTFINAL
         AND CDEMPRESA    = P_CDEMPRESA
         AND CDIMPOSTO    = P_COFINS;
   EXCEPTION
        WHEN NO_DATA_FOUND
        THEN V_NRMAPACOFINS := '';
   END;

   /*BUSCA OS VALORES DA TABELA QUE GRAVA SALDO PARA O PRÓXIMO PERÍODO, PARA SABER SE O CRÉDITO FOI TOTALMENTE UTILIZADO,
     OU, CASO CONTRÁRIO, QUANTO RESTOU PARA O PERÍODO SEGUINTE, PARA PREENCHER O REGISTRO M500*/
   V_VRSALDOFUTURO := 0;
   BEGIN
      SELECT DISTINCT NVL(VRSALDOCREDOR,0)
        INTO V_VRSALDOFUTURO
        FROM CREDANTSPED C
       WHERE C.NRSEQUMAPAPU = V_NRMAPACOFINS
         AND C.CDEMPRESA    = P_CDEMPRESA
         AND C.IDTPCREDANT  = 'CA';
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_VRSALDOFUTURO := 0;
   END;

   /*INICIALIZA AS VARIÁVEIS COM VALOR ZERO PARA QUE AS MESMAS NÃO FIQUEM NULAS*/
   V_TIPOCREDITO     := NULL;
   V_VRACRESAJUSAUTO := 0;
   V_VRREDUZAJUSAUTO := 0;
   V_CREDUTLIZADO    := 0;

   /*REGISTRO M500*/
   FOR C_M500 IN (SELECT '|M500'                                                                                   ||'|'||
                         CDTPCRED                                                                                  ||'|'|| /*TIPO DE CREDITO*/
                         '0'                                                                                       ||'|'|| /*INDICADOR CREDITO = OP. PROPRIAS*/
                         REPLACE(LTRIM(TO_CHAR(SUM(DECODE(IDTPALIQ,'P',VRBCCRED,0)),'999999999990.00')),'.',',')   ||'|'|| /*BC COFINS*/
                         REPLACE(LTRIM(TO_CHAR(DECODE(IDTPALIQ,'P',VRALIQCRED,0),'990.0000')),'.',',')             ||'|'|| /*ALIQ COFINS*/
                         REPLACE(LTRIM(TO_CHAR(SUM(DECODE(IDTPALIQ,'Q',VRBCCRED,0)),'999999999990.000')),'.',',')  ||'|'|| /*QTDE BC COFINS*/
                         REPLACE(LTRIM(TO_CHAR(DECODE(IDTPALIQ,'Q',VRALIQCRED,''),'990.0000')),'.',',')            ||'|' AS REGM500, /*ALIQ COFINS QTDE*/
                         CDTPCRED, SUM(VRCREDCOFINS) AS VRCREDCOFINS, SUM(VRCRED) AS VRCRED,
                         DECODE(IDTPALIQ,'P',VRALIQCRED, 0) AS VRALIQ_P,
                         DECODE(IDTPALIQ,'Q',VRALIQCRED,'') AS VRALIQ_Q
                    FROM (SELECT VRBCCRED*VRALIQCRED/100 AS VRCREDCOFINS, CDTPCRED, VRBCCRED, VRALIQCRED, IDTPALIQ, VRCRED
                            FROM (SELECT CDTPCRED, SUM(VRBCCRED) AS VRBCCRED, VRALIQCRED, SUM(VRCRED) AS VRCRED, IDTPALIQ
                                    FROM TMP_REGBLOCOM_PIS
                                   WHERE CDREGISTRO = 'M500'
                                   GROUP BY CDTPCRED, VRALIQCRED, IDTPALIQ))
                   GROUP BY CDTPCRED, IDTPALIQ, VRALIQCRED) LOOP

      /*BUSCA OS VALORES DOS AJUSTES DE CRÉDITO PARA GERAR O REGISTRO M500*/
      V_VRAJUSTEACRES  := 0;
      V_VRAJUSTEREDUC  := 0;
      V_VRCREDDIFERIDO := 0;

      /*NO CASO DE EXISTIR MAIS DE UMA ALÍQUOTA PARA O MESMO TIPO DE CRÉDITO, OS AJUSTES SERÃO GERADOS APENAS PARA A PRIMEIRA ALÍQUOTA*/
      BEGIN
         SELECT NVL(SUM(VL_AJUS_ACRES),0) AS VL_AJUS_ACRES, NVL(SUM(VL_AJUS_REDUC),0) AS VL_AJUS_REDUC
           INTO V_VRAJUSTEACRES, V_VRAJUSTEREDUC
           FROM (SELECT SUM(DECODE(A.IDTPAJUSTE,'1',A.VRAJUSTE,0)) AS VL_AJUS_ACRES,
                        SUM(DECODE(A.IDTPAJUSTE,'0',A.VRAJUSTE,0)) AS VL_AJUS_REDUC
                   FROM AJUSTEAPURCONTR A
                  WHERE A.NRSEQUMAPAPU    = V_NRMAPACOFINS
                    AND A.IDINDICAJUSTE   = 'C'
                    AND A.CDTPCREDPICOITE = C_M500.CDTPCRED
                    AND ((V_TIPOCREDITO IS NULL) OR (V_TIPOCREDITO <> C_M500.CDTPCRED))
                  UNION ALL
                 SELECT SUM(DECODE(T.IDAJUSTE,'E',T.VRAJUSTE,0)) AS VL_AJUS_ACRES,
                        SUM(DECODE(T.IDAJUSTE,'S',T.VRAJUSTE,0)) AS VL_AJUS_REDUC
                   FROM TMP_REGBLOCOM_PIS T
                  WHERE T.CDREGISTRO = 'M510'
                    AND T.CDTPCRED   = C_M500.CDTPCRED
                    AND DECODE(T.IDTPALIQ,'P',T.VRALIQCRED,0)    = C_M500.VRALIQ_P
                    AND ((DECODE(T.IDTPALIQ,'Q',T.VRALIQCRED,'') = C_M500.VRALIQ_Q) OR (DECODE(T.IDTPALIQ,'Q',T.VRALIQCRED,'') IS NULL AND C_M500.VRALIQ_Q IS NULL)));
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRAJUSTEACRES := 0;
            V_VRAJUSTEREDUC := 0;
      END;

      /*BUSCA O VALOR DE CRÉDITO DIFERIDO NO PERÍODO*/
      BEGIN
         SELECT SUM(VRCREDDIFERIDO)
           INTO V_VRCREDDIFERIDO
           FROM CONTROLCREDDIF
          WHERE CDTPCREDITO  = C_M500.CDTPCRED
            AND NRSEQMAPADIF = V_NRMAPACOFINS;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRCREDDIFERIDO := 0;
      END;

      IF ABS(C_M500.VRCRED - C_M500.VRCREDCOFINS) > 0.5 THEN
         V_VRCREDITO := C_M500.VRCREDCOFINS;
         IF V_GERAAJUSTEAUTO = 'S' THEN
            V_VRAJUSTEAUTO := C_M500.VRCRED-C_M500.VRCREDCOFINS;

            IF V_VRAJUSTEAUTO > 0 THEN
               V_VRAJUSTEACRES   := NVL(V_VRAJUSTEACRES,  0) + NVL(V_VRAJUSTEAUTO,0);
               V_VRACRESAJUSAUTO := NVL(V_VRACRESAJUSAUTO,0) + NVL(V_VRAJUSTEAUTO,0);
            ELSE
               V_VRAJUSTEREDUC   := NVL(V_VRAJUSTEREDUC,  0) + ABS(NVL(V_VRAJUSTEAUTO,0));
               V_VRREDUZAJUSAUTO := NVL(V_VRREDUZAJUSAUTO,0) + ABS(NVL(V_VRAJUSTEAUTO,0));
            END IF;
         END IF;
      ELSE
         V_VRCREDITO := C_M500.VRCRED;
      END IF;

      V_VRTOTACRED := NVL(V_VRCREDITO,0) + NVL(V_VRAJUSTEACRES,0) - NVL(V_VRAJUSTEREDUC,0) - NVL(V_VRCREDDIFERIDO,0);

      /*VERIFICA SE O CRÉDITO FOI TOTALMENTE UTILIZADO OU FOI UTILIZADO PARCIALMENTE*/
      IF V_VRSALDOFUTURO > 0 THEN
         IF V_VRSALDOFUTURO >= V_VRTOTACRED THEN
            V_CREDUTLIZADO  := 0;
            V_VRSALDOFUTURO := V_VRSALDOFUTURO - NVL(V_VRTOTACRED,0);
         ELSE
            V_CREDUTLIZADO  := NVL(V_VRTOTACRED,0) - V_VRSALDOFUTURO;
            V_VRSALDOFUTURO := 0;
         END IF;
      ELSE
         V_CREDUTLIZADO := NVL(V_VRTOTACRED,0);
      END IF;

      IF V_CREDUTLIZADO = V_VRTOTACRED THEN
         V_IDUTICRED := 0;
      ELSE
         V_IDUTICRED := 1;
      END IF;

      /*SOMA O VALOR DO CRÉDITO APLICADO O PERCENTUAL PARA GERAR O MESMO VALOR DE CREDITO NO REGISTRO M200*/
      V_VRCREDCOFINS := NVL(V_VRCREDCOFINS,0) + NVL(V_CREDUTLIZADO,0);

      /*MONTA O RESTANTE DO REGISTRO M500 COM OS VALORES APÓS O CÁLCULO*/
      V_REGM500 := REPLACE(LTRIM(TO_CHAR(V_VRCREDITO,'999999999990.00')),'.',',')                 ||'|'|| /*08-CREDITO COFINS*/
                   REPLACE(LTRIM(TO_CHAR(V_VRAJUSTEACRES,'999999999990.00')),'.',',')             ||'|'|| /*09-AJUSTE ACRESCIMO*/
                   REPLACE(LTRIM(TO_CHAR(V_VRAJUSTEREDUC,'999999999990.00')),'.',',')             ||'|'|| /*10-AJUSTE REDUCAO*/
                   REPLACE(LTRIM(TO_CHAR(NVL(V_VRCREDDIFERIDO,0),'999999999990.00')),'.',',')     ||'|'|| /*11-CREDITO DIFERIDO*/
                   REPLACE(LTRIM(TO_CHAR(V_VRTOTACRED,'999999999990.00')),'.',',')                ||'|'|| /*CREDITO (08+09-10-11)*/
                   NVL(V_IDUTICRED,'0')                                                           ||'|'|| /*INDICADOR UTILIZAÇÃO DO CRÉDITO*/
                   REPLACE(LTRIM(TO_CHAR(V_CREDUTLIZADO,'999999999990.00')),'.',',')              ||'|'|| /*VALOR DO CRÉDITO UTILIZADO*/
                   REPLACE(LTRIM(TO_CHAR(V_VRTOTACRED-V_CREDUTLIZADO,'999999999990.00')),'.',',') ||'|';  /*VALOR DO CRÉDITO PARA PERÍODO FUTURO*/
      V_CONTREGA:= NVL(V_CONTREGA,0)+1;

      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'650'||LPAD(RTRIM(V_CONTREGA),22,'0'),C_M500.REGM500||V_REGM500);

      /*REGISTRO M505(APENAS PARA NÃO CUMULATIVO)*/
      IF P_CDINCTRIB <> '2' THEN
         FOR REG_M505 IN (SELECT '|M505'                                                                          ||'|'||
                                 CDNATUBCALPCIT                                                                   ||'|'||
                                 CSTPISCOFINS                                                                     ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRBCCRED),'999999999990.00')),'.',',')                 ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRBCCRECUM),'999999999990.00')),'.',',')               ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRBCCRED)-SUM(VRBCCRECUM),'999999999990.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRBCCRED)-SUM(VRBCCRECUM),'999999999990.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRBCCREDQT),'999999999990.000')),'.',',')              ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRBCCREDQT),'999999999990.000')),'.',',')              ||'|'||
                                 DECODE(CDNATUBCALPCIT,'13','OUTRAS OPERAÇÕES COM DIREITO A CRÉDITO','')          ||'|' AS REGM505,
                                 SUM(VRBCCRED) AS VRBCCRED, SUM(VRBCCRECUM) AS VRBCCRECUM
                            FROM (SELECT CDNATUBCALPCIT, CSTPISCOFINS, ROUND(SUM(VRBCCRED),2) AS VRBCCRED, IDTPALIQ,
                                         DECODE(P_CDINCTRIB,'3',DECODE(NVL(NVL(F.IDCUMUPISCOFIL,T.CDFILIAL),'S'),'N',ROUND(SUM(VRBCCRED),2),0),0) AS VRBCCRECUM,
                                         DECODE(IDTPALIQ,'Q',SUM(VRBCCRED),'') AS VRBCCREDQT
                                    FROM TMP_REGBLOCOM_PIS T, FILIAL F
                                   WHERE T.CDFILIAL          = F.CDFILIAL(+)
                                     AND NVL(T.CDTPCRED,'T') = NVL(C_M500.CDTPCRED,'T') /*CASO OS CAMPOS ESTEJAM NULOS COMPARO T COM T PARA QUE O REGISTRO SEJA GERADO MESMO ASSIM(NÃO DÁ PARA FAZER NULL=NULL)*/
                                     AND DECODE(T.IDTPALIQ,'P',T.VRALIQCRED,0)    = C_M500.VRALIQ_P
                                     AND ((DECODE(T.IDTPALIQ,'Q',T.VRALIQCRED,'') = C_M500.VRALIQ_Q) OR (DECODE(T.IDTPALIQ,'Q',T.VRALIQCRED,'') IS NULL AND C_M500.VRALIQ_Q IS NULL))
                                     AND T.CDREGISTRO        = 'M500'
                                   GROUP BY CDNATUBCALPCIT, CSTPISCOFINS, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), IDTPALIQ)
                           GROUP BY CDNATUBCALPCIT,CSTPISCOFINS,DECODE(CDNATUBCALPCIT,'13','OUTRAS OPERAÇÕES COM DIREITO A CRÉDITO',''))LOOP

            V_CONTREGA:= NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'650'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M505.REGM505);
         END LOOP;
      END IF;

      /*REGISTRO M510*/
      IF (ABS(C_M500.VRCRED - C_M500.VRCREDCOFINS) > 0.5) AND (V_GERAAJUSTEAUTO = 'S') THEN
         V_REGM510 := '|M510'                                                                ||'|'||
                      CASE WHEN V_VRAJUSTEAUTO > 0 THEN 1 ELSE 0 END                         ||'|'||
                      REPLACE(LTRIM(TO_CHAR(ABS(V_VRAJUSTEAUTO),'999999999990.00')),'.',',') ||'|'||
                      V_CDAJUSTEAUTO                                                         ||'|'||
                      ''                                                                     ||'|'||
                      V_DESCAJUSTEAUTO                                                       ||'|'||
                      ''                                                                     ||'|';
         V_CONTREGA:= NVL(V_CONTREGA,0)+1;
         INSERT INTO ARQMAGPISCOFINS
            (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
            (P_NRSEQARQMAG,'650'||LPAD(RTRIM(V_CONTREGA),22,'0'),V_REGM510);
      END IF;

      FOR REG_M510 IN (SELECT '|M510'                                                          ||'|'||
                              IDAJUSTE                                                         ||'|'||
                              REPLACE(LTRIM(TO_CHAR(SUM(VRAJUSTE),'999999999990.00')),'.',',') ||'|'||
                              CDAJUSTE                                                         ||'|'||
                              NUMDOC                                                           ||'|'||
                              DSAJUSTE                                                         ||'|'||
                              TO_CHAR(DTAJUSTE,'DDMMYYYY')                                     ||'|' AS REGM510
                         FROM (SELECT DECODE(R.IDAJUSTE,'S','0','1') AS IDAJUSTE, R.VRAJUSTE, R.CDAJUSTE,
                                      N.NRNOTAFISC AS NUMDOC, T.NMTIPOOPER||' - '||N.NRINSJURNF AS DSAJUSTE,
                                      DECODE(N.IDENTRSAIDOP,'E',N.DTENTRSAID,N.DTEMISSAO) AS DTAJUSTE
                                 FROM TMP_REGBLOCOM_PIS R, NOTAFISCAL N, TIPOOPERAC T
                                WHERE R.CDREGISTRO = 'M510'
                                  AND NVL(R.CDTPCRED,'T') = NVL(C_M500.CDTPCRED,'T') /*CASO OS CAMPOS ESTEJAM NULOS COMPARO T COM T PARA QUE O REGISTRO SEJA GERADO MESMO ASSIM*/
                                  AND DECODE(R.IDTPALIQ,'P',R.VRALIQCRED,0)    = C_M500.VRALIQ_P
                                  AND ((DECODE(R.IDTPALIQ,'Q',R.VRALIQCRED,'') = C_M500.VRALIQ_Q) OR (DECODE(R.IDTPALIQ,'Q',R.VRALIQCRED,'') IS NULL AND C_M500.VRALIQ_Q IS NULL))
                                  AND N.CDFILIAL     = SUBSTR(R.CHAVENOTA,1,4)
                                  AND N.NRLANCTONF   = SUBSTR(R.CHAVENOTA,5,10)
                                  AND N.CDTIPOOPER   = T.CDTIPOOPER
                                  AND N.IDENTRSAIDOP = T.IDENTRSAIDOP
                                UNION ALL
                               SELECT A.IDTPAJUSTE AS IDAJUSTE, A.VRAJUSTE, A.CDAJUSTE,
                                      A.NRPROCESSO AS NUMDOC, A.DSAJUSTE, A.DTAJUSTE
                                 FROM AJUSTEAPURCONTR A
                                WHERE A.NRSEQUMAPAPU    = V_NRMAPACOFINS
                                  AND A.IDINDICAJUSTE   = 'C'
                                  AND A.CDTPCREDPICOITE = C_M500.CDTPCRED
                                  AND ((V_TIPOCREDITO IS NULL) OR (V_TIPOCREDITO <> C_M500.CDTPCRED)))
                        GROUP BY IDAJUSTE, CDAJUSTE, NUMDOC, DSAJUSTE, DTAJUSTE) LOOP

          V_CONTREGA:= NVL(V_CONTREGA,0)+1;
          INSERT INTO ARQMAGPISCOFINS
             (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
          VALUES
             (P_NRSEQARQMAG,'650'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M510.REGM510);
      END LOOP;

      V_TIPOCREDITO := C_M500.CDTPCRED;
   END LOOP;

   /*REGISTRO 1500 - CREDITO DE PERIODO ANTERIOR*/
   FOR C_1500 IN (SELECT '|1500'                                                               ||'|'||
                         TO_CHAR(M.DTINIPERIODO,'MMYYYY')                                      ||'|'||
                         '01'                                                                  ||'|'||
                         ''                                                                    ||'|'||
                         '199'                                                                 ||'|'||
                         REPLACE(LTRIM(TO_CHAR(C.VRSALDOCREDOR,'999999999990.00')),'.',',')    ||'|'||
                         '0'                                                                   ||'|'||
                         REPLACE(LTRIM(TO_CHAR(C.VRSALDOCREDOR,'999999999990.00')),'.',',')    ||'|'||
                         REPLACE(LTRIM(TO_CHAR(C.VRSALDOCREDUTANT,'999999999990.00')),'.',',') ||'|'||
                         '0'                                                                   ||'|'||
                         '0'                                                                   ||'|'||
                         REPLACE(LTRIM(TO_CHAR(NVL(C.VRSALDOCREDORUT,0) + NVL(C.VRSALDOCREDFIN,0),'999999999990.00')),'.',',') ||'|'||
                         REPLACE(LTRIM(TO_CHAR(C.VRSALDOCREDORUT,'999999999990.00')),'.',',')  ||'|'||
                         '0'                                                                   ||'|'||
                         '0'                                                                   ||'|'||
                         '0'                                                                   ||'|'||
                         '0'                                                                   ||'|'||
                         REPLACE(LTRIM(TO_CHAR(C.VRSALDOCREDFIN,'999999999990.00')),'.',',')   ||'|' AS REG_1500
                    FROM CREDANTSPED C, MAPAAPURAC M
                   WHERE C.DTUTILIZACRED = P_DTINICIAL
                     AND C.CDEMPRESA     = P_CDEMPRESA
                     AND C.IDTPCREDANT   = 'CA'
                     AND C.CDREGISTRO    = '1500'
                     AND C.NRSEQUMAPAPU  = M.NRSEQUMAPAPU
                   ORDER BY M.NRSEQUMAPAPU) LOOP

      V_CONT := NVL(V_CONT,0) +1;
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'8013'||LPAD(V_CONT,10,'0'),C_1500.REG_1500);
   END LOOP;

   V_CDCONTRIB         := NULL;
   V_VRAJUSTENCUM      := 0;
   V_VRAJUSTECUMU      := 0;
   V_VRDIFERIMENTONCUM := 0;
   V_VRDIFERIMENTOCUMU := 0;

   /*REGISTRO M610*/
   FOR REGM610 IN (SELECT '|M610'   AS REG,
                          CDCONTRI  AS COD_CONT,
                          NVL(SUM(VRRECEITA),0) AS VL_REC_BRT,
                          NVL(DECODE(IDTPALIQ,'P',SUM(VRBCCONTRI),''),0) AS VL_BC_CONT,
                          NVL(DECODE(IDTPALIQ,'P',VRALIQCRED,''),'') AS ALIQ_COFINS,
                          NVL(DECODE(IDTPALIQ,'Q',SUM(VRBCCONTRI),''),'') AS QUANT_BC_COFINS, /*BC POR QUANTIDADE*/
                          NVL(DECODE(IDTPALIQ,'Q',VRALIQCRED,''),'') AS ALIQ_COFINS_QUANT, /*ALIQUOTA POR QUANTIDADE*/
                          NVL(SUM(VRCONTRI),0) AS VL_CONT_APUR,
                          CDCONTRI, IDTPALIQ, VRALIQCRED, IDCUMUPISCOFIL, SUM(VRCONTRI) AS VRCONTRIBUICAO
                   FROM (/*ALÍQUOTA BÁSICA NÃO-CUMULATIVA*/
                         SELECT '01' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                           FROM TMP_REGBLOCOM_PIS T, FILIAL F
                          WHERE T.CDREGISTRO   = 'M600'
                            AND T.CDFILIAL     = F.CDFILIAL(+)
                            AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'S'
                            AND T.CSTPISCOFINS = '01'
                          GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                         UNION ALL /*ALIQUOTAS DIFERENCIADAS NÃO-CUMULATIVA*/
                         SELECT '02' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                           FROM TMP_REGBLOCOM_PIS T, FILIAL F
                          WHERE T.CDREGISTRO   = 'M600'
                            AND T.CDFILIAL     = F.CDFILIAL(+)
                            AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'S'
                            AND T.CSTPISCOFINS =  '02'
                          GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                         UNION ALL /*ALÍQUOTA BÁSICA CUMULATIVA*/
                         SELECT '51' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                           FROM TMP_REGBLOCOM_PIS T, FILIAL F
                          WHERE T.CDREGISTRO   = 'M600'
                            AND T.CDFILIAL     = F.CDFILIAL(+)
                            AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'N'
                            AND T.CSTPISCOFINS = '01'
                          GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                         UNION ALL /*ALÍQUOTA DIFERENCIADA CUMULATIVA*/
                         SELECT '52' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                           FROM TMP_REGBLOCOM_PIS T, FILIAL F
                          WHERE T.CDREGISTRO   = 'M600'
                            AND T.CDFILIAL     = F.CDFILIAL(+)
                            AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'N'
                            AND T.CSTPISCOFINS = '02'
                          GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                         UNION ALL /*CONTRIBUIÇÃO NÃO-CUMULATIVA APURADA A ALÍQUOTA POR UNIDADE DE MEDIDA DE PRODUTO*/
                         SELECT '03' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                           FROM TMP_REGBLOCOM_PIS T, FILIAL F
                          WHERE T.CDREGISTRO   = 'M600'
                            AND T.CDFILIAL     = F.CDFILIAL(+)
                            AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'S'
                            AND T.CSTPISCOFINS = '03'
                          GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                          UNION ALL /*CONTRIBUIÇÃO CUMULATIVA APURADA POR SUBSTITUIÇÃO TRIBUTÁRIA*/
                         SELECT '31' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                           FROM TMP_REGBLOCOM_PIS T, FILIAL F
                          WHERE T.CDREGISTRO   = 'M600'
                            AND T.CDFILIAL     = F.CDFILIAL(+)
                            AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'N'
                            AND T.CSTPISCOFINS = '05'
                          GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                          UNION ALL /*CONTRIBUIÇÃO NÃO-CUMULATIVA APURADA POR SUBSTITUIÇÃO TRIBUTÁRIA*/
                         SELECT '32' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                           FROM TMP_REGBLOCOM_PIS T, FILIAL F
                          WHERE T.CDREGISTRO   = 'M600'
                            AND T.CDFILIAL     = F.CDFILIAL(+)
                            AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'S'
                            AND T.CSTPISCOFINS = '05'
                          GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS
                          UNION ALL /*CONTRIBUIÇÃO CUMULATIVA APURADA A ALÍQUOTA POR UNIDADE DE MEDIDA DE PRODUTO*/
                         SELECT '53' AS CDCONTRI, SUM(VRTOTNF) AS VRRECEITA ,SUM(VRBCCRED) AS VRBCCONTRI, VRALIQCRED, SUM(VRCRED) AS VRCONTRI,IDTPALIQ,
                                NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) AS IDCUMUPISCOFIL, CSTPISCOFINS
                           FROM TMP_REGBLOCOM_PIS T, FILIAL F
                          WHERE T.CDREGISTRO   = 'M600'
                            AND T.CDFILIAL     = F.CDFILIAL(+)
                            AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL) = 'N'
                            AND T.CSTPISCOFINS = '03'
                          GROUP BY VRALIQCRED, IDTPALIQ, NVL(F.IDCUMUPISCOFIL,T.CDFILIAL), CSTPISCOFINS)
                   GROUP BY IDTPALIQ, VRALIQCRED, CDCONTRI, IDCUMUPISCOFIL) LOOP

      V_VRBCAJUSTEACRES := 0;
      V_VRAJUSTEACRESBC := 0;
      V_VRAJUSTEACRES   := 0;
      V_VRBCAJUSTEREDUC := 0;
      V_VRAJUSTEREDUCBC := 0;
      V_VRAJUSTEREDUC   := 0;

      BEGIN
         SELECT SUM(VRBCACRESCIMO) AS VRBCACRESCIMO, SUM(VRACRESCIMOBC) AS VRACRESCIMOBC, SUM(VRACRESCIMO) AS VRACRESCIMO, 
                SUM(VRBCREDUCAO) AS VRBCREDUCAO, SUM(VRREDUCAOBC) AS VRREDUCAOBC, SUM(VRREDUCAO) AS VRREDUCAO 
           INTO V_VRBCAJUSTEACRES, V_VRAJUSTEACRESBC, V_VRAJUSTEACRES, V_VRBCAJUSTEREDUC, V_VRAJUSTEREDUCBC, V_VRAJUSTEREDUC
           FROM (SELECT CASE WHEN P_VERSAO >= '005' THEN SUM(DECODE(IDAJUSTE,'S',VRBCCRED,0)) ELSE 0 END AS VRBCACRESCIMO,
                        CASE WHEN P_VERSAO >= '005' THEN SUM(DECODE(IDAJUSTE,'S',VRAJUSTE,0)) ELSE 0 END AS VRACRESCIMOBC,
                        CASE WHEN P_VERSAO >= '005' THEN 0 ELSE SUM(DECODE(IDAJUSTE,'S',VRAJUSTE,0)) END AS VRACRESCIMO,
                        CASE WHEN P_VERSAO >= '005' THEN SUM(DECODE(IDAJUSTE,'E',VRBCCRED,0)) ELSE 0 END AS VRBCREDUCAO,
                        CASE WHEN P_VERSAO >= '005' THEN SUM(DECODE(IDAJUSTE,'E',VRAJUSTE,0)) ELSE 0 END AS VRREDUCAOBC,
                        CASE WHEN P_VERSAO >= '005' THEN 0 ELSE SUM(DECODE(IDAJUSTE,'E',VRAJUSTE,0)) END AS VRREDUCAO
                   FROM TMP_REGBLOCOM_PIS T, FILIAL F
                  WHERE T.CDREGISTRO   = 'M620'
                    AND T.CDFILIAL     = F.CDFILIAL(+)
                    AND T.CSTPISCOFINS IN ('49','98','99')
                    AND ((DECODE(VRALIQCRED,7.6,'01','02') = REGM610.CDCONTRI) OR
                         (DECODE(VRALIQCRED,3,'51','52')   = REGM610.CDCONTRI))
                    AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL)   = REGM610.IDCUMUPISCOFIL
                    AND T.IDTPALIQ     = REGM610.IDTPALIQ
                    AND T.VRALIQCRED   = REGM610.VRALIQCRED
                  UNION ALL
                 SELECT SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRACRESCIMOBC,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCREDUCAO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRREDUCAOBC,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRREDUCAO
                   FROM AJUSTEAPURCONTR A
                  WHERE A.NRSEQUMAPAPU    = V_NRMAPACOFINS
                    AND SUBSTR(A.IDINDICAJUSTE,1,1) = 'D'
                    AND A.IDCUMUPISCOFIL  = REGM610.IDCUMUPISCOFIL
                    AND A.CDSITUTRIBITNFE IN ('01','49','98','99')
                    AND REGM610.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','51','01')
                    AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM610.CDCONTRI))
                  UNION ALL
                 SELECT SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRACRESCIMOBC,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCREDUCAO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRREDUCAOBC,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRREDUCAO
                   FROM AJUSTEAPURCONTR A
                  WHERE A.NRSEQUMAPAPU    = V_NRMAPACOFINS
                    AND SUBSTR(A.IDINDICAJUSTE,1,1) = 'D'
                    AND A.IDCUMUPISCOFIL  = REGM610.IDCUMUPISCOFIL
                    AND A.CDSITUTRIBITNFE = '02'
                    AND REGM610.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','52','02')
                    AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM610.CDCONTRI))
                  UNION ALL
                 SELECT SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRACRESCIMOBC,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCREDUCAO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRREDUCAOBC,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRREDUCAO
                   FROM AJUSTEAPURCONTR A
                  WHERE A.NRSEQUMAPAPU    = V_NRMAPACOFINS
                    AND SUBSTR(A.IDINDICAJUSTE,1,1) = 'D'
                    AND A.IDCUMUPISCOFIL  = REGM610.IDCUMUPISCOFIL
                    AND A.CDSITUTRIBITNFE = '03'
                    AND REGM610.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','53','03')
                    AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM610.CDCONTRI))
                  UNION ALL
                 SELECT SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRACRESCIMOBC,
                        SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRACRESCIMO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBCREDUCAO,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRREDUCAOBC,
                        SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRREDUCAO
                   FROM AJUSTEAPURCONTR A
                  WHERE A.NRSEQUMAPAPU    = V_NRMAPACOFINS
                    AND SUBSTR(A.IDINDICAJUSTE,1,1) = 'D'
                    AND A.IDCUMUPISCOFIL  = REGM610.IDCUMUPISCOFIL
                    AND A.CDSITUTRIBITNFE = '05'
                    AND REGM610.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','31','32')
                    AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM610.CDCONTRI)));
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRBCAJUSTEACRES := 0;
            V_VRAJUSTEACRESBC := 0;
            V_VRAJUSTEACRES   := 0;
            V_VRBCAJUSTEREDUC := 0;
            V_VRAJUSTEREDUCBC := 0;
            V_VRAJUSTEREDUC   := 0;
      END;

      IF REGM610.IDCUMUPISCOFIL = 'N' THEN
         V_VRAJUSTECUMU := NVL(V_VRAJUSTECUMU,0) + NVL(V_VRAJUSTEACRES,0) - NVL(V_VRAJUSTEREDUC,0) + NVL(V_VRAJUSTEACRESBC,0) - NVL(V_VRAJUSTEREDUCBC,0);
      ELSE
         V_VRAJUSTENCUM := NVL(V_VRAJUSTENCUM,0) + NVL(V_VRAJUSTEACRES,0) - NVL(V_VRAJUSTEREDUC,0) + NVL(V_VRAJUSTEACRESBC,0) - NVL(V_VRAJUSTEREDUCBC,0);
      END IF;

      V_VRCONTRIBDIF    := 0;
      V_VRCONTRIBDIFANT := 0;

      FOR C_DIF IN (SELECT SUM(C.VRCONTRIBDIF) AS VRCONTRIBDIF, SUM(C.VRCONTRIBDIFANT) AS VRCONTRIBDIFANT, F.IDCUMUPISCOFIL
                      FROM CONTRIBDIFERIDA C, NOTAFISCAL N, FILIAL F
                     WHERE C.NRSEQMAPADIF  = V_NRMAPACOFINS
                       AND C.CDFILIAL      = N.CDFILIAL
                       AND C.NRLANCTONF    = N.NRLANCTONF
                       AND N.CDFILIEMIT    = F.CDFILIAL
                       AND C.CDCONTRIBAPUR = REGM610.CDCONTRI
                     GROUP BY F.IDCUMUPISCOFIL) LOOP

         V_VRCONTRIBDIF    := NVL(V_VRCONTRIBDIF,   0) + C_DIF.VRCONTRIBDIF;
         V_VRCONTRIBDIFANT := NVL(V_VRCONTRIBDIFANT,0) + C_DIF.VRCONTRIBDIFANT;

         IF C_DIF.IDCUMUPISCOFIL = 'N' THEN
            V_VRDIFERIMENTOCUMU := NVL(V_VRDIFERIMENTOCUMU,0) - NVL(C_DIF.VRCONTRIBDIF,0) + NVL(C_DIF.VRCONTRIBDIFANT,0);
         ELSE
            V_VRDIFERIMENTONCUM := NVL(V_VRDIFERIMENTONCUM,0) - NVL(C_DIF.VRCONTRIBDIF,0) + NVL(C_DIF.VRCONTRIBDIFANT,0);
         END IF;
      END LOOP;

      V_REGM610 := REGM610.REG      ||'|'||
                   REGM610.COD_CONT ||'|'||
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM610.VL_REC_BRT,0),'999999999990.00')),'.',',')        ||'|'||
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM610.VL_BC_CONT,0),'999999999990.00')),'.',',')        ||
                   CASE WHEN P_VERSAO >= '005' THEN
                      '|'||REPLACE(LTRIM(TO_CHAR(NVL(V_VRBCAJUSTEACRES,0),'999999999990.00')),'.',',') ||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(V_VRBCAJUSTEREDUC,0),'999999999990.00')),'.',',')      ||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(REGM610.VL_BC_CONT,0) + NVL(V_VRBCAJUSTEACRES,0) - NVL(V_VRBCAJUSTEREDUC,0),'999999999990.00')),'.',',')
                   ELSE '' END                                                                         ||'|'||
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM610.ALIQ_COFINS,''),'990.0000')),'.',',')             ||'|'||
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM610.QUANT_BC_COFINS,''),'999999999990.000')),'.',',') ||'|'||/*BC POR QUANTIDADE*/
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM610.ALIQ_COFINS_QUANT,''),'990.0000')),'.',',')       ||'|'||/*ALIQUOTA POR QUANTIDADE*/
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM610.VL_CONT_APUR,0) + NVL(V_VRAJUSTEACRESBC,0) - NVL(V_VRAJUSTEREDUCBC,0),'999999999990.00')),'.',',')      ||'|'||
                   REPLACE(LTRIM(TO_CHAR(NVL(V_VRAJUSTEACRES,0),'999999999990.00')),'.',',')           ||'|'||/*AJUSTE A ACRESCIMO*/
                   REPLACE(LTRIM(TO_CHAR(NVL(V_VRAJUSTEREDUC,0),'999999999990.00')),'.',',')           ||'|'||/*AJUSTE A REDUÇÃO*/
                   REPLACE(LTRIM(TO_CHAR(NVL(V_VRCONTRIBDIF,0),'999999999990.00')),'.',',')            ||'|'||/*VALOR CONTRI. A DIFERIR*/
                   REPLACE(LTRIM(TO_CHAR(NVL(V_VRCONTRIBDIFANT,0),'999999999990.00')),'.',',')         ||'|'||/*VALOR CONTRI. DIFERIDA PER. ANT*/
                   REPLACE(LTRIM(TO_CHAR(NVL(REGM610.VRCONTRIBUICAO,0)+NVL(V_VRAJUSTEACRESBC,0)-NVL(V_VRAJUSTEREDUCBC,0)+NVL(V_VRAJUSTEACRES,0)-NVL(V_VRAJUSTEREDUC,0)-NVL(V_VRCONTRIBDIF,0)+NVL(V_VRCONTRIBDIFANT,0),'999999999990.00')),'.',',') ||'|';

      V_CONTREGA:= NVL(V_CONTREGA,0)+1;
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'662'||LPAD(RTRIM(V_CONTREGA),22,'0'),V_REGM610);

      IF P_VERSAO >= '005' THEN
         /*REGISTRO M615 - */
         FOR REG_M615 IN (SELECT '|M615'                                                            ||'|'||
                                 IND_AJ_BC                                                          ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(NVL(VL_AJ_BC,0),'999999999990.00')),'.',',') ||'|'||
                                 COD_AJ_BC                                                          ||'|'||
                                 NUM_DOC                                                            ||'|'||
                                 DESCR_AJ_BC                                                        ||'|'||
                                 TO_CHAR(DT_REF,'DDMMYYYY')                                         ||'|'||
                                 COD_CTA                                                            ||'|'||
                                 CNPJ                                                               ||'|'||
                                 INFO_COMPL                                                         ||'|' AS REGM615,
                                 CNPJ, COD_CTA
                            FROM (SELECT DECODE(T.IDAJUSTE,'S','1','0') AS IND_AJ_BC,
                                         NVL(T.VRBCCRED,0) AS VL_AJ_BC,
                                         '02' AS COD_AJ_BC,
                                         N.NRNOTAFISC AS NUM_DOC,
                                         'NF de Devolução: '|| N.NRNOTAFISC || ' - ' || N.NRINSJURNF AS DESCR_AJ_BC,
                                         DECODE(N.IDENTRSAIDOP,'E',N.DTENTRSAID,N.DTEMISSAO) AS DT_REF,
                                         MAX(CONTCTBL_SPED(N.IDENTRSAIDOP, IT.CDPRODUTO, N.CDTIPOOPER, DECODE(N.IDENTRSAIDOP,'E',N.CDFILIRECE,N.CDFILIEMIT))) AS COD_CTA,
                                         REPLACE(REPLACE(REPLACE(IE.NRINSJURIEST,'/'),'.'),'-') AS CNPJ,
                                         '' AS INFO_COMPL,
                                         T.CHAVENOTA
                                    FROM TMP_REGBLOCOM_PIS T, FILIAL F, NOTAFISCAL N, ITEMPRODUTO IT, INSCRESTAD IE
                                   WHERE T.CDREGISTRO   = 'M620'
                                     AND T.CDFILIAL     = F.CDFILIAL(+)
                                     AND T.CSTPISCOFINS IN ('49','98','99')
                                     AND ((DECODE(VRALIQCRED,7.6,'01','02') = REGM610.CDCONTRI) OR
                                          (DECODE(VRALIQCRED,3,'51','52') = REGM610.CDCONTRI))
                                     AND NVL(F.IDCUMUPISCOFIL,T.CDFILIAL)  = REGM610.IDCUMUPISCOFIL
                                     AND T.IDTPALIQ     = REGM610.IDTPALIQ
                                     AND T.VRALIQCRED   = REGM610.VRALIQCRED
                                     AND N.CDFILIAL     = SUBSTR(T.CHAVENOTA,1,4)
                                     AND N.NRLANCTONF   = SUBSTR(T.CHAVENOTA,5,10)
                                     AND N.CDFILIAL     = IT.CDFILIAL
                                     AND N.NRLANCTONF   = IT.NRLANCTONF
                                     AND N.CDINSCESTA   = IE.CDINSCESTA
                                     AND N.CDEMPRESA    = IE.CDEMPRESA
                                     AND P_VERSAO       >= '005'
                                   GROUP BY T.IDAJUSTE, T.VRBCCRED, N.NRNOTAFISC, N.NRINSJURNF, N.IDENTRSAIDOP,
                                         N.DTENTRSAID, N.DTEMISSAO, IE.NRINSJURIEST, T.CHAVENOTA
                                   UNION ALL
                                   SELECT A.IDTPAJUSTE AS IND_AJ_BC,
                                         NVL(A.VRBASECALCAJ,0) AS VL_AJ_BC,
                                         A.CDAJUSTEBC AS COD_AJ_BC,
                                         A.NRPROCESSO AS NUM_DOC,
                                         A.DSAJUSTE AS DESCR_AJ_BC,
                                         NVL(A.DTAJUSTE,P_DTFINAL) AS DT_REF,
                                         A.CDCONTCTBL AS COD_CTA,
                                         REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'/'),'.'),'-') AS CNPJ,
                                         '' AS INFO_COMPL,
                                         A.NRSEQAJUSTE AS CHAVENOTA
                                    FROM AJUSTEAPURCONTR A, FILIAL F, INSCRESTAD I
                                   WHERE A.NRSEQUMAPAPU    = V_NRMAPACOFINS
                                     AND A.IDINDICAJUSTE   = 'DB'
                                     AND A.IDCUMUPISCOFIL  = REGM610.IDCUMUPISCOFIL
                                     AND A.CDSITUTRIBITNFE IN ('01','49','98','99')
                                     AND REGM610.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','51','01')
                                     AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM610.CDCONTRI))
                                     AND A.CDFILIAL        = F.CDFILIAL
                                     AND F.CDEMPRESA       = I.CDEMPRESA
                                     AND F.CDINSCESTA      = I.CDINSCESTA
                                   UNION ALL
                                  SELECT A.IDTPAJUSTE AS IND_AJ_BC,
                                         NVL(A.VRBASECALCAJ,0) AS VL_AJ_BC,
                                         A.CDAJUSTEBC AS COD_AJ_BC,
                                         A.NRPROCESSO AS NUM_DOC,
                                         A.DSAJUSTE AS DESCR_AJ_BC,
                                         NVL(A.DTAJUSTE,P_DTFINAL) AS DT_REF,
                                         A.CDCONTCTBL AS COD_CTA,
                                         REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'/'),'.'),'-') AS CNPJ,
                                         '' AS INFO_COMPL,
                                         A.NRSEQAJUSTE AS CHAVENOTA
                                    FROM AJUSTEAPURCONTR A, FILIAL F, INSCRESTAD I
                                   WHERE A.NRSEQUMAPAPU    = V_NRMAPACOFINS
                                     AND A.IDINDICAJUSTE   = 'DB'
                                     AND A.IDCUMUPISCOFIL  = REGM610.IDCUMUPISCOFIL
                                     AND A.CDSITUTRIBITNFE = '02'
                                     AND REGM610.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','52','02')
                                     AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM610.CDCONTRI))
                                     AND A.CDFILIAL        = F.CDFILIAL
                                     AND F.CDEMPRESA       = I.CDEMPRESA
                                     AND F.CDINSCESTA      = I.CDINSCESTA
                                   UNION ALL
                                  SELECT A.IDTPAJUSTE AS IND_AJ_BC,
                                         NVL(A.VRBASECALCAJ,0) AS VL_AJ_BC,
                                         A.CDAJUSTEBC AS COD_AJ_BC,
                                         A.NRPROCESSO AS NUM_DOC,
                                         A.DSAJUSTE AS DESCR_AJ_BC,
                                         NVL(A.DTAJUSTE,P_DTFINAL) AS DT_REF,
                                         A.CDCONTCTBL AS COD_CTA,
                                         REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'/'),'.'),'-') AS CNPJ,
                                         '' AS INFO_COMPL,
                                         A.NRSEQAJUSTE AS CHAVENOTA
                                    FROM AJUSTEAPURCONTR A, FILIAL F, INSCRESTAD I
                                   WHERE A.NRSEQUMAPAPU    = V_NRMAPACOFINS
                                     AND A.IDINDICAJUSTE   = 'DB'
                                     AND A.IDCUMUPISCOFIL  = REGM610.IDCUMUPISCOFIL
                                     AND A.CDSITUTRIBITNFE = '03'
                                     AND REGM610.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','53','03')
                                     AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM610.CDCONTRI))
                                     AND A.CDFILIAL        = F.CDFILIAL
                                     AND F.CDEMPRESA       = I.CDEMPRESA
                                     AND F.CDINSCESTA      = I.CDINSCESTA
                                   UNION ALL
                                  SELECT A.IDTPAJUSTE AS IND_AJ_BC,
                                         NVL(A.VRBASECALCAJ,0) AS VL_AJ_BC,
                                         A.CDAJUSTEBC AS COD_AJ_BC,
                                         A.NRPROCESSO AS NUM_DOC,
                                         A.DSAJUSTE AS DESCR_AJ_BC,
                                         NVL(A.DTAJUSTE,P_DTFINAL) AS DT_REF,
                                         A.CDCONTCTBL AS COD_CTA,
                                         REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'/'),'.'),'-') AS CNPJ,
                                         '' AS INFO_COMPL,
                                         A.NRSEQAJUSTE AS CHAVENOTA
                                    FROM AJUSTEAPURCONTR A, FILIAL F, INSCRESTAD I
                                   WHERE A.NRSEQUMAPAPU    = V_NRMAPACOFINS
                                     AND A.IDINDICAJUSTE   = 'DB'
                                     AND A.IDCUMUPISCOFIL  = REGM610.IDCUMUPISCOFIL
                                     AND A.CDSITUTRIBITNFE = '05'
                                     AND REGM610.CDCONTRI  = DECODE(A.IDCUMUPISCOFIL,'N','31','32')
                                     AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM610.CDCONTRI))
                                     AND A.CDFILIAL        = F.CDFILIAL
                                     AND F.CDEMPRESA       = I.CDEMPRESA
                                     AND F.CDINSCESTA      = I.CDINSCESTA)) LOOP
            V_CONTREGA := NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'662'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M615.REGM615);

            /*VERIFICA SE O ESTABELECIMENTO JÁ FOI INSERIDO ANTERIORMENTE*/
            V_NRINSJUR := NULL;

            SELECT MAX(CDCHAVEREG) AS CNPJ
              INTO V_NRINSJUR
              FROM TMP_REGDADOSSPED_PIS
             WHERE CDREGISTRO = '0140'
               AND CDCHAVEREG = REG_M615.CNPJ;

            IF V_NRINSJUR IS NULL THEN
               V_CONTEST  := NVL(V_CONTEST,0)+1;
               V_REG      := NULL;
               BEGIN
                  SELECT '|0140'             ||'|'||
                         LTRIM(TO_CHAR(V_CONTEST,'000')) ||'|'||
                         MAX(E.NMRAZSOCEMPR) ||'|'||
                         REPLACE(REPLACE(REPLACE(REPLACE(MAX(IE.NRINSJURIEST),'.',''),'/',''),'-',''),'\','') ||'|'||
                         MAX(IE.SGESTADO)    ||'|'||
                         ''                  ||'|'||
                         MAX(M.CDMUNICIBGE)  ||'|'||
                         ''                  ||'|'||
                         ''                  ||'|'
                    INTO V_REG
                    FROM INSCRESTAD IE, MUNICIPIO M, EMPRESA E
                   WHERE IE.NRINSJURIEST = REG_M615.CNPJ
                     AND IE.CDPAIS       = M.CDPAIS
                     AND IE.SGESTADO     = M.SGESTADO
                     AND IE.CDMUNICIPIO  = M.CDMUNICIPIO
                     AND IE.CDEMPRESA    = P_CDEMPRESA
                     AND E.CDEMPRESA     = IE.CDEMPRESA
                   GROUP BY '0140';
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_REG:= NULL;
               END;

               V_COUNTBCL0:= NVL(V_COUNTBCL0,0)+1;
               INSERT INTO ARQMAGPISCOFINS
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
               VALUES
                  (P_NRSEQARQMAG,'104'||LTRIM(TO_CHAR(V_CONTEST,'000')),NVL(V_REG,'VAZIO'));

               V_SEQUPROD := NVL(V_SEQUPROD,0)+1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
                VALUES
                 ('0140', V_SEQUPROD, REG_M615.CNPJ ,NULL, LTRIM(TO_CHAR(V_CONTEST,'000')));
            END IF;

            /* CODIGO DA CONTA CONTÁBIL */
            BEGIN
               SELECT MAX(CDCHAVEREG)
                 INTO V_COD_CC
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = REG_M615.COD_CTA
                  AND CDREGISTRO = '0500';
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_COD_CC := NULL;
            END;

            IF (V_COD_CC IS NULL) AND (REG_M615.COD_CTA IS NOT NULL) THEN
               V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
               VALUES
                  ('0500', V_SEQCCTBL, REG_M615.COD_CTA, NULL);
            END IF;
         END LOOP;
      END IF;

      /*REGISTRO M620 - REGISTRO DE AJUSTES*/
      FOR REG_M620 IN (SELECT '|M620'                                                                 ||'|'||
                              IDAJUSTE                                                                ||'|'||
                              REPLACE(LTRIM(TO_CHAR(SUM(NVL(VRAJUSTE,0)),'999999999990.00')),'.',',') ||'|'||
                              CDAJUSTE                                                                ||'|'||
                              NUMDOC                                                                  ||'|'||
                              DSAJUSTE                                                                ||'|'||
                              TO_CHAR(DTAJUSTE,'DDMMYYYY')                                            ||'|' AS REGM620
                              /*DEVOLUÇÕES VENDA(ENTRADAS) REDUZEM - DEVOLUÇÕES COMPRA(SAÍDAS) ACRESCEM*/
                         FROM (SELECT DECODE(R.IDAJUSTE,'S','1','0') AS IDAJUSTE, R.VRAJUSTE, R.CDAJUSTE,
                                     N.NRNOTAFISC AS NUMDOC, T.NMTIPOOPER||' - '||N.NRINSJURNF AS DSAJUSTE,
                                     DECODE(N.IDENTRSAIDOP,'E',N.DTENTRSAID,N.DTEMISSAO) AS DTAJUSTE
                                FROM TMP_REGBLOCOM_PIS R, FILIAL F, NOTAFISCAL N, TIPOOPERAC T
                               WHERE R.CDREGISTRO     = 'M620'
                                 AND R.CSTPISCOFINS   IN ('49','98','99')
                                 AND R.CDFILIAL       = F.CDFILIAL
                                 AND F.IDCUMUPISCOFIL = REGM610.IDCUMUPISCOFIL
                                 AND REGM610.CDCONTRI IN ('01','02','51','52')
                                 AND N.CDFILIAL       = SUBSTR(R.CHAVENOTA,1,4)
                                 AND N.NRLANCTONF     = SUBSTR(R.CHAVENOTA,5,10)
                                 AND N.CDTIPOOPER     = T.CDTIPOOPER
                                 AND N.IDENTRSAIDOP   = T.IDENTRSAIDOP
                                 AND R.IDTPALIQ       = REGM610.IDTPALIQ
                                 AND R.VRALIQCRED     = REGM610.VRALIQCRED
                                 AND P_VERSAO         < '005'
                                 AND ((DECODE(VRALIQCRED,7.6,'01','02') = REGM610.CDCONTRI) OR
                                      (DECODE(VRALIQCRED,3,'51','52')   = REGM610.CDCONTRI))
                               UNION ALL
                              SELECT A.IDTPAJUSTE AS IDAJUSTE, A.VRAJUSTE, A.CDAJUSTE,
                                     A.NRPROCESSO AS NUMDOC, A.DSAJUSTE, A.DTAJUSTE
                                FROM AJUSTEAPURCONTR A
                               WHERE A.NRSEQUMAPAPU   = V_NRMAPACOFINS
                                 AND A.IDINDICAJUSTE  = 'DI'
                                 AND A.IDCUMUPISCOFIL = REGM610.IDCUMUPISCOFIL
                                 AND DECODE(A.CDSITUTRIBITNFE,'05',DECODE(A.IDCUMUPISCOFIL,'N','31','32'),
                                                              '03',DECODE(A.IDCUMUPISCOFIL,'N','53','03'),
                                                              '02',DECODE(A.IDCUMUPISCOFIL,'N','52','02'),
                                                              DECODE(A.IDCUMUPISCOFIL,'N','51','01')) = REGM610.CDCONTRI
                                 AND A.CDSITUTRIBITNFE IN ('01','02','03','05','49','98','99')
                                 AND ((V_CDCONTRIB IS NULL) OR (V_CDCONTRIB <> REGM610.CDCONTRI)))
                        GROUP BY IDAJUSTE, CDAJUSTE, NUMDOC, DSAJUSTE, DTAJUSTE ) LOOP

          V_CONTREGA:= NVL(V_CONTREGA,0)+1;
          INSERT INTO ARQMAGPISCOFINS
             (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
          VALUES
             (P_NRSEQARQMAG,'662'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M620.REGM620);
      END LOOP;

      /*REGISTRO M630: INFORMAÇÕES ADICIONAIS DE DIFERIMENTO*/
      FOR REG_M630 IN (SELECT '|M630'                                                                     ||'|'||
                              REPLACE(REPLACE(REPLACE(CNPJ,'.'),'/'),'-')                                 ||'|'||
                              REPLACE(LTRIM(TO_CHAR(SUM(NVL(VL_VEND,0)),'999999999990.00')),'.',',')      ||'|'||
                              REPLACE(LTRIM(TO_CHAR(SUM(NVL(VL_NAO_RECEB,0)),'999999999990.00')),'.',',') ||'|'||
                              REPLACE(LTRIM(TO_CHAR(SUM(NVL(VL_CONT_DIF,0)),'999999999990.00')),'.',',')  ||'|'||
                              REPLACE(LTRIM(TO_CHAR(SUM(NVL(VL_CRED_DIF,0)),'999999999990.00')),'.',',')  ||'|'||
                              CDTPCREDITO  ||'|' AS REGM630
                         FROM (SELECT CL.NRINSJURCLIE AS CNPJ,
                                      CD.VRCONTABIL AS VL_VEND, CD.VRCONTNAOREC AS VL_NAO_RECEB,
                                      SUM(NVL(CC.VRCONTRIBDIF,CD.VRCONTRIBDIF)) AS VL_CONT_DIF,
                                      SUM(NVL(CC.VRCREDDIFERIDO,CD.VRCREDDIFERIDO)) AS VL_CRED_DIF,
                                      CC.CDTPCREDITO, CD.NRSEQCONTRDIF
                                 FROM CONTRIBDIFERIDA CD, CLIENTE CL, NOTAFISCAL NF, FILIAL FL,
                                      (SELECT SUM(VRCREDDIFERIDO) AS VRCREDDIFERIDO, SUM(VRCONTRIBDIF) AS  VRCONTRIBDIF,
                                              CDTPCREDITO, NRSEQCONTRDIF
                                         FROM CONTROLCREDDIF
                                        WHERE NRSEQMAPADIF = V_NRMAPACOFINS
                                        GROUP BY CDTPCREDITO, NRSEQCONTRDIF) CC
                                WHERE CD.NRSEQMAPADIF  = V_NRMAPACOFINS
                                  AND CD.CDFILIAL      = NF.CDFILIAL
                                  AND CD.NRLANCTONF    = NF.NRLANCTONF
                                  AND NF.CDFILIEMIT    = FL.CDFILIAL
                                  AND CD.CDCONTRIBAPUR = REGM610.CDCONTRI
                                  AND CD.CDCLIENTE     = CL.CDCLIENTE
                                  AND CD.NRSEQCONTRDIF = CC.NRSEQCONTRDIF(+)
                                GROUP BY CL.NRINSJURCLIE, CD.VRCONTABIL, CD.VRCONTNAOREC, CC.VRCREDDIFERIDO, CC.CDTPCREDITO, CD.NRSEQCONTRDIF)
                         GROUP BY CNPJ, CDTPCREDITO)LOOP

          V_CONTREGA:= NVL(V_CONTREGA,0)+1;
          INSERT INTO ARQMAGPISCOFINS
             (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
          VALUES
             (P_NRSEQARQMAG,'662'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M630.REGM630);
      END LOOP;

      V_CDCONTRIB := REGM610.CDCONTRI;
   END LOOP;

   /*GERA OS REGISTROS M610 E M620 PARA ITENS DE AJUSTES QUE POSSUEM CST PARA O QUAL NÃO EXISTEM NOTAS NO PERÍODO*/
   FOR REG_M610A IN (SELECT DECODE(A.CDSITUTRIBITNFE,'05',DECODE(A.IDCUMUPISCOFIL,'N','31','32'),
                                                     '03',DECODE(A.IDCUMUPISCOFIL,'N','53','03'),
                                                     '02',DECODE(A.IDCUMUPISCOFIL,'N','52','02'),
                                                          DECODE(A.IDCUMUPISCOFIL,'N','51','01')) AS CDCONTRI,
                            SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBASECALCAJREDUC,
                            SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRAJUSTEREDUCBC,
                            SUM(DECODE(IDTPAJUSTE,'0',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRAJUSTEREDUC,
                            SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRBASECALCAJ,0),0)) AS VRBASECALCAJACRES,
                            SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DB',VRAJUSTE,0),0)) AS VRAJUSTEACRESBC,
                            SUM(DECODE(IDTPAJUSTE,'1',DECODE(IDINDICAJUSTE,'DI',VRAJUSTE,0),0)) AS VRAJUSTEACRES,
                            A.IDCUMUPISCOFIL
                       FROM AJUSTEAPURCONTR A
                      WHERE A.NRSEQUMAPAPU   = V_NRMAPACOFINS
                        AND SUBSTR(A.IDINDICAJUSTE,1,1) = 'D'
                        AND A.CDSITUTRIBITNFE IN ('01','02','03','05','49','98','99')
                        AND DECODE(A.CDSITUTRIBITNFE,'05',DECODE(A.IDCUMUPISCOFIL,'N','31','32'),
                                                     '03',DECODE(A.IDCUMUPISCOFIL,'N','53','03'),
                                                     '02',DECODE(A.IDCUMUPISCOFIL,'N','52','02'),
                                                          DECODE(A.IDCUMUPISCOFIL,'N','51','01')) NOT IN (SELECT DECODE(T.CSTPISCOFINS,'05',DECODE(F.IDCUMUPISCOFIL,'N','31','32'),
                                                                                                                                       '03',DECODE(F.IDCUMUPISCOFIL,'N','53','03'),
                                                                                                                                       '02',DECODE(F.IDCUMUPISCOFIL,'N','52','02'),
                                                                                                                                            DECODE(F.IDCUMUPISCOFIL,'N','51','01'))  AS COD_CONTR
                                                                                                            FROM TMP_REGBLOCOM_PIS T, FILIAL F
                                                                                                           WHERE T.CDREGISTRO IN ('M600','M620')
                                                                                                             AND T.CDFILIAL   = F.CDFILIAL(+))
                      GROUP BY DECODE(A.CDSITUTRIBITNFE,'05',DECODE(A.IDCUMUPISCOFIL,'N','31','32'),
                                                        '03',DECODE(A.IDCUMUPISCOFIL,'N','53','03'),
                                                        '02',DECODE(A.IDCUMUPISCOFIL,'N','52','02'),
                                                             DECODE(A.IDCUMUPISCOFIL,'N','51','01')), A.IDCUMUPISCOFIL) LOOP

      IF NVL(REG_M610A.VRAJUSTEACRES,0) - NVL(REG_M610A.VRAJUSTEREDUC,0) + NVL(REG_M610A.VRAJUSTEACRESBC,0) - NVL(REG_M610A.VRAJUSTEREDUCBC,0) > 0 THEN

         IF REG_M610A.IDCUMUPISCOFIL = 'N' THEN
            V_VRAJUSTECUMU := NVL(V_VRAJUSTECUMU,0) + NVL(REG_M610A.VRAJUSTEACRES,0) - NVL(REG_M610A.VRAJUSTEREDUC,0) + NVL(REG_M610A.VRAJUSTEACRESBC,0) - NVL(REG_M610A.VRAJUSTEREDUCBC,0);
         ELSE
            V_VRAJUSTENCUM := NVL(V_VRAJUSTENCUM,0) + NVL(REG_M610A.VRAJUSTEACRES,0) - NVL(REG_M610A.VRAJUSTEREDUC,0) + NVL(REG_M610A.VRAJUSTEACRESBC,0) - NVL(REG_M610A.VRAJUSTEREDUCBC,0);
         END IF;

         V_REGM610 := '|M610'            ||'|'||
                      REG_M610A.CDCONTRI ||'|'||
                      '0,00'             ||'|'||
                      '0,00'             ||
                      CASE WHEN P_VERSAO >= '005' THEN
                         '|'||REPLACE(LTRIM(TO_CHAR(NVL(REG_M610A.VRBASECALCAJACRES,0),'999999999990.00')),'.',',')||'|'||
                         REPLACE(LTRIM(TO_CHAR(NVL(REG_M610A.VRBASECALCAJREDUC,0),'999999999990.00')),'.',',')     ||'|'||
                         REPLACE(LTRIM(TO_CHAR(NVL(REG_M610A.VRBASECALCAJACRES,0) - NVL(REG_M610A.VRBASECALCAJREDUC,0),'999999999990.00')),'.',',')
                      ELSE '' END        ||'|'||
                      ''                 ||'|'||
                      ''                 ||'|'||
                      ''                 ||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(REG_M610A.VRAJUSTEACRESBC,0)-NVL(REG_M610A.VRAJUSTEREDUCBC,0),'999999999990.00')),'.',',') ||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(REG_M610A.VRAJUSTEACRES,0),'999999999990.00')),'.',',') ||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(REG_M610A.VRAJUSTEREDUC,0),'999999999990.00')),'.',',') ||'|'||
                      ''                 ||'|'||
                      ''                 ||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(REG_M610A.VRAJUSTEACRES,0)-NVL(REG_M610A.VRAJUSTEREDUC,0)+NVL(REG_M610A.VRAJUSTEACRESBC,0)-NVL(REG_M610A.VRAJUSTEREDUCBC,0),'999999999990.00')),'.',',')||'|';

         V_CONTREGA := NVL(V_CONTREGA,0)+1;
         INSERT INTO ARQMAGPISCOFINS
            (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
            (P_NRSEQARQMAG,'662'||LPAD(RTRIM(V_CONTREGA),22,'0'),V_REGM610);

         IF P_VERSAO >= '005' THEN
            FOR REG_M615A IN (SELECT '|M615'                                                                  ||'|'||
                                     A.IDTPAJUSTE                                                             ||'|'||
                                     REPLACE(LTRIM(TO_CHAR(NVL(A.VRBASECALCAJ,0),'999999999990.00')),'.',',') ||'|'||
                                     A.CDAJUSTEBC                                                             ||'|'||
                                     A.NRPROCESSO                                                             ||'|'||
                                     A.DSAJUSTE                                                               ||'|'||
                                     TO_CHAR(NVL(A.DTAJUSTE,P_DTFINAL),'DDMMYYYY')                            ||'|'||
                                     A.CDCONTCTBL                                                             ||'|'||
                                     REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'/'),'.'),'-')                    ||'|'||
                                     ''                                                                       ||'|' AS REGM615,
                                     REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'/'),'.'),'-') AS CNPJ, A.CDCONTCTBL AS COD_CTA
                                FROM AJUSTEAPURCONTR A, FILIAL F, INSCRESTAD I
                               WHERE A.NRSEQUMAPAPU    = V_NRMAPACOFINS
                                 AND A.IDINDICAJUSTE   = 'DB'
                                 AND A.CDSITUTRIBITNFE IN ('01','02','03','05','49','98','99')
                                 AND A.IDCUMUPISCOFIL  = REG_M610A.IDCUMUPISCOFIL
                                 AND DECODE(A.CDSITUTRIBITNFE,'05',DECODE(A.IDCUMUPISCOFIL,'N','31','32'),
                                                              '03',DECODE(A.IDCUMUPISCOFIL,'N','53','03'),
                                                              '02',DECODE(A.IDCUMUPISCOFIL,'N','52','02'),
                                                                   DECODE(A.IDCUMUPISCOFIL,'N','51','01')) = REG_M610A.CDCONTRI
                                 AND A.CDFILIAL        = F.CDFILIAL
                                 AND F.CDEMPRESA       = I.CDEMPRESA
                                 AND F.CDINSCESTA      = I.CDINSCESTA) LOOP

                V_CONTREGA := NVL(V_CONTREGA,0)+1;
               INSERT INTO ARQMAGPISCOFINS
                  (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
               VALUES
                  (P_NRSEQARQMAG,'662'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M615A.REGM615);

               /*VERIFICA SE O ESTABELECIMENTO JÁ FOI INSERIDO ANTERIORMENTE*/
               V_NRINSJUR := NULL;

               SELECT MAX(CDCHAVEREG) AS CNPJ
                 INTO V_NRINSJUR
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDREGISTRO = '0140'
                  AND CDCHAVEREG = REG_M615A.CNPJ;

               IF V_NRINSJUR IS NULL THEN
                  V_CONTEST  := NVL(V_CONTEST,0)+1;
                  V_REG      := NULL;
                  BEGIN
                     SELECT '|0140'             ||'|'||
                            LTRIM(TO_CHAR(V_CONTEST,'000')) ||'|'||
                            MAX(E.NMRAZSOCEMPR) ||'|'||
                            REPLACE(REPLACE(REPLACE(REPLACE(MAX(IE.NRINSJURIEST),'.',''),'/',''),'-',''),'\','') ||'|'||
                            MAX(IE.SGESTADO)    ||'|'||
                            ''                  ||'|'||
                            MAX(M.CDMUNICIBGE)  ||'|'||
                            ''                  ||'|'||
                            ''                  ||'|'
                       INTO V_REG
                       FROM INSCRESTAD IE, MUNICIPIO M, EMPRESA E
                      WHERE IE.NRINSJURIEST = REG_M615A.CNPJ
                        AND IE.CDPAIS       = M.CDPAIS
                        AND IE.SGESTADO     = M.SGESTADO
                        AND IE.CDMUNICIPIO  = M.CDMUNICIPIO
                        AND IE.CDEMPRESA    = P_CDEMPRESA
                        AND E.CDEMPRESA     = IE.CDEMPRESA
                      GROUP BY '0140';
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_REG:= NULL;
                  END;

                  V_COUNTBCL0:= NVL(V_COUNTBCL0,0)+1;
                  INSERT INTO ARQMAGPISCOFINS
                     (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
                  VALUES
                     (P_NRSEQARQMAG,'104'||LTRIM(TO_CHAR(V_CONTEST,'000')),NVL(V_REG,'VAZIO'));

                  V_SEQUPROD := NVL(V_SEQUPROD,0)+1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                    (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
                   VALUES
                    ('0140', V_SEQUPROD, REG_M615A.CNPJ ,NULL, LTRIM(TO_CHAR(V_CONTEST,'000')));
               END IF;

               /* CODIGO DA CONTA CONTÁBIL */
               BEGIN
                  SELECT MAX(CDCHAVEREG)
                    INTO V_COD_CC
                    FROM TMP_REGDADOSSPED_PIS
                   WHERE CDCHAVEREG = REG_M615A.COD_CTA
                     AND CDREGISTRO = '0500';
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_COD_CC := NULL;
               END;

               IF (V_COD_CC IS NULL) AND (REG_M615A.COD_CTA IS NOT NULL) THEN
                  V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
                  VALUES
                     ('0500', V_SEQCCTBL, REG_M615A.COD_CTA, NULL);
               END IF;
            END LOOP;
         END IF;

         FOR REG_M620A IN (SELECT '|M620'                                                                 ||'|'||
                                  IDTPAJUSTE                                                              ||'|'||
                                  REPLACE(LTRIM(TO_CHAR(SUM(NVL(VRAJUSTE,0)),'999999999990.00')),'.',',') ||'|'||
                                  CDAJUSTE                                                                ||'|'||
                                  NRPROCESSO                                                              ||'|'||
                                  DSAJUSTE                                                                ||'|'||
                                  TO_CHAR(DTAJUSTE,'DDMMYYYY')                                            ||'|' AS REGM620
                             FROM AJUSTEAPURCONTR A
                            WHERE A.NRSEQUMAPAPU    = V_NRMAPACOFINS
                              AND A.IDINDICAJUSTE   = 'DI'
                              AND A.CDSITUTRIBITNFE IN ('01','02','03','05','49','98','99')
                              AND A.IDCUMUPISCOFIL  = REG_M610A.IDCUMUPISCOFIL
                              AND DECODE(A.CDSITUTRIBITNFE,'05',DECODE(A.IDCUMUPISCOFIL,'N','31','32'),
                                                           '03',DECODE(A.IDCUMUPISCOFIL,'N','53','03'),
                                                           '02',DECODE(A.IDCUMUPISCOFIL,'N','52','02'),
                                                                DECODE(A.IDCUMUPISCOFIL,'N','51','01')) = REG_M610A.CDCONTRI
                            GROUP BY IDTPAJUSTE, CDAJUSTE, NRPROCESSO, DSAJUSTE, DTAJUSTE) LOOP

            V_CONTREGA:= NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'662'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M620A.REGM620);
         END LOOP;
      END IF;
   END LOOP;

   /*BUSCA O CRÉDITO ANTERIOR UTILIZADO NO PERÍODO*/
   V_CREDANTERIOR := 0;
   BEGIN
      SELECT NVL(SUM(VRSALDOCREDORUT),0)
        INTO V_CREDANTERIOR
        FROM CREDANTSPED C
       WHERE C.NRSEQUMAPAPU  <> V_NRMAPACOFINS
         AND C.CDEMPRESA     = P_CDEMPRESA
         AND C.DTUTILIZACRED = P_DTINICIAL
         AND C.IDTPCREDANT   = 'CA'
         AND C.CDREGISTRO    = '1500';
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_CREDANTERIOR := 0;
   END;

   /*BUSCA O VALOR DO IMPOSTO RETIDO UTILIZADO NO PERÍODO*/
   V_IMPRETIDONCUM := 0;
   V_IMPRETIDOCUM  := 0;
   BEGIN
      SELECT NVL(SUM(DECODE(IDCUMUPISCOFIL,'S',VRSALDOCREDORUT,0)),0),
             NVL(SUM(DECODE(IDCUMUPISCOFIL,'N',VRSALDOCREDORUT,0)),0)
        INTO V_IMPRETIDONCUM, V_IMPRETIDOCUM
        FROM CREDANTSPED C
       WHERE C.DTUTILIZACRED = P_DTINICIAL
         AND C.CDEMPRESA     = P_CDEMPRESA
         AND C.IDTPCREDANT   = 'CO'
         AND C.CDREGISTRO    = '1700';
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IMPRETIDONCUM := 0;
         V_IMPRETIDOCUM  := 0;
   END;

   /*BUSCA O VALOR DAS DEDUÇÕES CUMULATIVO E NÃO CUMULATIVO NO PERÍODO*/
   V_VRDEDUCAONCUM := 0;
   V_VRDEDUCAOCUMU := 0;
   BEGIN
      SELECT NVL(SUM(DECODE(I.IDCUMUPISCOFIL,'S',I.VRITEMDETAPU,0)),0) AS VRDEDUCAONCUM,
             NVL(SUM(DECODE(I.IDCUMUPISCOFIL,'N',I.VRITEMDETAPU,0)),0) AS VRDEDUCAOCUMU
        INTO V_VRDEDUCAONCUM, V_VRDEDUCAOCUMU
        FROM ITDETAPUCONTR I
       WHERE I.NRSEQUMAPAPU = V_NRMAPACOFINS
         AND I.IDTIPODETAPU = 'DD'
       GROUP BY I.IDCUMUPISCOFIL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_VRDEDUCAONCUM := 0;
         V_VRDEDUCAOCUMU := 0;
   END;

   /*REGISTRO M600(UM POR ARQUIVO)*/
   FOR REG_M600 IN (SELECT '|M600'                                                                                          ||'|'||
                           REPLACE(LTRIM(TO_CHAR(VRDEBITONCUM,   '999999999990.00')),'.',',') ||'|'|| /*CONTRIB. NÃO CUMULATIVA*/
                           REPLACE(LTRIM(TO_CHAR(VRCREDNCUM,     '999999999990.00')),'.',',') ||'|'|| /*CRÉDITO UTILIZADO DO PRÓPRIO PERÍODO - NÃO CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(VRCREDANTNCUM,  '999999999990.00')),'.',',') ||'|'|| /*CRÉDITO UTILIZADO DE PERÍODOS ANTERIORES - NÃO CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(VRIMPDEVIDONCUM,'999999999990.00')),'.',',') ||'|'|| /*VR. DEVIDO NÃO CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(VRIMPRETIDONCUM,'999999999990.00')),'.',',') ||'|'|| /*RETENÇÃO NA FONTE NÃO CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(V_VRDEDUCAONCUM,'999999999990.00')),'.',',') ||'|'|| /*DEDUÇÕES NÃO CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(CASE WHEN VRIMPDEVIDONCUM - VRIMPRETIDONCUM - V_VRDEDUCAONCUM > 0 THEN VRIMPDEVIDONCUM - VRIMPRETIDONCUM - V_VRDEDUCAONCUM ELSE 0 END,'999999999990.00')),'.',',') ||'|'|| /*VR. NÃO CUMULATIVO A PAGAR*/
                           REPLACE(LTRIM(TO_CHAR(VRDEBITOCUMU,   '999999999990.00')),'.',',') ||'|'|| /*CONTRIB. CUMULATIVA*/
                           REPLACE(LTRIM(TO_CHAR(VRIMPRETIDOCUMU,'999999999990.00')),'.',',') ||'|'|| /*RETENÇÃO NA FONTE CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(V_VRDEDUCAOCUMU,'999999999990.00')),'.',',') ||'|'|| /*DEDUÇÕES CUMULATIVO*/
                           REPLACE(LTRIM(TO_CHAR(CASE WHEN VRDEBITOCUMU - VRIMPRETIDOCUMU - V_VRDEDUCAOCUMU > 0 THEN VRDEBITOCUMU - VRIMPRETIDOCUMU - V_VRDEDUCAOCUMU ELSE 0 END,'999999999990.00')),'.',',')       ||'|'|| /*VR. CUMULATIVO A PAGAR*/
                           REPLACE(LTRIM(TO_CHAR(CASE WHEN (CASE WHEN VRIMPDEVIDONCUM-VRIMPRETIDONCUM-V_VRDEDUCAONCUM > 0 THEN VRIMPDEVIDONCUM-VRIMPRETIDONCUM-V_VRDEDUCAONCUM ELSE 0 END + CASE WHEN VRDEBITOCUMU-VRIMPRETIDOCUMU-V_VRDEDUCAOCUMU > 0 THEN VRDEBITOCUMU-VRIMPRETIDOCUMU-V_VRDEDUCAOCUMU ELSE 0 END) > 0
                                                      THEN (CASE WHEN VRIMPDEVIDONCUM-VRIMPRETIDONCUM-V_VRDEDUCAONCUM > 0 THEN VRIMPDEVIDONCUM-VRIMPRETIDONCUM-V_VRDEDUCAONCUM ELSE 0 END + CASE WHEN VRDEBITOCUMU-VRIMPRETIDOCUMU-V_VRDEDUCAOCUMU > 0 THEN VRDEBITOCUMU-VRIMPRETIDOCUMU-V_VRDEDUCAOCUMU ELSE 0 END) ELSE 0 END,'999999999990.00')),'.',',') ||'|' AS REGM600,
                           /*BUSCA OS VALORES DE DÉBITO NÃO CUMULATIVO E CUMULATIVO PARA GERAR O REGISTRO M605*/
                           CASE WHEN VRIMPDEVIDONCUM - VRIMPRETIDONCUM - V_VRDEDUCAONCUM > 0 THEN VRIMPDEVIDONCUM - VRIMPRETIDONCUM - V_VRDEDUCAONCUM ELSE 0 END AS VRIMPRECOLNCUM,
                           CASE WHEN VRDEBITOCUMU - VRIMPRETIDOCUMU - V_VRDEDUCAOCUMU > 0 THEN VRDEBITOCUMU - VRIMPRETIDOCUMU - V_VRDEDUCAOCUMU ELSE 0 END AS VRIMPRECOLCUM
                      FROM (SELECT CASE WHEN NVL(VRDEBITONCUM,0) + V_VRAJUSTENCUM + V_VRDIFERIMENTONCUM > 0
                                        THEN NVL(VRDEBITONCUM,0) + V_VRAJUSTENCUM + V_VRDIFERIMENTONCUM
                                        ELSE 0 END AS VRDEBITONCUM,
                                   DECODE(P_CDINCTRIB,'2',0,NVL(V_VRCREDCOFINS, 0)) AS VRCREDNCUM, DECODE(P_CDINCTRIB,'2',0,NVL(V_CREDANTERIOR,0)) AS VRCREDANTNCUM,
                                   CASE WHEN NVL(VRDEBITONCUM,0) + V_VRAJUSTENCUM + V_VRDIFERIMENTONCUM - DECODE(P_CDINCTRIB,'2',0,NVL(V_VRCREDCOFINS, 0)) - DECODE(P_CDINCTRIB,'2',0,NVL(V_CREDANTERIOR,0)) > 0
                                        THEN NVL(VRDEBITONCUM,0) + V_VRAJUSTENCUM + V_VRDIFERIMENTONCUM - DECODE(P_CDINCTRIB,'2',0,NVL(V_VRCREDCOFINS, 0)) - DECODE(P_CDINCTRIB,'2',0,NVL(V_CREDANTERIOR,0))
                                        ELSE 0 END AS VRIMPDEVIDONCUM,
                                   CASE WHEN NVL(VRDEBITOCUM,0) + V_VRAJUSTECUMU + V_VRDIFERIMENTOCUMU> 0
                                        THEN NVL(VRDEBITOCUM,0) + V_VRAJUSTECUMU + V_VRDIFERIMENTOCUMU
                                        ELSE 0 END AS VRDEBITOCUMU,
                                   V_IMPRETIDONCUM AS VRIMPRETIDONCUM, V_IMPRETIDOCUM AS VRIMPRETIDOCUMU
                              FROM (SELECT SUM(DECODE(NVL(F.IDCUMUPISCOFIL,T.CDFILIAL),'S',NVL(VRCRED,0),0)) AS VRDEBITONCUM,
                                           SUM(DECODE(NVL(F.IDCUMUPISCOFIL,T.CDFILIAL),'N',NVL(VRCRED,0),0)) AS VRDEBITOCUM
                               FROM TMP_REGBLOCOM_PIS T, FILIAL F
                              WHERE T.CDREGISTRO = 'M600'
                                AND T.CDFILIAL   = F.CDFILIAL(+))) /*USA ALTER JOIN NA FILIAL DEVIDO AS RECEITAS FINANCEIRAS, QUE NÃO TEM FILIAL, E O PRÓPRIO CAMPO JÁ TRAZ O REGIME*/
                     UNION
                    SELECT '|M600|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|' AS REGM600,
                           0 AS VRIMPRECOLCUM,
                           0 AS VRIMPRECOLNCUM
                      FROM DUAL
                     WHERE P_GERABCLP = '2')LOOP

      V_CONTREGA:= NVL(V_CONTREGA,0)+1;
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'660'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M600.REGM600);

      /*REGISTRO M605 - OBRIGATÓRIO A PARTIR DE ABRIL DE 2014*/
      /*GERA O REGISTRO CASO TENHA VALOR DE IMPOSTO A RECOLHER PARA CUMULATIVO OU NÃO CUMULATIVO DE ACORDO COM OS CÓDIGOS DA RECEITA INFORMADOS NO MAPA*/
      BEGIN
         SELECT NVL(NVL(CDRECECUMU, CDRECEITACONTR||CDVARIACAO),CDRECEGUIA||NVL(CDVARIACAO,'01')), /*CASO OS ARQUIVOS GERADOS SEJAM DE MAPAS ANTIGOS PEGA O CÓDIGO DA RECEITA DO CAMPO CDRECEITACONTR CONCACTENADO COM A VARIAÇÃO*/
                NVL(NVL(CDRECENCUMU,CDRECEITACONTR||CDVARIACAO),CDRECEGUIA||NVL(CDVARIACAO,'01'))
           INTO V_CDRECECOFINSCUMU, V_CDRECECOFINSNCUMU
           FROM MAPAAPURAC
          WHERE CDEMPRESA = P_CDEMPRESA
            AND CDIMPOSTO = P_COFINS
            AND DTINIPERIODO = P_DTINICIAL
            AND DTFIMPERIODO = P_DTFINAL;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_CDRECECOFINSCUMU  := NULL;
            V_CDRECECOFINSNCUMU := NULL;
      END;

      IF ((NVL(REG_M600.VRIMPRECOLCUM,0) > 0) OR (NVL(REG_M600.VRIMPRECOLNCUM,0) > 0)) AND ((P_DTINICIAL > '31/03/2014')) THEN     /*VERIFICA SE TEVE IMPOSTO A RECOLHER SE O MÊS É MAIOR QUE MARÇO DE 2014 PARA GERAR O RESGISTRO M605*/
         IF NVL(REG_M600.VRIMPRECOLCUM,0) > 0 THEN /*VERIFICA SE TEVE DÉBITO CUMULATIVO*/
            V_REGM605_C := '|M605'            ||'|'||
                           '12'               ||'|'||
                           V_CDRECECOFINSCUMU ||'|'||
                           REPLACE(LTRIM(TO_CHAR(REG_M600.VRIMPRECOLCUM,'999999999990.00')),'.',',')  ||'|';

            V_CONTREGA:= NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'661'||LPAD(RTRIM(V_CONTREGA),22,'0'),V_REGM605_C);
         END IF;
         IF NVL(REG_M600.VRIMPRECOLNCUM,0) > 0 THEN /*VERIFICA SE TEVE DÉBITO NÃO CUMULATIVO*/
            V_REGM605_NC := '|M605'             ||'|'||
                            '08'                ||'|'||
                            V_CDRECECOFINSNCUMU ||'|'||
                            REPLACE(LTRIM(TO_CHAR(REG_M600.VRIMPRECOLNCUM,'999999999990.00')),'.',',')  ||'|';

            V_CONTREGA:= NVL(V_CONTREGA,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'661'||LPAD(RTRIM(V_CONTREGA),22,'0'),V_REGM605_NC);
         END IF;
      END IF;
   END LOOP;

   /*REGISTRO M300: CONTRIBUIÇÃO DE PIS/PASEP DIFERIDA EM PERÍODOS ANTERIORES – VALORES A PAGAR NO PERÍODO.*/
   FOR REG_M700 IN (SELECT '|M700'            ||'|'||
                           CD.CDCONTRIBAPUR   ||'|'||
                           REPLACE(LTRIM(TO_CHAR(SUM(NVL(CC.VRCONTRIBDIFAT, CD.VRCONTRIBDIFAT)),  '999999999990.00')),'.',',') ||'|'||
                           CC.CDNATUCREDDIF   ||'|'||
                           REPLACE(LTRIM(TO_CHAR(SUM(NVL(CC.VRCREDDIFAT, CD.VRCREDDIFAT)),        '999999999990.00')),'.',',') ||'|'||
                           REPLACE(LTRIM(TO_CHAR(SUM(NVL(CC.VRCONTRIBDIFANT, CD.VRCONTRIBDIFANT)),'999999999990.00')),'.',',') ||'|'||
                           TO_CHAR(MP.DTINIPERIODO,'MMYYYY')    ||'|'||
                           TO_CHAR(CD.DTRECEBIMENTO,'DDMMYYYY') ||'|' AS REGM700
                      FROM CONTRIBDIFERIDA CD, MAPAAPURAC MP,
                           (SELECT C.VRCONTRIBDIFAT, C.CDNATUCREDDIF, C.VRCREDDIFAT, C.VRCONTRIBDIFANT, C.NRSEQCONTRDIF
                              FROM CONTROLCREDDIF C
                             WHERE C.NRSEQMAPADIF = V_NRMAPACOFINS
                               AND C.VRCONTRIBDIFANT > 0) CC
                     WHERE CD.NRSEQMAPADIF  = V_NRMAPACOFINS
                       AND CD.NRSEQUMAPAPU  = MP.NRSEQUMAPAPU
                       AND CD.VRCONTRIBDIFANT > 0
                       AND CD.NRSEQCONTRDIF = CC.NRSEQCONTRDIF(+)
                     GROUP BY CD.CDCONTRIBAPUR, CC.CDNATUCREDDIF, MP.DTINIPERIODO, CD.DTRECEBIMENTO) LOOP

       V_CONTREGA:= NVL(V_CONTREGA,0)+1;
       INSERT INTO ARQMAGPISCOFINS
          (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
       VALUES
          (P_NRSEQARQMAG,'670'||LPAD(RTRIM(V_CONTREGA),22,'0'),REG_M700.REGM700);
   END LOOP;

   /*REGISTRO M800*/
   FOR REGM800 IN (SELECT '|M800'       ||'|'||
                          CSTPISCOFINS  ||'|'||
                          REPLACE(LTRIM(TO_CHAR(SUM(VRTOTNF),'999999999990.00')),'.',',')||'|'||
                          CDCONTCTBL    ||'|'||
                          ''            ||'|' AS REGISTRO, CSTPISCOFINS, CDCONTCTBL
                     FROM TMP_REGBLOCOM_PIS
                    WHERE CDREGISTRO   = 'M600'
                      AND CSTPISCOFINS IN ('04','05','06','07','08','09')
                    GROUP BY 'M800', CSTPISCOFINS,CDCONTCTBL)LOOP

      V_CONTREGA:= NVL(V_CONTREGA,0)+1;
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'680'||LPAD(RTRIM(V_CONTREGA),22,'0'),REGM800.REGISTRO);

      /*REGISTRO M810*/
      FOR REGM810 IN (SELECT '|M810'       ||'|'||
                             CDNATUREC     ||'|'||
                             REPLACE(LTRIM(TO_CHAR(SUM(VRTOTNF),'999999999990.00')),'.',',')||'|'||
                             CDCONTCTBL    ||'|'||
                             ''            ||'|' AS REGISTRO
                        FROM TMP_REGBLOCOM_PIS
                       WHERE CDREGISTRO   = 'M600'
                         AND CSTPISCOFINS = REGM800.CSTPISCOFINS
                         AND CDCONTCTBL   = REGM800.CDCONTCTBL
                       GROUP BY 'M810', CDNATUREC, CDCONTCTBL)LOOP

         V_CONTREGA:= NVL(V_CONTREGA,0)+1;
         INSERT INTO ARQMAGPISCOFINS
            (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
            (P_NRSEQARQMAG,'680'||LPAD(RTRIM(V_CONTREGA),22,'0'),REGM810.REGISTRO);
      END LOOP;
   END LOOP;
   P_COUNTBLC0 := V_COUNTBCL0;
   RETURN(V_CONTREGA);
END;
/

create or replace FUNCTION SPED_PIS_COFINS_BLOCOC_ECF(
   P_CONTEST     IN NUMBER, 
   P_NRSEQARQMAG IN ARQMAGPISCOFINS.NRSEQARQMAG%TYPE, 
   P_DTINICIAL   IN NOTAFISCAL.DTENTRSAID%TYPE, 
   P_DTFINAL     IN NOTAFISCAL.DTENTRSAID%TYPE, 
   P_CDEMPRESA   IN EMPRESA.CDEMPRESA%TYPE, 
   P_PIS         IN IMPOSTO.CDIMPOSTO%TYPE, 
   P_COFINS      IN IMPOSTO.CDIMPOSTO%TYPE, 
   P_LIVROMAG    IN LIVROMAGNETICO.CDLIVROMAG%TYPE, 
   P_CONTREGA    IN DOUBLE PRECISION, 
   P_COUNTA      OUT NUMBER, 
   P_CONTESTAB   OUT NUMBER) RETURN NUMBER 
AS 
   V_ESTABELE  VARCHAR2(4); 
   V_NRINSJUR  VARCHAR2(20); 
   V_REG_C010  VARCHAR(100); 
   V_IDMOVREF  VARCHAR2(1); 
   V_REG       VARCHAR2(1000); 
   V_PRODUTO   VARCHAR2(100); 
   V_NOVOEST   VARCHAR2(1); 
   V_UNID      VARCHAR2(10); 
   V_CONTREGA  NUMBER; 
   V_COUNTBCL0 NUMBER; 
   V_TMPBLCM   NUMBER; 
   V_CONTEST   NUMBER; 
   V_SEQUPROD  NUMBER; 
   V_IDC010    VARCHAR2(20); 
   V_COD_CC    VARCHAR2(20); 
   V_SEQCCTBL  NUMBER; 
BEGIN 
   SELECT MAX(CDCONTREGI) 
     INTO V_SEQUPROD 
     FROM TMP_REGDADOSSPED_PIS; 
 
   SELECT MAX(CDCONTREGI) 
     INTO V_TMPBLCM 
     FROM TMP_REGBLOCOM_PIS; 
 
   V_CONTEST := P_CONTEST; 
   V_CONTREGA:= P_CONTREGA; 
   FOR C_ESTAB IN (SELECT DISTINCT CNPJ, INSCRICAO 
                     FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'.',''),'/',''),'-',''),'\','') AS CNPJ, 
                                  REPLACE(REPLACE(REPLACE(REPLACE(I.CDINSCESTA,'.',''),'/',''),'-',''),'\','') AS INSCRICAO 
                             FROM INSCRESTAD I, FILIAL F, CAIXA CX 
                            WHERE I.CDEMPRESA  = P_CDEMPRESA 
                              AND F.CDINSCESTA = I.CDINSCESTA 
                              AND I.CDEMPRESA  = F.CDEMPRESA 
                              AND F.CDFILIAL   = CX.CDFILIAL)JUR)LOOP 
 
      V_NOVOEST:= 'S'; 
      FOR C_REGC400 IN (SELECT '|C400'                      ||'|'|| 
                               '2D'                         ||'|'|| 
                               TRIM(NVL(DSMODMARCAECF,'M')) ||'|'||   
                               NRSERIEREDZ1                 ||'|'|| 
                               CDCAIXA                      ||'|'   AS C400, 
                               CDCAIXA, NRSERIEREDZ, CDFILIAL, CDINSCESTA 
                          FROM (SELECT SUBSTR(NRSERIEREDZ,1,20) AS NRSERIEREDZ1, 
                                       SUBSTR(REPLACE(TRIM(DSMODMARCAECF),'|','-'),1,20) AS DSMODMARCAECF,  
                                       CDCAIXA, RZ.NRSERIEREDZ, RZ.CDFILIAL, FI.CDINSCESTA 
                                  FROM REDUCAOZ RZ ,FILIAL FI, INSCRESTAD IE 
                                 WHERE RZ.DTREDUCAOZ BETWEEN P_DTINICIAL AND P_DTFINAL 
                                   AND RZ.CDFILIAL     = FI.CDFILIAL 
                                   AND FI.CDEMPRESA    = P_CDEMPRESA 
                                   AND REPLACE(REPLACE(REPLACE(REPLACE(IE.NRINSJURIEST,'.',''),'/',''),'-',''),'\','') = C_ESTAB.CNPJ 
                                   AND FI.CDINSCESTA   = IE.CDINSCESTA 
                                   AND REPLACE(REPLACE(REPLACE(REPLACE(FI.CDINSCESTA,'.',''),'/',''),'-',''),'\','') = C_ESTAB.INSCRICAO 
                                   AND RZ.IDSTATUS     = 'A' 
                                   AND NRSERIEREDZ IS NOT NULL 
                                 GROUP BY SUBSTR(NRSERIEREDZ,1,20),DSMODMARCAECF, 
                                          CDCAIXA, RZ.NRSERIEREDZ,RZ.CDFILIAL, FI.CDINSCESTA))LOOP 
 
 
         IF V_NOVOEST = 'S' THEN 
             
            V_IDC010:= NULL; 
            SELECT MAX(CDCHAVEREG) 
             INTO V_IDC010 
             FROM TMP_REGDADOSSPED_PIS 
            WHERE CDREGISTRO = 'C010' 
              AND CDCHAVEREG = C_ESTAB.CNPJ; 
 
             
            IF V_IDC010 IS NULL THEN 
               V_REG_C010 := '|C010|'||C_ESTAB.CNPJ||'|2|'; 
               V_CONTEST  := NVL(V_CONTEST,0)+1; 
               V_CONTREGA := NVL(V_CONTREGA,0)+1; 
               INSERT INTO ARQMAGPISCOFINS 
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG) 
               VALUES 
                  (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(V_CONTEST,'000')),V_REG_C010); 
 
               V_SEQUPROD := NVL(V_SEQUPROD,0)+1; 
               INSERT INTO TMP_REGDADOSSPED_PIS 
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB) 
               VALUES 
                  ('C010',V_SEQUPROD,C_ESTAB.CNPJ,NULL,LTRIM(TO_CHAR(V_CONTEST,'000'))); 
            END IF; 
 
             
            V_ESTABELE:=NULL; 
            V_NRINSJUR:=NULL; 
            SELECT MAX(CDESTAB) AS ESTAB, MAX(CDCHAVEREG) AS CNPJ 
              INTO V_ESTABELE, V_NRINSJUR 
              FROM TMP_REGDADOSSPED_PIS 
             WHERE CDREGISTRO = '0140' 
               AND CDCHAVEREG = C_ESTAB.CNPJ; 
 
            IF V_NRINSJUR IS NULL THEN 
               V_ESTABELE:= V_CONTEST; 
               V_REG:= NULL; 
               BEGIN 
                  SELECT '|0140'             ||'|'|| 
                         LTRIM(TO_CHAR(V_ESTABELE,'000'))                 ||'|'|| 
                         MAX(E.NMRAZSOCEMPR) ||'|'|| 
                         REPLACE(REPLACE(REPLACE(REPLACE(MAX(IE.NRINSJURIEST),'.',''),'/',''),'-',''),'\','') ||'|'|| 
                         MAX(IE.SGESTADO)    ||'|'|| 
                         ''                  ||'|'|| 
                         MAX(M.CDMUNICIBGE)  ||'|'|| 
                         ''                  ||'|'|| 
                         ''                  ||'|' 
                         INTO V_REG 
                    FROM INSCRESTAD IE, MUNICIPIO M, EMPRESA E 
                      WHERE IE.NRINSJURIEST = C_ESTAB.CNPJ 
                        AND IE.CDPAIS       = M.CDPAIS 
                        AND IE.SGESTADO     = M.SGESTADO 
                        AND IE.CDMUNICIPIO  = M.CDMUNICIPIO 
                        AND IE.CDEMPRESA    = P_CDEMPRESA 
                        AND E.CDEMPRESA     = IE.CDEMPRESA 
                      GROUP BY '0140'; 
               EXCEPTION 
                  WHEN NO_DATA_FOUND THEN 
                     V_REG:= NULL; 
               END; 
               V_COUNTBCL0:= NVL(V_COUNTBCL0,0)+1; 
               INSERT INTO ARQMAGPISCOFINS 
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG) 
               VALUES 
                  (P_NRSEQARQMAG,'104'||LTRIM(TO_CHAR(V_ESTABELE,'000')),NVL(V_REG,'VAZIO')); 
 
               V_SEQUPROD := NVL(V_SEQUPROD,0)+1; 
               INSERT INTO TMP_REGDADOSSPED_PIS 
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB) 
                VALUES 
                 ('0140', V_SEQUPROD, C_ESTAB.CNPJ ,NULL, LTRIM(TO_CHAR(V_CONTEST,'000'))); 
            END IF; 
 
         END IF; 
          
         V_CONTREGA := NVL(V_CONTREGA,0)+1; 
         INSERT INTO ARQMAGPISCOFINS 
            (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG) 
         VALUES 
            (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(V_ESTABELE,'000'))||'03'||LPAD(RTRIM(V_CONTREGA),22,'0'),C_REGC400.C400); 
 
         V_NOVOEST:= 'N'; 
 
         FOR C_REGC405 IN (SELECT ('|C405'                                                                           || '|' || 
                                   TO_CHAR(RZ.DTREDUCAOZ,'ddmmyyyy')                                                 || '|' || 
                                   LPAD(LTRIM(NVL(RZ.NRREINIREDZ,'0'),'0'), 3, '0')                                  || '|' || 
                                   LPAD(LTRIM(NVL(RZ.NRREDREDZ,'0'),'0'), 6, '0')                                    || '|' || 
                                   LPAD(LTRIM(NVL(RZ.NRULTCFREDZ,'0'),'0'), 6, '0')                                  || '|' || 
                                   REPLACE(LTRIM(TO_CHAR(TRUNC(RZ.VRGTREDZ,2), '999999999990.00')), '.', ',')        || '|' || 
                                   REPLACE(LTRIM(TO_CHAR(TRUNC(RZ.VRVENBRUREDZ,2), '999999999990.00')), '.', ',')    || '|' ) AS C405, 
                                   DTREDUCAOZ, RZ.NRECFREDZ, FI.CDFILIAL, NRULTCFREDZ, RZ.NRREDREDZ 
                             FROM REDUCAOZ RZ, FILIAL FI, INSCRESTAD IE 
                            WHERE RZ.CDFILIAL    = FI.CDFILIAL 
                              AND RZ.DTREDUCAOZ BETWEEN P_DTINICIAL AND P_DTFINAL 
                              AND FI.CDEMPRESA   = P_CDEMPRESA 
                              AND IE.NRINSJURIEST = C_ESTAB.CNPJ 
                              AND FI.CDINSCESTA   = IE.CDINSCESTA 
                              AND RZ.IDSTATUS     = 'A' 
                              AND IE.CDEMPRESA    = P_CDEMPRESA 
                              AND REPLACE(REPLACE(REPLACE(REPLACE(FI.CDINSCESTA,'.',''),'/',''),'-',''),'\','') = C_ESTAB.INSCRICAO 
                              AND RZ.CDCAIXA     = C_REGC400.CDCAIXA 
                              AND NRSERIEREDZ    = C_REGC400.NRSERIEREDZ 
                              AND VRVENBRUREDZ   > 0) LOOP 
            V_CONTREGA := NVL(V_CONTREGA,0)+1; 
            INSERT INTO ARQMAGPISCOFINS 
               (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG) 
            VALUES 
               (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(V_ESTABELE,'000'))||'03'||LPAD(RTRIM(V_CONTREGA),22,'0'),C_REGC405.C405); 
 
             
            FOR C_REGC481 IN (SELECT REGISTRO      ||'|'|| 
                                     CDSITUTRIBNFE ||'|'|| 
                                     LTRIM(REPLACE(TO_CHAR(ROUND(SUM(NVL(VRPRODUTO,0)),2),'9999999999990.00'),'.',','))||'|'|| 
                                     LTRIM(REPLACE(TO_CHAR(ROUND(SUM(NVL(VRBASECALCIT,0)),2),'9999999999990.00'),'.',','))||'|'|| 
                                     LTRIM(REPLACE(TO_CHAR(ROUND(NVL(VRALIQIT,0),2),'990.00'),'.',','))||'|'|| 
                                     ALI_PIS_QT                                               ||'|'|| 
                                     QT_BC_PIS                                                ||'|'|| 
                                     LTRIM(REPLACE(TO_CHAR(ROUND(SUM(NVL(VRIMPOSTO,0)),2),'9999999999990.00'),'.',','))||'|'|| 
                                     CDARVPROD||'|'|| 
                                     CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,C_REGC405.CDFILIAL) ||'|' AS REGISTRO , 
                                     CDSITUTRIBNFE, CDPRODUTO, VRALIQIT,CDARVPROD,SGUNIDADE, 
                                     CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,C_REGC405.CDFILIAL) AS COD_CTA, CDCLASFISC 
                                FROM (SELECT '|C481' AS REGISTRO, CDSITUTRIBNFE, IT.VRPRODUTO AS VRPRODUTO, DECODE(CDFISCALIT,1,IT.VRPRODUTO,0) AS VRBASECALCIT, 
                                             DECODE(CDFISCALIT,'1',VRALIQIT,0) AS VRALIQIT, '' AS ALI_PIS_QT, '' AS QT_BC_PIS, 
                                             (VRPRODUTO*(DECODE(CDFISCALIT,'1',VRALIQIT,0))/100) AS VRIMPOSTO, 
                                             P.CDARVPROD AS CDARVPROD, P.CDPRODUTO, P.SGUNIDADE, PV.CDTPOPERCNTREC AS CDTIPOOPER, IT.CDCLASFISC 
                                        FROM ITEMVENOUTIMPOS IT, PRODUTO P, IMPOSTO I, PARAVEND PV 
                                       WHERE IT.CDFILIAL    = C_REGC405.CDFILIAL 
                                         AND IT.CDCAIXA     = C_REGC400.CDCAIXA 
                                         AND IT.DTREDUCAOZ  = C_REGC405.DTREDUCAOZ 
                                         AND IT.CDIMPOSTO   = I.CDIMPOSTO 
                                         AND I.CDIMPOSTONFE = P_PIS 
                                         AND P.CDPRODUTO    = IT.CDPRODUTO 
                                         AND (IT.IDORIGEMVENDA NOT IN ('SAT', 'NFCE')) 
                                         AND PV.CDFILIAL    = IT.CDFILIAL) 
                               GROUP BY CDSITUTRIBNFE, CDPRODUTO, VRALIQIT, REGISTRO, ALI_PIS_QT, QT_BC_PIS, CDARVPROD,SGUNIDADE, 
                                        CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,C_REGC405.CDFILIAL),CDCLASFISC)LOOP 
 
               V_CONTREGA := NVL(V_CONTREGA,0)+1; 
               INSERT INTO ARQMAGPISCOFINS 
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG) 
               VALUES 
                  (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(V_ESTABELE,'000'))||'03'||LPAD(RTRIM(V_CONTREGA),22,'0'),C_REGC481.REGISTRO); 
 
               V_PRODUTO:=NULL; 
               
               SELECT MAX(CDCHAVEREG) 
                 INTO V_PRODUTO 
                 FROM TMP_REGDADOSSPED_PIS 
                WHERE CDCHAVEREG = C_REGC481.CDARVPROD 
                  AND CDREGISTRO = '0200' 
                  AND CDESTAB = LTRIM(TO_CHAR(V_ESTABELE,'000')); 
 
               IF (V_PRODUTO IS NULL) AND (C_REGC481.CDARVPROD IS NOT NULL) THEN 
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1; 
                  INSERT INTO TMP_REGDADOSSPED_PIS 
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB,CDCAMPO4) 
                  VALUES 
                     ('0200', V_SEQUPROD, C_REGC481.CDARVPROD,NULL,LTRIM(TO_CHAR(V_ESTABELE,'000')),C_REGC481.CDCLASFISC); 
               END IF; 
 
               V_UNID:= null; 
                
               SELECT MAX(CDCHAVEREG) 
                 INTO V_UNID 
                 FROM TMP_REGDADOSSPED_PIS 
                WHERE CDCHAVEREG = C_REGC481.SGUNIDADE 
                  AND CDREGISTRO = '0190' 
                  AND CDESTAB = LTRIM(TO_CHAR(V_ESTABELE,'000')); 
 
               IF (V_UNID IS NULL) AND (C_REGC481.SGUNIDADE IS NOT NULL) THEN 
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1; 
                  INSERT INTO TMP_REGDADOSSPED_PIS 
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB) 
                  VALUES 
                     ('0190', V_SEQUPROD, C_REGC481.SGUNIDADE,NULL,LTRIM(TO_CHAR(V_ESTABELE,'000'))); 
               END IF; 
 
                
               BEGIN 
                  SELECT MAX(CDCHAVEREG) 
                    INTO V_COD_CC 
                    FROM TMP_REGDADOSSPED_PIS 
                   WHERE CDCHAVEREG = C_REGC481.COD_CTA 
                     AND CDREGISTRO = '0500'; 
               EXCEPTION 
                  WHEN NO_DATA_FOUND THEN 
                     V_COD_CC := NULL; 
               END; 
 
               IF (V_COD_CC IS NULL) AND (C_REGC481.COD_CTA IS NOT NULL) THEN 
                  V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1; 
                  INSERT INTO TMP_REGDADOSSPED_PIS 
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1) 
                  VALUES 
                     ('0500', V_SEQCCTBL, C_REGC481.COD_CTA, NULL); 
               END IF; 
            END LOOP; 
 
             
            FOR C_GRAVM2 IN(SELECT SUM(VRBASECALCIT) AS VRBASECALCIT, SUM(VRIMPOSTO) AS VRIMPOSTO, CDSITUTRIBNFE, 
                                   VRALIQIT, CDTPCRPICOSTNFE, CDNATUBCPCSTNFE, SUM(VRPRODUTO) AS VRPRODUTO, 
                                   CDNATUREC, COD_CTA 
                              FROM (SELECT DECODE(CDFISCALIT,1,IT.VRPRODUTO,0) AS VRBASECALCIT, VRPRODUTO , (VRPRODUTO*(DECODE(CDFISCALIT,'1',VRALIQIT,0))/100) AS VRIMPOSTO, 
                                           CDSITUTRIBNFE, DECODE(CDFISCALIT,'1',VRALIQIT,0) AS VRALIQIT, CDTPCRPICOSTNFE, CDNATUBCPCSTNFE, 
                                           R.CDNATUREC, CONTCTBL_SPED('S',IT.CDPRODUTO,P.CDTPOPERCNTREC,P.CDFILIAL) AS COD_CTA 
                                      FROM ITEMVENOUTIMPOS IT, IMPOSTO I, RELACPRODITGEN R, PARAVEND P 
                                     WHERE IT.CDFILIAL    = C_REGC405.CDFILIAL 
                                       AND IT.CDCAIXA     = C_REGC400.CDCAIXA 
                                       AND IT.DTREDUCAOZ  = C_REGC405.DTREDUCAOZ 
                                       AND IT.CDFILIAL    = P.CDFILIAL 
                                       AND IT.CDIMPOSTO   = I.CDIMPOSTO 
                                       AND I.CDIMPOSTONFE = P_PIS 
                                       AND IT.CDPRODUTO   = R.CDPRODUTO(+) 
                                       AND P_LIVROMAG     = R.CDLIVROMAG(+) 
                                       AND (IT.IDORIGEMVENDA IS NULL OR IT.IDORIGEMVENDA NOT IN ('SAT', 'NFCE'))) 
                             GROUP BY CDSITUTRIBNFE, VRALIQIT, CDTPCRPICOSTNFE, CDNATUBCPCSTNFE, CDNATUREC, COD_CTA)LOOP 
 
                
                
               IF (C_GRAVM2.CDSITUTRIBNFE <> '05') AND (C_REGC405.DTREDUCAOZ >= '01/08/2013') THEN 
                  V_TMPBLCM:= NVL(V_TMPBLCM,0)+1; 
                  INSERT INTO TMP_REGBLOCOM_PIS 
                     (CHAVENOTA, CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT,VRIMPRETIDO,VRTOTNF,CDNATUREC,CDCONTCTBL) 
                  VALUES 
                     ('C481'||C_REGC405.DTREDUCAOZ||C_REGC405.CDFILIAL,'M200',V_TMPBLCM,C_GRAVM2.CDTPCRPICOSTNFE,C_GRAVM2.VRBASECALCIT,C_GRAVM2.VRALIQIT,'P',C_GRAVM2.VRIMPOSTO,C_GRAVM2.CDSITUTRIBNFE,C_REGC405.CDFILIAL,C_GRAVM2.CDNATUBCPCSTNFE,'0',C_GRAVM2.VRPRODUTO,C_GRAVM2.CDNATUREC,C_GRAVM2.COD_CTA); 
               END IF; 
            END LOOP; 
 
             
            FOR C_REGC485 IN (SELECT REGISTRO      ||'|'|| 
                                     CDSITUTRIBNFE ||'|'|| 
                                     LTRIM(REPLACE(TO_CHAR(ROUND(SUM(NVL(VRPRODUTO,0)),2),'9999999999990.00'),'.',','))||'|'|| 
                                     LTRIM(REPLACE(TO_CHAR(ROUND(SUM(NVL(VRBASECALCIT,0)),2),'9999999999990.00'),'.',','))||'|'|| 
                                     LTRIM(REPLACE(TO_CHAR(ROUND(NVL(VRALIQIT,0),2),'990.00'),'.',','))||'|'|| 
                                     ALI_COFINS_QT                                               ||'|'|| 
                                     QT_BC_COFINS                                                ||'|'|| 
                                     LTRIM(REPLACE(TO_CHAR(ROUND(SUM(NVL(VRIMPOSTO,0)),2),'9999999999990.00'),'.',','))||'|'|| 
                                     CDARVPROD||'|'|| 
                                     CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,C_REGC405.CDFILIAL) ||'|' AS REGISTRO , 
                                     CDSITUTRIBNFE, CDPRODUTO, VRALIQIT, CDARVPROD, SGUNIDADE, 
                                     CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,C_REGC405.CDFILIAL) AS COD_CTA 
                                FROM (SELECT '|C485' AS REGISTRO, CDSITUTRIBNFE, IT.VRPRODUTO AS VRPRODUTO, DECODE(CDFISCALIT,1,IT.VRPRODUTO,0) AS VRBASECALCIT, 
                                             DECODE(CDFISCALIT,'1',VRALIQIT,0) AS VRALIQIT, '' AS ALI_COFINS_QT, '' AS QT_BC_COFINS, (VRPRODUTO*(DECODE(CDFISCALIT,'1',VRALIQIT,0))/100) AS VRIMPOSTO, 
                                             P.CDARVPROD AS CDARVPROD, P.CDPRODUTO, P.SGUNIDADE,PV.CDTPOPERCNTREC AS CDTIPOOPER 
                                        FROM ITEMVENOUTIMPOS IT, PRODUTO P, IMPOSTO I, PARAVEND PV 
                                       WHERE IT.CDFILIAL    = C_REGC405.CDFILIAL 
                                         AND IT.CDCAIXA     = C_REGC400.CDCAIXA 
                                         AND IT.DTREDUCAOZ  = C_REGC405.DTREDUCAOZ 
                                         AND IT.CDIMPOSTO   = I.CDIMPOSTO 
                                         AND I.CDIMPOSTONFE = P_COFINS 
                                         AND P.CDPRODUTO    = IT.CDPRODUTO 
                                         AND (IT.IDORIGEMVENDA NOT IN ('SAT', 'NFCE')) 
                                         AND PV.CDFILIAL    = IT.CDFILIAL) 
                                       GROUP BY REGISTRO, CDSITUTRIBNFE, CDPRODUTO, CDARVPROD, VRALIQIT, ALI_COFINS_QT, QT_BC_COFINS, 
                                             SGUNIDADE, CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,C_REGC405.CDFILIAL))LOOP 
 
               V_CONTREGA := NVL(V_CONTREGA,0)+1; 
               INSERT INTO ARQMAGPISCOFINS 
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG) 
               VALUES 
                  (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(V_ESTABELE,'000'))||'03'||LPAD(RTRIM(V_CONTREGA),22,'0'),C_REGC485.REGISTRO); 
 
                
               BEGIN 
                  SELECT MAX(CDCHAVEREG) 
                    INTO V_COD_CC 
                    FROM TMP_REGDADOSSPED_PIS 
                   WHERE CDCHAVEREG = C_REGC485.COD_CTA 
                     AND CDREGISTRO = '0500'; 
               EXCEPTION 
                  WHEN NO_DATA_FOUND THEN 
                     V_COD_CC := NULL; 
               END; 
 
               IF (V_COD_CC IS NULL) AND (C_REGC485.COD_CTA IS NOT NULL) THEN 
                  V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1; 
                  INSERT INTO TMP_REGDADOSSPED_PIS 
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1) 
                  VALUES 
                     ('0500', V_SEQCCTBL, C_REGC485.COD_CTA, NULL); 
               END IF; 
            END LOOP; 
 
             
            FOR C_GRAVM6 IN(SELECT SUM(VRBASECALCIT) AS VRBASECALCIT, SUM(VRIMPOSTO) AS VRIMPOSTO, CDSITUTRIBNFE, 
                                   VRALIQIT, CDTPCRPICOSTNFE, CDNATUBCPCSTNFE, SUM(VRPRODUTO) AS VRPRODUTO, 
                                   CDNATUREC, COD_CTA 
                              FROM (SELECT DECODE(CDFISCALIT,1,IT.VRPRODUTO,0) AS VRBASECALCIT, VRPRODUTO , (VRPRODUTO*(DECODE(CDFISCALIT,'1',VRALIQIT,0))/100) AS VRIMPOSTO, 
                                           CDSITUTRIBNFE, DECODE(CDFISCALIT,'1',VRALIQIT,0) AS VRALIQIT, CDTPCRPICOSTNFE, CDNATUBCPCSTNFE, 
                                           R.CDNATUREC, CONTCTBL_SPED('S',IT.CDPRODUTO,P.CDTPOPERCNTREC,P.CDFILIAL) AS COD_CTA 
                                      FROM ITEMVENOUTIMPOS IT, IMPOSTO I, RELACPRODITGEN R, PARAVEND P 
                                     WHERE IT.CDFILIAL    = C_REGC405.CDFILIAL 
                                       AND IT.CDCAIXA     = C_REGC400.CDCAIXA 
                                       AND IT.DTREDUCAOZ  = C_REGC405.DTREDUCAOZ 
                                       AND IT.CDFILIAL    = P.CDFILIAL 
                                       AND IT.CDIMPOSTO   = I.CDIMPOSTO 
                                       AND I.CDIMPOSTONFE = P_COFINS 
                                       AND IT.CDPRODUTO   = R.CDPRODUTO(+) 
                                       AND P_LIVROMAG     = R.CDLIVROMAG(+) 
                                       AND (IT.IDORIGEMVENDA IS NULL OR IT.IDORIGEMVENDA NOT IN ('SAT', 'NFCE'))) 
                                     GROUP BY CDSITUTRIBNFE, VRALIQIT,CDTPCRPICOSTNFE, CDNATUBCPCSTNFE, CDNATUREC, COD_CTA)LOOP 
 
                
                
               IF (C_GRAVM6.CDSITUTRIBNFE <> '05') AND (C_REGC405.DTREDUCAOZ >= '01/08/2013') THEN 
                  V_TMPBLCM:= NVL(V_TMPBLCM,0)+1; 
                  INSERT INTO TMP_REGBLOCOM_PIS 
                     (CHAVENOTA,CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT,VRIMPRETIDO,VRTOTNF,CDNATUREC,CDCONTCTBL) 
                  VALUES 
                     ('C485'||C_REGC405.DTREDUCAOZ||C_REGC405.CDFILIAL,'M600',V_TMPBLCM,C_GRAVM6.CDTPCRPICOSTNFE,C_GRAVM6.VRBASECALCIT,C_GRAVM6.VRALIQIT,'P',C_GRAVM6.VRIMPOSTO,C_GRAVM6.CDSITUTRIBNFE,C_REGC405.CDFILIAL,C_GRAVM6.CDNATUBCPCSTNFE,'0',C_GRAVM6.VRPRODUTO,C_GRAVM6.CDNATUREC,C_GRAVM6.COD_CTA); 
               END IF; 
            END LOOP; 
         END LOOP; 
      END LOOP; 
 
      FOR C_REGC860 IN (SELECT (REG     || '|' || 
                                COD_MOD || '|' || 
                                NR_SAT  || '|' || 
                                DT_DOC  || '|' || 
                                DOC_INI || '|' || 
                                DOC_FIM || '|' ) C860, NR_SAT, DTEMISSAO, CDFILIAL 
                          FROM (SELECT '|C860' AS REG, '59' AS COD_MOD, VE.CDSERIESAT AS NR_SAT, TO_CHAR(TRUNC(VE.DTEMISSAONFCE),'DDMMYYYY') AS DT_DOC, 
                                       MIN(LPAD(NVL(VE.NRNOTAFISCALCE,0),6,'0')) DOC_INI, MAX(LPAD(NVL(VE.NRNOTAFISCALCE,0),6,'0')) DOC_FIM, 
                                       TRUNC(VE.DTEMISSAONFCE) AS DTEMISSAO, MAX(VE.CDFILIAL) AS CDFILIAL 
                                  FROM VENDA VE, FILIAL FI, INSCRESTAD IE 
                                 WHERE TRUNC(VE.DTEMISSAONFCE) BETWEEN P_DTINICIAL AND P_DTFINAL 
                                   AND VE.IDTPEMISVEND    = 'S' 
                                   AND VE.CDFILIAL        = FI.CDFILIAL 
                                   AND FI.CDEMPRESA       = P_CDEMPRESA 
                                   AND FI.CDEMPRESA       = IE.CDEMPRESA 
                                   AND FI.CDINSCESTA      = IE.CDINSCESTA 
                                   AND REPLACE(REPLACE(REPLACE(REPLACE(IE.NRINSJURIEST,'.',''),'/',''),'-',''),'\','') = C_ESTAB.CNPJ 
                                   AND REPLACE(REPLACE(REPLACE(REPLACE(IE.CDINSCESTA,'.',''),'/',''),'-',''),'\','')   = C_ESTAB.INSCRICAO 
                                   AND VE.IDSITUVENDA     IN ('O') 
                                   AND VE.IDAPROVACAONFCE = 'A' 
                                   AND VE.IDSTATUSNFCE    = 'A' 
                                   AND VE.IDTPAMBNFCE     = '1' 
                                 GROUP BY VE.CDSERIESAT, TRUNC(VE.DTEMISSAONFCE))) LOOP 
 
         IF V_NOVOEST = 'S' THEN 
             
            V_IDC010:= NULL; 
            SELECT MAX(CDCHAVEREG) 
              INTO V_IDC010 
              FROM TMP_REGDADOSSPED_PIS 
             WHERE CDREGISTRO = 'C010' 
               AND CDCHAVEREG = C_ESTAB.CNPJ; 
 
             
            IF V_IDC010 IS NULL THEN 
               V_REG_C010:= '|C010|'||C_ESTAB.CNPJ||'|2|'; 
               V_CONTEST := NVL(V_CONTEST,0)+1; 
               V_CONTREGA := NVL(V_CONTREGA,0)+1; 
               INSERT INTO ARQMAGPISCOFINS 
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG) 
               VALUES 
                  (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(V_CONTEST,'000')),V_REG_C010); 
 
               V_SEQUPROD := NVL(V_SEQUPROD,0)+1; 
               INSERT INTO TMP_REGDADOSSPED_PIS 
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB) 
               VALUES 
                  ('C010',V_SEQUPROD,C_ESTAB.CNPJ,NULL,LTRIM(TO_CHAR(V_CONTEST,'000'))); 
            END IF; 
 
             
            V_ESTABELE:=NULL; 
            V_NRINSJUR:=NULL; 
            SELECT MAX(CDESTAB) AS ESTAB, MAX(CDCHAVEREG) AS CNPJ 
              INTO V_ESTABELE, V_NRINSJUR 
              FROM TMP_REGDADOSSPED_PIS 
             WHERE CDREGISTRO = '0140' 
               AND CDCHAVEREG = C_ESTAB.CNPJ; 
 
            IF V_NRINSJUR IS NULL THEN 
               V_ESTABELE:= V_CONTEST; 
               V_REG:= NULL; 
               BEGIN 
                  SELECT '|0140'             ||'|'|| 
                         LTRIM(TO_CHAR(V_ESTABELE,'000'))                 ||'|'|| 
                         MAX(E.NMRAZSOCEMPR) ||'|'|| 
                         REPLACE(REPLACE(REPLACE(REPLACE(MAX(IE.NRINSJURIEST),'.',''),'/',''),'-',''),'\','') ||'|'|| 
                         MAX(IE.SGESTADO)    ||'|'|| 
                         ''                  ||'|'|| 
                         MAX(M.CDMUNICIBGE)  ||'|'|| 
                         ''                  ||'|'|| 
                         ''                  ||'|' 
                         INTO V_REG 
                    FROM INSCRESTAD IE, MUNICIPIO M, EMPRESA E 
                   WHERE REPLACE(REPLACE(REPLACE(REPLACE(IE.NRINSJURIEST,'.',''),'/',''),'-',''),'\','') = C_ESTAB.CNPJ 
                     AND IE.CDPAIS       = M.CDPAIS 
                     AND IE.SGESTADO     = M.SGESTADO 
                     AND IE.CDMUNICIPIO  = M.CDMUNICIPIO 
                     AND IE.CDEMPRESA    = P_CDEMPRESA 
                     AND E.CDEMPRESA     = IE.CDEMPRESA 
                   GROUP BY '0140'; 
               EXCEPTION 
                  WHEN NO_DATA_FOUND THEN 
                     V_REG:= NULL; 
               END; 
               V_COUNTBCL0:= NVL(V_COUNTBCL0,0)+1; 
               INSERT INTO ARQMAGPISCOFINS 
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG) 
               VALUES 
                  (P_NRSEQARQMAG,'104'||LTRIM(TO_CHAR(V_ESTABELE,'000')),NVL(V_REG,'VAZIO')); 
 
               V_SEQUPROD := NVL(V_SEQUPROD,0)+1; 
               INSERT INTO TMP_REGDADOSSPED_PIS 
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB) 
                VALUES 
                 ('0140', V_SEQUPROD, C_ESTAB.CNPJ ,NULL, LTRIM(TO_CHAR(V_CONTEST,'000'))); 
            END IF; 
         END IF; 
         V_NOVOEST := 'N'; 
 
          
         V_CONTREGA := NVL(V_CONTREGA,0)+1; 
         INSERT INTO ARQMAGPISCOFINS 
            (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG) 
         VALUES 
            (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(V_ESTABELE,'000'))||'05'||LPAD(RTRIM(V_CONTREGA),22,'0'),C_REGC860.C860); 
 
         FOR C_REGC870 IN (SELECT (REG                                                             ||'|'|| 
                                   COD_ITEM                                                        ||'|'|| 
                                   CFOP                                                            ||'|'|| 
                                   LTRIM(REPLACE(TO_CHAR(VL_ITEM,  '999999999990.00'),'.',','))    ||'|'|| 
                                   VL_DESC                                                         ||'|'|| 
                                   CST_PIS                                                         ||'|'|| 
                                   LTRIM(REPLACE(TO_CHAR(VL_BC_PIS,'999999999990.00'),'.',','))    ||'|'|| 
                                   LTRIM(REPLACE(TO_CHAR(ALIQ_PIS, '990.00'),'.',','))             ||'|'|| 
                                   LTRIM(REPLACE(TO_CHAR(VL_PIS,   '999999999990.00'),'.',','))    ||'|'|| 
                                   CST_COFINS                                                      ||'|'|| 
                                   LTRIM(REPLACE(TO_CHAR(VL_BC_COFINS,'999999999990.00'),'.',',')) ||'|'|| 
                                   LTRIM(REPLACE(TO_CHAR(ALIQ_COFINS, '990.00'),'.',','))          ||'|'|| 
                                   LTRIM(REPLACE(TO_CHAR(VL_COFINS,   '999999999990.00'),'.',',')) ||'|'|| 
                                   COD_CTA                                                         ||'|') C870, 
                                   COD_ITEM, VL_ITEM, CST_PIS, VL_BC_PIS, ALIQ_PIS, VL_PIS, VL_BC_COFINS, 
                                   ALIQ_COFINS, VL_COFINS, SGUNIDADE, CDNATUREC, COD_CTA, CDCLASFISC 
                             FROM (SELECT '|C870' AS REG, PR.CDARVPROD AS COD_ITEM, IT.CDFISCOPERSN AS CFOP, 
                                          SUM(DECODE(IM.CDIMPOSTONFE,'50',IT.VRPRODUTO,0)) AS VL_ITEM, 
                                          '0,00' AS VL_DESC, 
                                          IT.CDSITUTRIBNFE AS CST_PIS, 
                                          SUM(DECODE(IM.CDIMPOSTONFE,'50',DECODE(IT.CDFISCALIT,'1',IT.VRPRODUTO,0),0)) AS VL_BC_PIS, 
                                          MAX(DECODE(IM.CDIMPOSTONFE,'50',DECODE(IT.CDFISCALIT,'1',NVL(IT.VRALIQIT,0),0),0)) AS ALIQ_PIS, 
                                          SUM(DECODE(IM.CDIMPOSTONFE,'50',DECODE(IT.CDFISCALIT,'1',CASE WHEN IDORIGEMVENDA IN ('SAT','ECF') 
                                              THEN IT.VRIMPOSTOIT ELSE IT.VRPRODUTO*IT.VRALIQIT/100 END,0),0)) AS VL_PIS, 
                                          IT.CDSITUTRIBNFE AS CST_COFINS, 
                                          SUM(DECODE(IM.CDIMPOSTONFE,'60',DECODE(IT.CDFISCALIT,'1',IT.VRPRODUTO,0),0)) AS VL_BC_COFINS, 
                                          MAX(DECODE(IM.CDIMPOSTONFE,'60',DECODE(IT.CDFISCALIT,'1',NVL(IT.VRALIQIT,0),0),0)) AS ALIQ_COFINS, 
                                          SUM(DECODE(IM.CDIMPOSTONFE,'60',DECODE(IT.CDFISCALIT,'1',CASE WHEN IDORIGEMVENDA IN ('SAT','ECF') 
                                              THEN IT.VRIMPOSTOIT ELSE IT.VRPRODUTO*IT.VRALIQIT/100 END,0),0)) AS VL_COFINS, 
                                          CONTCTBL_SPED('S',PR.CDPRODUTO,PV.CDTPOPERCNTREC,IT.CDFILIAL) AS COD_CTA, 
                                          PR.SGUNIDADE, RE.CDNATUREC, MAX(IT.CDCLASFISC) AS CDCLASFISC
                                     FROM ITEMVENOUTIMPOS IT, FILIAL FI, INSCRESTAD IE, PRODUTO PR, IMPOSTO IM, RELACPRODITGEN RE, PARAVEND PV 
                                    WHERE IT.CDFILIAL      = FI.CDFILIAL 
                                      AND FI.CDEMPRESA     = P_CDEMPRESA 
                                      AND FI.CDINSCESTA    = IE.CDINSCESTA 
                                      AND FI.CDEMPRESA     = IE.CDEMPRESA 
                                      AND REPLACE(REPLACE(REPLACE(REPLACE(IE.NRINSJURIEST,'.',''),'/',''),'-',''),'\','') = C_ESTAB.CNPJ 
                                      AND REPLACE(REPLACE(REPLACE(REPLACE(IE.CDINSCESTA,'.',''),'/',''),'-',''),'\','') = C_ESTAB.INSCRICAO 
                                      AND IT.DTREDUCAOZ    = C_REGC860.DTEMISSAO 
                                      AND IT.CDSERIESAT    = C_REGC860.NR_SAT 
                                      AND IT.CDPRODUTO     = PR.CDPRODUTO 
                                      AND IT.CDIMPOSTO     = IM.CDIMPOSTO 
                                      AND IM.CDIMPOSTONFE  IN ('50','60') 
                                      AND RE.CDLIVROMAG(+) = P_LIVROMAG 
                                      AND RE.CDPRODUTO(+)  = PR.CDPRODUTO 
                                      AND IT.IDORIGEMVENDA IN ('SAT', 'ECF') 
                                      AND PV.CDFILIAL      = IT.CDFILIAL 
                                    GROUP BY PR.CDARVPROD, IT.CDFISCOPERSN, IT.CDSITUTRIBNFE, PR.SGUNIDADE, RE.CDNATUREC, 
                                          CONTCTBL_SPED('S',PR.CDPRODUTO,PV.CDTPOPERCNTREC,IT.CDFILIAL))) LOOP 
 
             
            V_CONTREGA := NVL(V_CONTREGA,0)+1; 
            INSERT INTO ARQMAGPISCOFINS 
               (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG) 
            VALUES 
               (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(V_ESTABELE,'000'))||'05'||LPAD(RTRIM(V_CONTREGA),22,'0'),C_REGC870.C870); 
 
            IF (C_REGC870.CST_PIS <> '05') AND (C_REGC860.DTEMISSAO >= '01/08/2013') THEN 
                
               V_TMPBLCM:= NVL(V_TMPBLCM,0)+1; 
               INSERT INTO TMP_REGBLOCOM_PIS 
                  (CHAVENOTA,CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT,VRIMPRETIDO,VRTOTNF,CDNATUREC,CDCONTCTBL) 
               VALUES 
                  ('C870'||C_REGC860.CDFILIAL,'M200',V_TMPBLCM,'',C_REGC870.VL_BC_PIS,C_REGC870.ALIQ_PIS,'P',C_REGC870.VL_PIS,C_REGC870.CST_PIS,C_REGC860.CDFILIAL,'','0',C_REGC870.VL_ITEM,C_REGC870.CDNATUREC,C_REGC870.COD_CTA); 
 
                
               V_TMPBLCM:= NVL(V_TMPBLCM,0)+1; 
               INSERT INTO TMP_REGBLOCOM_PIS 
                  (CHAVENOTA,CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT,VRIMPRETIDO,VRTOTNF,CDNATUREC,CDCONTCTBL) 
               VALUES 
                  ('C870'||C_REGC860.CDFILIAL,'M600',V_TMPBLCM,'',C_REGC870.VL_BC_COFINS,C_REGC870.ALIQ_COFINS,'P',C_REGC870.VL_COFINS,C_REGC870.CST_PIS,C_REGC860.CDFILIAL,'','0',C_REGC870.VL_ITEM,C_REGC870.CDNATUREC,C_REGC870.COD_CTA); 
            END IF; 
 
            V_PRODUTO:=NULL; 
 
             
            SELECT MAX(CDCHAVEREG) 
              INTO V_PRODUTO 
              FROM TMP_REGDADOSSPED_PIS 
             WHERE CDCHAVEREG = C_REGC870.COD_ITEM 
               AND CDREGISTRO = '0200' 
               AND CDESTAB = LTRIM(TO_CHAR(V_ESTABELE,'000')); 
 
            IF (V_PRODUTO IS NULL) AND (C_REGC870.COD_ITEM IS NOT NULL) THEN 
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1; 
               INSERT INTO TMP_REGDADOSSPED_PIS 
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB, CDCAMPO4) 
               VALUES 
                  ('0200', V_SEQUPROD, C_REGC870.COD_ITEM, NULL, LTRIM(TO_CHAR(V_ESTABELE,'000')), C_REGC870.CDCLASFISC); 
            END IF; 
 
            V_UNID:= null; 
             
            SELECT MAX(CDCHAVEREG) 
              INTO V_UNID 
              FROM TMP_REGDADOSSPED_PIS 
             WHERE CDCHAVEREG = C_REGC870.SGUNIDADE 
               AND CDREGISTRO = '0190' 
               AND CDESTAB = LTRIM(TO_CHAR(V_ESTABELE,'000')); 
 
            IF (V_UNID IS NULL) AND (C_REGC870.SGUNIDADE IS NOT NULL) THEN 
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1; 
               INSERT INTO TMP_REGDADOSSPED_PIS 
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB) 
               VALUES 
                  ('0190', V_SEQUPROD, C_REGC870.SGUNIDADE,NULL,LTRIM(TO_CHAR(V_ESTABELE,'000'))); 
            END IF; 
 
             
            BEGIN 
               SELECT MAX(CDCHAVEREG) 
                 INTO V_COD_CC 
                 FROM TMP_REGDADOSSPED_PIS 
                WHERE CDCHAVEREG = C_REGC870.COD_CTA 
                  AND CDREGISTRO = '0500'; 
            EXCEPTION 
               WHEN NO_DATA_FOUND THEN 
                  V_COD_CC := NULL; 
            END; 
 
            IF (V_COD_CC IS NULL) AND (C_REGC870.COD_CTA IS NOT NULL) THEN 
               V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1; 
               INSERT INTO TMP_REGDADOSSPED_PIS 
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1) 
               VALUES 
                  ('0500', V_SEQCCTBL, C_REGC870.COD_CTA, NULL); 
            END IF; 
         END LOOP; 
      END LOOP; 
   END LOOP; 
   P_COUNTA    := V_COUNTBCL0; 
   P_CONTESTAB := V_CONTEST; 
   RETURN(V_CONTREGA); 
END;
/
                             
CREATE OR REPLACE FUNCTION SPED_PIS_COFINS_BLOCO0(
   P_CDEMPRESA    IN EMPRESA.CDEMPRESA%TYPE,
   P_NRSEQARQMAG  IN ARQMAGPISCOFINS.NRSEQARQMAG%TYPE,
   P_DTINICIAL    IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DTFINAL      IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_VERSAO       IN VARCHAR2,
   P_TPESCRITU    IN NOTAFISCAL.IDSTATUS%TYPE,
   P_IDSITUESP    IN NOTAFISCAL.IDSTATUS%TYPE,
   P_NUMRECANT    IN VARCHAR2,
   P_TPNATJURPJ   IN NOTAFISCAL.CDMODDOCFISC%TYPE,
   P_ATIVIDADE    IN NOTAFISCAL.IDSTATUS%TYPE,
   P_CDINCTRIB    IN NOTAFISCAL.IDSTATUS%TYPE,
   P_INDAPROCRED  IN NOTAFISCAL.IDSTATUS%TYPE,
   P_CDTPCON      IN NOTAFISCAL.IDSTATUS%TYPE,
   P_CRTESCRITUR  IN NOTAFISCAL.IDSTATUS%TYPE,
   P_LIVROMAG     IN RELACPRODITGEN.CDLIVROMAG%TYPE,
   P_GERABCLP     IN VARCHAR2,
   P_CDPAIS       IN PAIS.CDPAIS%TYPE,
   P_ICMS         IN IMPOSTO.CDIMPOSTO%TYPE,
   P_IPI          IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ISS_E        IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ISS_S        IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ISS_RET_E    IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ISS_RET_S    IN IMPOSTO.CDIMPOSTO%TYPE,
   P_PIS          IN IMPOSTO.CDIMPOSTO%TYPE,
   P_PIS_RET_E    IN IMPOSTO.CDIMPOSTO%TYPE,
   P_PIS_RET_S    IN IMPOSTO.CDIMPOSTO%TYPE,
   P_COFINS       IN IMPOSTO.CDIMPOSTO%TYPE,
   P_COFINS_RET_E IN IMPOSTO.CDIMPOSTO%TYPE,
   P_COFINS_RET_S IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ICMS_ST      IN IMPOSTO.CDIMPOSTO%TYPE,
   P_NATUJURID    IN VARCHAR2) RETURN NUMBER
AS
   V_REG_0000       VARCHAR2(1000);
   V_REG_0110       VARCHAR2(1000);
   V_REG_0140       VARCHAR2(1000);
   V_REG_A001       VARCHAR2(100);
   V_REG_C001       VARCHAR2(100);
   V_REG_D001       VARCHAR2(100);
   V_REG_M001       VARCHAR2(100);
   V_REG_F001       VARCHAR2(100);
   V_REG_P001       VARCHAR2(100);
   V_CNPJ_0140      VARCHAR2(20);
   V_INSJUREST      VARCHAR2(20);
   V_OLDESTAB       VARCHAR2(20);
   V_CONTEST        NUMBER;
   V_NEWESTAB       NUMBER;
   V_TOTLINHAS      NUMBER;
   V_TOTBLC0        NUMBER;
   V_TOTBLCA        NUMBER;
   V_TOTBLCC        NUMBER;
   V_TOTBLCD        NUMBER;
   V_TOTBLCM        NUMBER;
   V_TOTBLCP        NUMBER;
   V_SEQNOTAS       NUMBER;
   V_SEQESTAB       NUMBER;
   V_CONTREGA       NUMBER;
   V_IDNOVOESTA     VARCHAR2(1);
   V_IDNOVOESTC     VARCHAR2(1);
   V_IDNOVOESTD     VARCHAR2(1);
   VDIMPISS         VARCHAR2(2);
   VDIMPICMS        VARCHAR2(2);
   V_SGESTEMPR      VARCHAR2(2);
   V_CDPAISEMPR     VARCHAR2(4);
   V_CDMUNIEMPR     VARCHAR2(4);
   V_PRODUTO        VARCHAR(100);
   V_UNID           VARCHAR(4);
   TIPOOPER_COMPL_S VARCHAR2(2);
   TIPOOPER_COMPL_E VARCHAR2(2);
   V_RESULTADO      VARCHAR2(100);
   IDGEROUBCLACD    VARCHAR2(1);
   V_REG            VARCHAR2(1000);
   V_SEQA           NUMBER;
   V_SEQC           NUMBER;
   V_SEQD           NUMBER;
   V_TMPBLCM        NUMBER;
   V_TOTALBCLF      NUMBER;
   V_SEQESTABBLCF   NUMBER;
   V_IDOUTROS       VARCHAR2(1);
   V_VRDESTOTIT     FLOAT;
   V_VROUTDESPIT    FLOAT;
   V_FRETE          FLOAT;
   V_DESCONTO       FLOAT;
   V_OUTROS         FLOAT;
   V_SEGUR          FLOAT;
   V_COUNTBL0ECF    NUMBER;
   V_COUNTBL0P      NUMBER;
   V_CNPJ_REAL      VARCHAR2(20);
   V_CONTREG1       NUMBER;
   V_SEMMOVIMENTO   VARCHAR2(1);
   V_SEQVENDAS      NUMBER;
   V_GERADEVOLVEND  VARCHAR2(1);
   V_NRSEQUMAPPIS   VARCHAR2(10);
   V_COD_CC         VARCHAR2(20);
   V_SEQCCTBL       NUMBER;
   V_CONTBLC0M      NUMBER;
BEGIN
   V_TMPBLCM := 0;
   V_SEQESTAB:= 0;
   BEGIN
      SELECT CDPAIS,SGESTADO, CDMUNICIPIO
        INTO V_CDPAISEMPR, V_SGESTEMPR, V_CDMUNIEMPR
        FROM EMPRESA
       WHERE CDEMPRESA = P_CDEMPRESA;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_CDPAISEMPR:= '55';
         V_SGESTEMPR:= 'MG';
         V_CDMUNIEMPR:= '0001';
   END;
   BEGIN
      SELECT MAX(IDDEVOLNCUMUSPED)
        INTO V_GERADEVOLVEND
        FROM PARAMFISCAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
        V_GERADEVOLVEND := 'A';
   END;
   /*SELECTIONA O TIPO DE OPERAÇÃO DE NOTAS FISCAIS COMPLEMENTARES QUE SEJAM DIFERENTES DE 03. TIPO DE OPERAÇÃO 03 JÁ É FIXO NO SISTEMA COM COMPLEMENTAR*/
   SELECT MAX(TIPOOPER_S), MAX(TIPOOPER_E)
     INTO TIPOOPER_COMPL_S, TIPOOPER_COMPL_E
     FROM (SELECT DECODE(IDENTRSAIDOP,'S',CDTIPOOPER,NULL) AS TIPOOPER_S,
                  DECODE(IDENTRSAIDOP,'E',CDTIPOOPER,NULL) AS TIPOOPER_E
             FROM TIPOOPERAC
            WHERE UPPER(NMTIPOOPER) LIKE '%NF COMPLEMENTO%'
              AND CDTIPOOPER <> '03');
  /*REGISTRO 0000*/
   BEGIN
      SELECT '|0000'                         ||'|'||
             P_VERSAO                        ||'|'||
             P_TPESCRITU                     ||'|'||
             P_IDSITUESP                     ||'|'||
             P_NUMRECANT                     ||'|'||
             TO_CHAR(P_DTINICIAL,'ddmmyyyy') ||'|'||
             TO_CHAR(P_DTFINAL,'ddmmyyyy')   ||'|'||
             NMRAZSOCEMPR                    ||'|'||
             NRINSJUREMPR                    ||'|'||
             E.SGESTADO                      ||'|'||
             M.CDMUNICIBGE                   ||'|'||
             ''                              ||'|'||
             P_NATUJURID                     ||'|'||
             P_ATIVIDADE                     ||'|'
        INTO V_REG_0000
        FROM EMPRESA E, MUNICIPIO M
       WHERE E.CDPAIS      = M.CDPAIS
         AND E.SGESTADO    = M.SGESTADO
         AND E.CDMUNICIPIO = M.CDMUNICIPIO
         AND E.CDEMPRESA   = P_CDEMPRESA;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_REG_0000 := '';
   END;
   V_TOTBLC0   := NVL(V_TOTBLC0,  0)+1;
   V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,LPAD('0',10,'0'),V_REG_0000);
   /*REGISTRO 0001*/
   V_TOTBLC0   := NVL(V_TOTBLC0,  0)+1;
   V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'101'||LPAD('0',7,'0'),'|0001|0|');
   /* GERAÇÃO DO REGISTRO 0035 SOMENTE PARA AS NATUREZAS JURÍDIAS 03 E 04 */
   IF P_NATUJURID IN ('03', '04') THEN
      FOR C_0035 IN (SELECT '|0035' ||'|'||
                            REPLACE(REPLACE(REPLACE(CODSCP,'-',''),'/',''),'.','') ||'|'||
                            DESCSCP ||'|'||
                            INFCOMP ||'|' AS REGISTRO
                       FROM SCPEMPRESA
                      WHERE CDEMPRESA = P_CDEMPRESA) LOOP
         V_TOTBLC0   := NVL(V_TOTBLC0,  0)+1;
         V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
         INSERT INTO ARQMAGPISCOFINS
           (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
           (P_NRSEQARQMAG,'101'||LPAD('0',8,'0'),C_0035.REGISTRO);
      END LOOP;
   END IF;
   /*Registro 0100*/
   FOR REG_0100 IN(SELECT ('|0100'                                    || '|' ||
                          NMCONTADOR                                || '|' ||
                          NRCPFRESPONS                              || '|' ||
                          REPLACE(REPLACE(NRCRCCONT2,'/',''),'-','')|| '|' ||
                          ''                                        || '|' ||
                          REPLACE(REPLACE(NRCEP,'/',''),'-','')     || '|' ||
                          LTRIM(RTRIM(DSLOGRADOURO))                || '|' ||
                          ''                                        || '|' ||
                          LTRIM(RTRIM(DSCOMPLLOGRA))                || '|' ||
                          LTRIM(RTRIM(DSBAIRRO))                    || '|' ||
                          SUBSTR(RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(NRTELCONTATO, '(',''),')','') ,'-',''))),1,10)  || '|' ||
                          SUBSTR(RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(NRFAXCONTATO, '(',''),')','') ,'-',''))),1,10)  || '|' ||
                          DSENDINTERN                               || '|' ||
                          M.CDMUNICIBGE                             || '|'  ) ARQ_0100
                     FROM CONTADOR C, MUNICIPIO M, EMPRESA E
                    WHERE E.CDCONTADOR2 = C.CDCONTADOR2
                      AND C.CDPAIS      = M.CDPAIS
                      AND C.CDMUNICIPIO = M.CDMUNICIPIO
                      AND C.SGESTADO    = M.SGESTADO
                      AND E.CDEMPRESA   = P_CDEMPRESA)LOOP
      V_TOTBLC0   := NVL(V_TOTBLC0,  0)+1;
      V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'102'||LPAD(RTRIM(V_TOTLINHAS),27,'0'),REG_0100.ARQ_0100);
   END LOOP;
   /*REGISTRO 0110*/
   V_REG_0110 := '|0110'        ||'|'||
                 P_CDINCTRIB    ||'|'||
                 P_INDAPROCRED  ||'|'||
                 P_CDTPCON      ||'|';
   /*Campo critério da escrituração a ser importado pelo PVA*/
   IF P_VERSAO NOT IN ('001','002') THEN
      IF P_CDINCTRIB = '2' THEN
         V_REG_0110:= V_REG_0110||P_CRTESCRITUR||'|';
      ELSE
         V_REG_0110:= V_REG_0110||'|';
      END IF;
   END IF;
   V_TOTBLC0   := NVL(V_TOTBLC0,  0)+1;
   V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'103'||LPAD(RTRIM(V_TOTLINHAS),22,'0'),V_REG_0110);
   /*SELECT QUE BUSCA AS NOTAS QUE IRÃO COMPOR O ARQUIVO - PRINCIPAL*/
   FOR C_NOTAS IN (SELECT NRLANCTONF, CDFILIAL, ESTAB
                     FROM (SELECT DISTINCT NF.NRLANCTONF, NF.CDFILIAL,
                                  BUSCA_CNPJ_ESTAB(P_ICMS,P_ISS_E,P_ISS_S,P_ISS_RET_E,P_ISS_RET_S,NF.NRLANCTONF,NF.CDFILIAL,NF.CDINSCESTA,NF.CDINSCMUNI,NF.CDFILIEMIT,NF.CDFILIRECE,NF.IDENTRSAIDOP) AS ESTAB
                             FROM NOTAFISCAL NF, FILIAL F, CFOPPADRAO C, (SELECT IP.CDFILIAL, IP.NRLANCTONF, IP.CDFISCOPERNF
                                                                            FROM MAPAAPURAC MP, IMPOSTONF IP, IMPOSTO IM
                                                                           WHERE MP.CDEMPRESA    = P_CDEMPRESA
                                                                             AND MP.CDIMPOSTO    IN (P_PIS,P_COFINS)
                                                                             AND MP.DTINIPERIODO = P_DTINICIAL
                                                                             AND MP.DTFIMPERIODO = P_DTFINAL
                                                                             AND MP.NRSEQUMAPAPU = IP.NRSEQUMAPAPU
                                                                             AND MP.CDIMPOSTO    = IM.CDIMPOSTONFE
                                                                             AND IM.CDIMPOSTO    = IP.CDIMPOSTO
                                                                           UNION ALL
                                                                          SELECT IB.CDFILIAL, IB.NRLANCTONF, IB.CDFISCOPERNF
                                                                            FROM MAPAAPURAC MP, IMPBAIXAREC IB, IMPOSTO IM
                                                                           WHERE MP.CDEMPRESA    = P_CDEMPRESA
                                                                             AND MP.CDIMPOSTO    IN (P_PIS,P_COFINS)
                                                                             AND MP.DTINIPERIODO = P_DTINICIAL
                                                                             AND MP.DTFIMPERIODO = P_DTFINAL
                                                                             AND MP.NRSEQUMAPAPU = IB.NRSEQUMAPAPU
                                                                             AND MP.CDIMPOSTO    = IM.CDIMPOSTONFE
                                                                             AND IM.CDIMPOSTO    = IB.CDIMPOSTO) IP
                            WHERE IP.CDFILIAL     = NF.CDFILIAL
                              AND IP.NRLANCTONF   = NF.NRLANCTONF
                              AND (NF.IDSTATUS = 'A' OR IDSTATUS = 'E')
                              AND DECODE(NF.IDENTRSAIDOP,'E',NF.CDFILIRECE, NF.CDFILIEMIT) = F.CDFILIAL
                              AND ((NF.IDENTRSAIDOP = 'E' AND F.IDCUMUPISCOFIL = 'S') OR (NF.IDENTRSAIDOP = 'S' AND F.IDCUMUPISCOFIL IN ('S','N')) )
                              AND IP.CDFISCOPERNF   = C.CDCFOPPADRAO(+)
                              AND ((NVL(C.IDTIPOCFOP,'X') <> 'D') OR (((F.IDCUMUPISCOFIL = 'S') AND (NF.IDENTRSAIDOP = 'E') AND (IP.CDFISCOPERNF = C.CDCFOPPADRAO) AND (C.IDTIPOCFOP = 'D') AND (NVL(V_GERADEVOLVEND,'A') = 'C'))))     
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'REC'
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'PAG'
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'CMP'
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'SUP'
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'FIS'
                              --AND NVL(NF.IDSISTEMA, DFS) <> TMP /*As notas do TMP devem entrar no arquivo para quem utiliza regime de caixa e o ForSale*/
                              ))LOOP
         /*GRAVA TODAS A NOTAS QUE ESTÃO NO ARQUIVO*/
         V_SEQNOTAS := NVL(V_SEQNOTAS,0) + 1;
         INSERT INTO TMP_REGDADOSSPED_PIS
            (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1, CDCAMPO2, CDESTAB)
         VALUES
            ('NOTA', V_SEQNOTAS, C_NOTAS.CDFILIAL||C_NOTAS.NRLANCTONF, C_NOTAS.CDFILIAL, C_NOTAS.NRLANCTONF, C_NOTAS.ESTAB);
         END LOOP;
   /*SELECT QUE BUSCA AS NOTAS FISCAIS ELETRÔNICAS AO CONSUMIDOR FINAL (NFC-e) QUE IRÃO COMPOR O ARQUIVO - PRINCIPAL*/
   FOR C_VENDAS IN (SELECT NRSEQVENDA, CDFILIAL, CDCAIXA,
                           LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(NRINSJURFILI,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0')||'ICM' AS ESTAB,
                           IDTPEMISVEND
                      FROM (SELECT DISTINCT VE.NRSEQVENDA, VE.CDFILIAL, VE.CDCAIXA, FI.NRINSJURFILI, VE.IDTPEMISVEND
                              FROM VENDA VE, FILIAL FI, MAPAAPURAC MP
                             WHERE MP.CDEMPRESA       = P_CDEMPRESA
                               AND MP.CDIMPOSTO       IN (P_PIS,P_COFINS)
                               AND MP.DTINIPERIODO    = P_DTINICIAL
                               AND MP.DTFIMPERIODO    = P_DTFINAL
                               AND FI.CDEMPRESA       = MP.CDEMPRESA
                               AND FI.CDFILIAL        = VE.CDFILIAL
                               AND TRUNC(VE.DTEMISSAONFCE) BETWEEN MP.DTINIPERIODO AND MP.DTFIMPERIODO
                               AND VE.IDSITUVENDA     = 'O'
                               AND VE.IDTPAMBNFCE     = '1'
                               AND VE.IDSTATUSNFCE    IN ('A','C')
                               AND VE.IDAPROVACAONFCE = 'A'
                               AND VE.IDTPEMISVEND    = 'N'
                             UNION 
                            SELECT DISTINCT VE.NRSEQVENDA, VE.CDFILIAL, VE.CDCAIXA, FI.NRINSJURFILI, VE.IDTPEMISVEND
                              FROM VENDA VE, FILIAL FI, MAPAAPURAC MP
                             WHERE MP.CDEMPRESA       = P_CDEMPRESA
                               AND MP.CDIMPOSTO       IN (P_PIS,P_COFINS)
                               AND MP.DTINIPERIODO    = P_DTINICIAL
                               AND MP.DTFIMPERIODO    = P_DTFINAL
                               AND FI.CDEMPRESA       = MP.CDEMPRESA
                               AND FI.CDFILIAL        = VE.CDFILIAL
                               AND TRUNC(VE.DTEMISSAONFCE) BETWEEN MP.DTINIPERIODO AND MP.DTFIMPERIODO
                               AND VE.IDSITUVENDA     = 'O'
                               AND VE.IDTPAMBNFCE     = '1'
                               AND VE.IDSTATUSNFCE    IN ('A','C')
                               AND VE.IDAPROVACAONFCE = 'A'
                               AND VE.IDTPEMISVEND    = 'S'))LOOP
         /*GRAVA TODAS A NFC-Es QUE ESTÃO NO ARQUIVO*/
         V_SEQVENDAS := NVL(V_SEQVENDAS,0) + 1;
         INSERT INTO TMP_REGDADOSSPED_PIS
            (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1, CDCAMPO2, CDCAMPO3, CDESTAB)
         VALUES
            (DECODE(C_VENDAS.IDTPEMISVEND, 'N', 'NFCE', 'SAT'), V_SEQVENDAS, C_VENDAS.CDFILIAL||C_VENDAS.NRSEQVENDA||C_VENDAS.CDCAIXA, C_VENDAS.CDFILIAL, C_VENDAS.NRSEQVENDA, C_VENDAS.CDCAIXA, C_VENDAS.ESTAB);
         END LOOP;
   V_SEMMOVIMENTO := 'S';
   V_CONTEST      := NULL;
   IF P_GERABCLP IN ('0','1') THEN
      IF ((P_CRTESCRITUR IS NULL) OR (P_CRTESCRITUR = '9')) THEN /*ESCRITURAÇÃO DETALHADA*/
         /*BUSCA AS NOTAS PARA GERAR O ARQUIVO DE FORMA DETALHADA - BLOCOS A,C,D,F*/
         FOR C_NOTAS_DETAL IN (SELECT CDREGISTRO, NRLANCTONF, CDFILIAL, '' AS CDCAIXA, IDENTRSAIDOP,IDSTATUS,CDINSCESTA, CDINSCMUNI,
                                      CDFORNECED, CDCLIENTE, CDFILIEMIT, CDFILIRECE, CDSERIE, CDSERIEENTR, NRNOTAFISC,
                                      DTEMISSAO, DTENTRSAID, NRACESSONFE, VRNOTAFISC, VRPRODUTOS,
                                      VALOR_IMPOSTO_NFE(NF.CDFILIAL, NF.NRLANCTONF, '50','C') AS VRCONTABIL,
                                      IDPGTOFRETE, CDMODDOCFISC, SUBSTR(CDESTAB,1,LENGTH(CDESTAB)-3) AS CNPJ,
                                      SUBSTR(CDESTAB,LENGTH(CDESTAB)-2,3) AS IDIMPOSTO,
                                      CDTIPOOPER, IDSTATUSNFE, NRNOTAFISCALELE,
                                      NVL(IDORIGDESTNF, CASE WHEN CDFORNECED IS NOT NULL THEN 'F'
                                                             WHEN CDCLIENTE  IS NOT NULL THEN 'C'
                                                             WHEN CDFORNECED IS NULL AND CDCLIENTE IS NULL THEN 'L' END) AS IDORIGDESTNF,
                                      NF.CDTIPOCTE
                                 FROM TMP_REGDADOSSPED_PIS TMP, NOTAFISCAL NF
                                WHERE TMP.CDREGISTRO = 'NOTA'
                                  AND TMP.CDCAMPO1   = NF.CDFILIAL
                                  AND TMP.CDCAMPO2   = NF.NRLANCTONF
                                UNION ALL
                               SELECT TMP.CDREGISTRO, VE.NRSEQVENDA AS NRLANCTONF, VE.CDFILIAL, VE.CDCAIXA, 'S' AS IDENTRSAIDOP, VE.IDSTATUSNFCE AS IDSTATUS,
                                      FI.CDINSCESTA AS CDINSCESTA, FI.CDINSCMUNI AS CDINSCMUNI, '' AS CDFORNECED, '' AS CDCLIENTE, '' AS CDFILIEMIT, '' AS CDFILIRECE,
                                      VE.CDSERIENFCE AS CDSERIE, '' AS CDSERIEENTR, VE.NRNOTAFISCALCE AS NRNOTAFISC,
                                      TRUNC(VE.DTEMISSAONFCE) AS  DTEMISSAO, TRUNC(VE.DTEMISSAONFCE) AS DTENTRSAID, VE.NRACESSONFCE AS NRACESSONFE,
                                      SUM(TRUNC((IT.QTPRODVEND*(IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0)))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) AS VRNOTAFISC,
                                      SUM(TRUNC((IT.QTPRODVEND*(IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0)))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) AS VRPRODUTOS,
                                      SUM(TRUNC((IT.QTPRODVEND*(IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0)))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) AS VRCONTABIL,
                                      '9' AS IDPGTOFRETE, '65' AS CDMODDOCFISC, SUBSTR(CDESTAB,1,LENGTH(CDESTAB)-3) AS CNPJ, SUBSTR(CDESTAB,LENGTH(CDESTAB)-2,3) AS IDIMPOSTO,
                                      PV.CDTPOPERCNTREC AS CDTIPOOPER, VE.IDSTATUSNFCE AS IDSTATUSNFE,
                                      VE.NRNOTAFISCALCE AS NRNOTAFISCALELE, 'C' AS IDORIGDESTNF, '' AS CDTIPOCTE
                                 FROM TMP_REGDADOSSPED_PIS TMP, VENDA VE, ITEMVENDA IT, FILIAL FI, PARAVEND PV
                                WHERE TMP.CDREGISTRO = 'NFCE'
                                  AND TMP.CDCAMPO1   = VE.CDFILIAL
                                  AND TMP.CDCAMPO2   = VE.NRSEQVENDA
                                  AND TMP.CDCAMPO3   = VE.CDCAIXA
                                  AND TMP.CDCAMPO1   = IT.CDFILIAL
                                  AND TMP.CDCAMPO2   = IT.NRSEQVENDA
                                  AND TMP.CDCAMPO3   = IT.CDCAIXA
                                  AND TMP.CDCAMPO1   = FI.CDFILIAL
                                  AND TMP.CDCAMPO1   = PV.CDFILIAL
                                  AND VE.CDFILIAL    = IT.CDFILIAL
                                  AND VE.NRSEQVENDA  = IT.NRSEQVENDA
                                  AND VE.CDCAIXA     = IT.CDCAIXA
                                  AND VE.CDFILIAL    = FI.CDFILIAL
                                  AND VE.CDFILIAL    = PV.CDFILIAL
                                  AND PV.CDFILIAL    = FI.CDFILIAL
                                  AND IT.CDFILIAL    = FI.CDFILIAL
                                  AND PV.CDFILIAL    = IT.CDFILIAL
                                GROUP BY TMP.CDREGISTRO, VE.NRSEQVENDA, VE.CDFILIAL, VE.CDCAIXA, VE.IDSTATUSNFCE, FI.CDINSCESTA, FI.CDINSCMUNI,
                                         VE.CDSERIENFCE, VE.NRNOTAFISCALCE, TRUNC(VE.DTEMISSAONFCE), VE.DTENTRVENDA, VE.NRACESSONFCE,
                                         TMP.CDESTAB, PV.CDTPOPERCNTREC) LOOP
            IF C_NOTAS_DETAL.CDREGISTRO = 'NOTA' THEN
               /*BUSCA O VALOR DOS ENCARGOS*/
               /*PEGA O VALOR DO FRETE*/
               BEGIN
                  SELECT SUM(VRITEMENCA)
                    INTO V_FRETE
                    FROM ITEMENCARGO I, ENCARGO EN
                   WHERE I.CDENCARGO     = EN.CDENCARGO
                     AND EN.CDENCARGONFE = '01'
                     AND NRLANCTONF      = C_NOTAS_DETAL.NRLANCTONF
                     AND CDFILIAL        = C_NOTAS_DETAL.CDFILIAL;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_FRETE:=0;
               END;
               /*PEGA O VALOR DO SEGURO*/
               BEGIN
                  SELECT SUM(VRITEMENCA)
                    INTO V_SEGUR
                    FROM ITEMENCARGO I, ENCARGO EN
                   WHERE I.CDENCARGO     = EN.CDENCARGO
                     AND EN.CDENCARGONFE = '02'
                     AND NRLANCTONF      = C_NOTAS_DETAL.NRLANCTONF
                     AND CDFILIAL        = C_NOTAS_DETAL.CDFILIAL;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_SEGUR:=0;
               END;
               /*PEGA O VALOR DO DESCONTO*/
               BEGIN
                  SELECT SUM(VRDESCITEM)
                    INTO V_DESCONTO
                    FROM ITEMPRODUTO
                   WHERE NRLANCTONF = C_NOTAS_DETAL.NRLANCTONF
                     AND CDFILIAL   = C_NOTAS_DETAL.CDFILIAL;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_DESCONTO:=0;
               END;
               /*PEGA O VALOR DE OUTROS*/
               BEGIN
                  SELECT SUM(VRITEMENCA)
                    INTO V_OUTROS
                    FROM ITEMENCARGO I, ENCARGO EN
                   WHERE I.CDENCARGO     = EN.CDENCARGO
                     AND EN.CDENCARGONFE = '04'
                     AND NRLANCTONF      = C_NOTAS_DETAL.NRLANCTONF
                     AND CDFILIAL        = C_NOTAS_DETAL.CDFILIAL;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_OUTROS:=0;
               END;
            ELSE /*NFC-e*/
               /*BUSCA O VALOR DOS ENCARGOS*/
               V_FRETE :=0;
               V_SEGUR :=0;
               V_OUTROS:=0;
               V_INSJUREST := NULL;
               /*PEGA O VALOR DO DESCONTO*/
               BEGIN
                  SELECT SUM(VRDESITVEND)
                    INTO V_DESCONTO
                    FROM ITEMVENDA
                   WHERE NRSEQVENDA = C_NOTAS_DETAL.NRLANCTONF
                     AND CDFILIAL   = C_NOTAS_DETAL.CDFILIAL
                     AND CDCAIXA    = C_NOTAS_DETAL.CDCAIXA;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_DESCONTO:=0;
               END;
            END IF;
            SELECT MAX(LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0'))
              INTO V_CNPJ_REAL
              FROM INSCRESTAD I
             WHERE I.CDEMPRESA  = P_CDEMPRESA
               AND I.CDINSCESTA = C_NOTAS_DETAL.CDINSCESTA;
            /*VERIFICA SE O ESTABELECIMENTO JA FOI INSERIDO*/
            V_INSJUREST:= NULL;
            SELECT MAX(CDCHAVEREG),MAX(CDESTAB)
              INTO V_INSJUREST, V_OLDESTAB
              FROM TMP_REGDADOSSPED_PIS TMP
             WHERE CDREGISTRO = '0140'
               AND CDCHAVEREG = V_CNPJ_REAL;
            /*LEMBRAR QUE O REGISTRO 0140 TAMBEM  INSERIDO NA FUNCAO SPED_PIS_COFINS_BLOCOC_ECF*/
            /*GERA O REGISTRO 0140 - ESTABELECIMENTO*/
            IF V_INSJUREST IS NULL THEN
               /*ACRESCE UM NO NUMERO DO ESTABELECIMENTO*/
               V_CONTEST:= NVL(V_CONTEST,0)+1;
               V_NEWESTAB:= V_CONTEST;
               BEGIN
                  SELECT REG, INSJUREST
                    INTO V_REG, V_INSJUREST
                    FROM (SELECT '|0140'         ||'|'||
                                 LTRIM(TO_CHAR(V_NEWESTAB,'000'))      ||'|'||
                                 E.NMRAZSOCEMPR  ||'|'||
                                 LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0') ||'|'||
                                 I.SGESTADO     ||'|'||
                                 ''/*REPLACE(REPLACE(REPLACE(REPLACE(IE.CDINSCESTA,.,),/,),-,),\,)*/ ||'|'||
                                 M.CDMUNICIBGE   ||'|'||
                                 ''             ||'|'||
                                 ''             ||'|' AS REG,
                                 LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0') AS INSJUREST
                            FROM MUNICIPIO M, INSCRESTAD I, EMPRESA E
                           WHERE I.CDEMPRESA    = P_CDEMPRESA
                             AND I.CDINSCESTA   = C_NOTAS_DETAL.CDINSCESTA
                             AND I.CDPAIS       = M.CDPAIS
                             AND I.SGESTADO     = M.SGESTADO
                             AND I.CDMUNICIPIO  = M.CDMUNICIPIO
                             AND E.CDEMPRESA    = I.CDEMPRESA);
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_REG:= C_NOTAS_DETAL.CDINSCESTA||'-'||C_NOTAS_DETAL.NRLANCTONF||'-'||C_NOTAS_DETAL.CDFILIAL;
                     V_INSJUREST:='';
               END;
               INSERT INTO ARQMAGPISCOFINS
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
               VALUES
                  (P_NRSEQARQMAG,'104'||LTRIM(TO_CHAR(V_CONTEST,'000')),V_REG);
               V_SEQESTAB:= NVL(V_SEQESTAB,0)+1;
               V_CONTREGA:= NVL(V_CONTREGA,0)+1;
               V_TOTBLC0:= NVL(V_TOTBLC0,0)+1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
                VALUES
                 ('0140', V_SEQESTAB, V_INSJUREST ,NULL,LTRIM(TO_CHAR(V_CONTEST,'000')));
            ELSE
               V_NEWESTAB:= TO_NUMBER(V_OLDESTAB);
            END IF;
            /*VARIAVEL IDENTIFICA SE GEROU O BLOCO A,C,E -  SE NAO GERAR GERA PELO BLOCO F */
            IDGEROUBCLACD:= 'N';
            IF C_NOTAS_DETAL.IDIMPOSTO = 'ICM' THEN
               IF C_NOTAS_DETAL.CDMODDOCFISC IN ('01','1B','04','55','02','06','29','28','65') THEN
                  /*BLOCO C*/
                  V_RESULTADO:= NVL(SPED_PIS_COFINS_BLOCOC(C_NOTAS_DETAL.NRLANCTONF, C_NOTAS_DETAL.CDFILIAL, C_NOTAS_DETAL.CDCAIXA,
                                                           P_NRSEQARQMAG,V_INSJUREST,V_IDNOVOESTC,
                                                           C_NOTAS_DETAL.IDENTRSAIDOP,C_NOTAS_DETAL.IDSTATUS,
                                                           C_NOTAS_DETAL.IDORIGDESTNF,C_NOTAS_DETAL.CDFILIEMIT,
                                                           C_NOTAS_DETAL.CDFILIRECE,C_NOTAS_DETAL.CDCLIENTE,
                                                           C_NOTAS_DETAL.CDFORNECED,NVL(C_NOTAS_DETAL.CDSERIE, C_NOTAS_DETAL.CDSERIEENTR),
                                                           C_NOTAS_DETAL.NRNOTAFISC,C_NOTAS_DETAL.DTEMISSAO,C_NOTAS_DETAL.DTENTRSAID,
                                                           C_NOTAS_DETAL.VRNOTAFISC,C_NOTAS_DETAL.VRCONTABIL, P_PIS,P_PIS_RET_E,P_PIS_RET_S,
                                                           P_COFINS,P_COFINS_RET_E,P_COFINS_RET_S,P_ISS_E,P_ISS_S,P_ISS_RET_E,P_ISS_RET_S,
                                                           V_NEWESTAB,P_CDPAIS, P_CDEMPRESA,NVL(V_SEQC,0),C_NOTAS_DETAL.IDPGTOFRETE,
                                                           C_NOTAS_DETAL.NRACESSONFE, C_NOTAS_DETAL.CDMODDOCFISC,C_NOTAS_DETAL.VRPRODUTOS,
                                                           P_ICMS_ST,P_IPI,P_ICMS,P_DTINICIAL,P_DTFINAL,V_DESCONTO,C_NOTAS_DETAL.CDTIPOOPER,
                                                           C_NOTAS_DETAL.IDSTATUSNFE, V_FRETE,V_OUTROS,V_SEGUR,TIPOOPER_COMPL_S,
                                                           TIPOOPER_COMPL_E,V_SEQESTAB,V_TMPBLCM,C_NOTAS_DETAL.NRNOTAFISCALELE,
                                                           P_LIVROMAG,V_GERADEVOLVEND),0);
                  V_TOTBLCC  := TO_NUMBER(SUBSTR(V_RESULTADO,1,20));
                  V_SEQESTAB := NVL(V_SEQESTAB, 0) + TO_NUMBER(SUBSTR(V_RESULTADO,22,20));
                  V_TMPBLCM  := NVL(V_TMPBLCM, 0)  + TO_NUMBER(SUBSTR(V_RESULTADO,43,20));
                  V_SEQC     := NVL(V_TOTBLCC,0);
                  IDGEROUBCLACD:= 'S';
                  /*V_IDNOVOESTC:= N;*/
               END IF;
            END IF;
            /*GERA BLOCO A*/
            IF C_NOTAS_DETAL.IDIMPOSTO = 'ISS' THEN
               V_RESULTADO:= NVL(SPED_PIS_COFINS_BLOCOA(C_NOTAS_DETAL.NRLANCTONF, C_NOTAS_DETAL.CDFILIAL,
                                                        P_NRSEQARQMAG,V_INSJUREST,V_IDNOVOESTA,
                                                        C_NOTAS_DETAL.IDENTRSAIDOP,C_NOTAS_DETAL.CDTIPOOPER,
                                                        C_NOTAS_DETAL.IDSTATUS, C_NOTAS_DETAL.IDORIGDESTNF,
                                                        C_NOTAS_DETAL.CDFILIEMIT,C_NOTAS_DETAL.CDFILIRECE,
                                                        C_NOTAS_DETAL.CDCLIENTE,C_NOTAS_DETAL.CDFORNECED,
                                                        NVL(C_NOTAS_DETAL.CDSERIE, C_NOTAS_DETAL.CDSERIEENTR),
                                                        C_NOTAS_DETAL.NRNOTAFISC,C_NOTAS_DETAL.DTEMISSAO,C_NOTAS_DETAL.DTENTRSAID,
                                                        C_NOTAS_DETAL.VRNOTAFISC,P_PIS,P_PIS_RET_E,P_PIS_RET_S,P_COFINS,P_COFINS_RET_E,P_COFINS_RET_S,P_ISS_E,P_ISS_S,P_ISS_RET_E,P_ISS_RET_S,V_NEWESTAB,P_CDPAIS,
                                                        P_CDEMPRESA,NVL(V_SEQA,0),V_VRDESTOTIT,V_SEQESTAB,V_TMPBLCM,P_LIVROMAG),0);
               V_TOTBLCA  := TO_NUMBER(SUBSTR(V_RESULTADO,1,20));
               V_SEQA     := NVL(V_TOTBLCA,0);
               V_SEQESTAB := NVL(V_SEQESTAB, 0) + TO_NUMBER(SUBSTR(V_RESULTADO,22,20));
               V_TMPBLCM  := NVL(V_TMPBLCM, 0)  + TO_NUMBER(SUBSTR(V_RESULTADO,43,20));
               IDGEROUBCLACD:= 'S';
            END IF;
            IF C_NOTAS_DETAL.CDMODDOCFISC IN ('07','08','09','10','11','26','27','57','67','21','22')  AND C_NOTAS_DETAL.IDENTRSAIDOP = 'E' AND C_NOTAS_DETAL.IDIMPOSTO = 'ICM' THEN
               /*GERA BLOCO D*/
               V_RESULTADO:= NVL(SPED_PIS_COFINS_BLOCOD(C_NOTAS_DETAL.NRLANCTONF, C_NOTAS_DETAL.CDFILIAL,
                                                        P_NRSEQARQMAG,V_INSJUREST,V_IDNOVOESTD,
                                                        C_NOTAS_DETAL.IDENTRSAIDOP,C_NOTAS_DETAL.CDTIPOOPER,
                                                        C_NOTAS_DETAL.IDSTATUS, C_NOTAS_DETAL.IDORIGDESTNF,
                                                        C_NOTAS_DETAL.CDFILIEMIT, C_NOTAS_DETAL.CDFILIRECE,
                                                        C_NOTAS_DETAL.CDCLIENTE, C_NOTAS_DETAL.CDFORNECED,
                                                        NVL(C_NOTAS_DETAL.CDSERIE, C_NOTAS_DETAL.CDSERIEENTR),
                                                        C_NOTAS_DETAL.NRNOTAFISC,C_NOTAS_DETAL.DTEMISSAO,C_NOTAS_DETAL.DTENTRSAID,
                                                        C_NOTAS_DETAL.VRNOTAFISC,P_PIS,P_PIS_RET_E,P_PIS_RET_S,P_COFINS,P_COFINS_RET_E,
                                                        P_COFINS_RET_S,P_ISS_E,P_ISS_S,P_ISS_RET_E,P_ISS_RET_S,V_NEWESTAB,P_CDPAIS,
                                                        P_CDEMPRESA,NVL(V_SEQD,0),P_ICMS,P_DTFINAL,P_DTINICIAL,C_NOTAS_DETAL.CDMODDOCFISC,
                                                        V_VRDESTOTIT,V_IDOUTROS,V_SEQESTAB,V_TMPBLCM,C_NOTAS_DETAL.NRACESSONFE,
                                                        C_NOTAS_DETAL.CDTIPOCTE),0);
               V_TOTBLCD  := TO_NUMBER(SUBSTR(V_RESULTADO,1,20));
               V_SEQD     := NVL(V_TOTBLCD,0);
               V_SEQESTAB := NVL(V_SEQESTAB, 0) + TO_NUMBER(SUBSTR(V_RESULTADO,22,20));
               V_TMPBLCM  := NVL(V_TMPBLCM, 0)  + TO_NUMBER(SUBSTR(V_RESULTADO,43,20));
               IDGEROUBCLACD:= 'S';
               /*V_IDNOVOESTD:= N;*/
            END IF;
            /*VEFIFICA SE A NOTA FOI GERADA NOS BLOCOS A, C OU D. CASO NAO TENHA SIDO GERADA INSERE O LANCAMENTO PARA GERAR PELO BLOCO F*/
            IF IDGEROUBCLACD = 'N' THEN
               --V_SEQESTAB:= NVL(V_SEQESTAB,0)+1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDCAMPO2, CDCAMPO3, CDESTAB)
               VALUES
                  ('F100', V_SEQESTAB, C_NOTAS_DETAL.CDFILIAL||C_NOTAS_DETAL.NRLANCTONF,C_NOTAS_DETAL.CDFILIAL,C_NOTAS_DETAL.NRLANCTONF, C_NOTAS_DETAL.IDIMPOSTO,'0000');
            END IF;
            V_SEMMOVIMENTO := 'N';
         END LOOP;/*END C_NOTAS_DETAL*/
   ---------------------------------------   /*GERA O REGISTRO C380 - NOTAS FISCAIS MODELO 02*/------------------------------------------------------------
         FOR C_REGC380 IN (SELECT '|C380'                                   ||'|'||
                                  '02'                                      ||'|'||
                                  TO_CHAR(DTEMISSAO,'ddmmyyyy')             ||'|'||
                                  TO_CHAR(DTEMISSAO,'ddmmyyyy')             ||'|'||
                                  SUBSTR(LPAD(MIN(MIN_NUM_DOC),10,'0'),5,6) ||'|'||
                                  SUBSTR(LPAD(MIN(MAX_NUM_DOC),10,'0'),5,6) ||'|'||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(SUM(VRNOTAFISC),2), '999999999990.00')), '.', ',')       || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(SUM(CANC_VRNOTAFISC),2), '999999999990.00')), '.', ',')  || '|' AS C380,
                                  ESTABELECIMENTO,DTEMISSAO, MAX(CDFILIEMIT) AS CDFILIEMIT,NRINSJUREST
                             FROM (SELECT SUM(CDCAMPO8) AS VRNOTAFISC, DECODE(CDCAMPO3,'C',SUM(CDCAMPO8),0) AS CANC_VRNOTAFISC,
                                          MIN(CDCAMPO6) AS  MIN_NUM_DOC, MAX(CDCAMPO6) AS MAX_NUM_DOC,
                                          TO_DATE(CDCAMPO1) AS DTEMISSAO, CDESTAB AS ESTABELECIMENTO, MAX(CDCAMPO7) AS CDFILIEMIT,NRINSJUREST
                                     FROM TMP_REGDADOSSPED_PIS
                                    WHERE CDREGISTRO = 'C380'
                                    GROUP BY CDCAMPO1,CDCAMPO3,CDESTAB,NRINSJUREST)
                            GROUP BY DTEMISSAO,ESTABELECIMENTO,NRINSJUREST)LOOP
            V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'))||'02'||LPAD(RTRIM(V_TOTLINHAS),22,'0'),C_REGC380.C380);
            V_SEQC:= NVL(V_SEQC,0)+1;
            /*REGISTRO C381*/
            FOR REGC381 IN (SELECT '|C381'                  ||'|'||
                                   CDSITUTRIBITNFE          ||'|'||
                                   CDARVPROD                ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(VRTOTAITEM),'9999999999900.00')),'.',',') ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(VRBASECALCIT),'9999999999900.00')),'.',',')||'|'||
                                   REPLACE(LTRIM(TO_CHAR(VRALIQITEM,'9900.0000')),'.',',')||'|'||
                                   ''                                                                                    ||'|'||
                                   ''                                                                                    ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(VRIMPOSTOIT),'9999999999900.00')),'.',',')||'|'||
                                   CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,CDFILIEMIT) ||'|'/*CÓDIGO DA CONTA ANALÍTICA*/ AS C381,
                                   CDNATUBCALPCIT, CDTPCREDPICOITE, CDSITUTRIBITNFE, CDARVPROD, SGUNIDADE, CDNATUREC, SUM(VRTOTAITEM) AS VRTOTAITEM,
                                   SUM(VRBASECALCIT) AS VRBASECALCIT, SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,VRALIQITEM, MAX(CDFILIEMIT) AS CDFILIEMIT,
                                   CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,CDFILIEMIT) AS COD_CTA
                              FROM (SELECT ROUND(IP.VRTOTAITEM,2) AS VRTOTAITEM,
                                           CDTPCREDPICOITE,
                                           DECODE(CDFISCALIT,'1',VRBASECALCIT,0) AS VRBASECALCIT ,
                                           ROUND(VRALIQITEM,4) AS VRALIQITEM,
                                           ROUND(DECODE(CDFISCALIT,'1',VRIMPOSTOIT,0),2) AS VRIMPOSTOIT,
                                           CDNATUBCALPCIT,
                                           CDSITUTRIBITNFE,
                                           P.CDARVPROD AS CDARVPROD,
                                           SGUNIDADE,
                                           CDFISCALIT,
                                           CDNATUREC,
                                           CDCAMPO7 AS CDFILIEMIT,
                                           P.CDPRODUTO,
                                           CDCAMPO9 AS CDTIPOOPER
                                      FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, PRODUTO P, TMP_REGDADOSSPED_PIS TMP, IMPOSTO IM, RELACPRODITGEN R
                                     WHERE IT.CDIMPOSTO    = IM.CDIMPOSTO
                                       AND IM.CDIMPOSTONFE = P_PIS
                                       AND IT.NRLANCTONF   = IP.NRLANCTONF
                                       AND IT.CDFILIAL     = IP.CDFILIAL
                                       AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                                       AND IT.NRITPROIMPOS = '1'
                                       AND P.CDPRODUTO     = IP.CDPRODUTO
                                       AND TMP.CDREGISTRO  = 'C380'
                                       AND TMP.CDCAMPO4    = IT.CDFILIAL
                                       AND TMP.CDCAMPO5    = IT.NRLANCTONF
                                       AND TMP.CDCAMPO4    = IP.CDFILIAL
                                       AND TMP.CDCAMPO5    = IP.NRLANCTONF
                                       AND TMP.CDESTAB     = C_REGC380.ESTABELECIMENTO
                                       AND TMP.CDCAMPO1    = C_REGC380.DTEMISSAO
                                       AND P.CDPRODUTO     = R.CDPRODUTO(+)
                                       AND P_LIVROMAG      = R.CDLIVROMAG(+))
                                     GROUP BY CDNATUBCALPCIT, CDTPCREDPICOITE, CDSITUTRIBITNFE, CDARVPROD, SGUNIDADE,CDNATUREC,
                                           VRALIQITEM, CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,CDFILIEMIT))LOOP
               V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
               INSERT INTO ARQMAGPISCOFINS
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
               VALUES
                  (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'))||'02'||LPAD(RTRIM(V_TOTLINHAS),22,'0'),REGC381.C381);
               V_SEQC   := NVL(V_SEQC,0)+1;
               V_PRODUTO:=NULL;
               /* CODIGO DO PRODUTO */
               SELECT MAX(CDCHAVEREG)
                 INTO V_PRODUTO
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = REGC381.CDARVPROD
                  AND CDREGISTRO = '0200'
                  AND CDESTAB = LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'));
               IF (V_PRODUTO IS NULL) AND (REGC381.CDARVPROD IS NOT NULL) THEN
                  V_SEQESTAB := NVL(V_SEQESTAB,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
                  VALUES
                     ('0200', V_SEQESTAB, REGC381.CDARVPROD,NULL,LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000')));
               END IF;
               V_UNID:= NULL;
               /* UNIDADE DE MEDIDA */
               SELECT MAX(CDCHAVEREG)
                 INTO V_UNID
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = REGC381.SGUNIDADE
                  AND CDREGISTRO = '0190'
                  AND CDESTAB = LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'));
               IF (V_UNID IS NULL) AND (REGC381.SGUNIDADE IS NOT NULL) THEN
                  V_SEQESTAB := NVL(V_SEQESTAB,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
                  VALUES
                     ('0190', V_SEQESTAB, REGC381.SGUNIDADE,NULL,LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000')));
               END IF;
               /* CODIGO DA CONTA CONTÁBIL */
               BEGIN
                  SELECT MAX(CDCHAVEREG)
                    INTO V_COD_CC
                    FROM TMP_REGDADOSSPED_PIS
                   WHERE CDCHAVEREG = REGC381.COD_CTA
                     AND CDREGISTRO = '0500';
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_COD_CC := NULL;
               END;
               IF (V_COD_CC IS NULL) AND (REGC381.COD_CTA IS NOT NULL) THEN
                  V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
                  VALUES
                     ('0500', V_SEQCCTBL, REGC381.COD_CTA, NULL);
               END IF;
            END LOOP;
            FOR REGC385 IN (SELECT '|C385'                                                              ||'|'||
                                   CDSITUTRIBITNFE                                                      ||'|'||
                                   CDARVPROD                                                            ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(VRTOTAITEM),'9999999999900.00')),'.',',')  ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(VRBASECALCIT),'9999999999900.00')),'.',',')||'|'||
                                   REPLACE(LTRIM(TO_CHAR(VRALIQITEM,'9900.0000')),'.',',')              ||'|'||
                                   ''                                                                   ||'|'||
                                   ''                                                                   ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(VRIMPOSTOIT),'9999999999900.00')),'.',',') ||'|'||
                                   CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,CDFILIEMIT)                   ||'|'/*CÓDIGO DA CONTA ANALÍTICA*/ AS C385,
                                   CDNATUBCALPCIT, CDTPCREDPICOITE, CDSITUTRIBITNFE, CDARVPROD, SGUNIDADE, CDNATUREC, SUM(VRTOTAITEM) AS VRTOTAITEM,
                                   SUM(VRBASECALCIT) AS VRBASECALCIT, SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,VRALIQITEM, MAX(CDFILIEMIT) AS CDFILIEMIT,
                                   CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,CDFILIEMIT)AS COD_CTA
                              FROM (SELECT ROUND(IP.VRTOTAITEM,2) AS VRTOTAITEM,
                                           CDTPCREDPICOITE,
                                           DECODE(CDFISCALIT,'1',VRBASECALCIT,0) AS VRBASECALCIT ,
                                           ROUND(VRALIQITEM,4) AS VRALIQITEM,
                                           ROUND(DECODE(CDFISCALIT,'1',VRIMPOSTOIT,0),2) AS VRIMPOSTOIT,
                                           CDNATUBCALPCIT,
                                           CDSITUTRIBITNFE,
                                           P.CDARVPROD AS CDARVPROD,
                                           SGUNIDADE,
                                           CDFISCALIT,
                                           CDNATUREC,
                                           CDCAMPO7 AS CDFILIEMIT,
                                           P.CDPRODUTO,
                                           CDCAMPO9 AS CDTIPOOPER
                                      FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, PRODUTO P, TMP_REGDADOSSPED_PIS TMP, IMPOSTO IM, RELACPRODITGEN R
                                     WHERE IT.CDIMPOSTO    = IM.CDIMPOSTO
                                       AND IM.CDIMPOSTONFE  = P_COFINS
                                       AND IT.NRLANCTONF   = IP.NRLANCTONF
                                       AND IT.CDFILIAL     = IP.CDFILIAL
                                       AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                                       AND IT.NRITPROIMPOS = '1'
                                       AND P.CDPRODUTO     = IP.CDPRODUTO
                                       AND TMP.CDREGISTRO  = 'C380'
                                       AND TMP.CDCAMPO4    = IT.CDFILIAL
                                       AND TMP.CDCAMPO5    = IT.NRLANCTONF
                                       AND TMP.CDCAMPO4    = IP.CDFILIAL
                                       AND TMP.CDCAMPO5    = IP.NRLANCTONF
                                       AND TMP.CDESTAB     = C_REGC380.ESTABELECIMENTO
                                       AND TMP.CDCAMPO1    = C_REGC380.DTEMISSAO
                                       AND P.CDPRODUTO     = R.CDPRODUTO(+)
                                       AND P_LIVROMAG      = R.CDLIVROMAG(+))
                                     GROUP BY CDNATUBCALPCIT, CDTPCREDPICOITE, CDSITUTRIBITNFE, CDARVPROD, SGUNIDADE,CDNATUREC,
                                           VRALIQITEM, CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,CDFILIEMIT))LOOP
               V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
               INSERT INTO ARQMAGPISCOFINS
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
               VALUES
                  (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'))||'02'||LPAD(RTRIM(V_TOTLINHAS),22,'0'),REGC385.C385);
               V_SEQC   := NVL(V_SEQC,0)+1;
               V_PRODUTO:=NULL;
               /* CODIGO DO PRODUTO */
               SELECT MAX(CDCHAVEREG)
                 INTO V_PRODUTO
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = REGC385.CDARVPROD
                  AND CDREGISTRO = '0200'
                  AND CDESTAB = LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'));
               IF (V_PRODUTO IS NULL) AND (REGC385.CDARVPROD IS NOT NULL) THEN
                  V_SEQESTAB := NVL(V_SEQESTAB,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
                  VALUES
                     ('0200', V_SEQESTAB, REGC385.CDARVPROD,NULL,LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000')));
               END IF;
               V_UNID:= NULL;
               /* UNIDADE DE MEDIDA */
               SELECT MAX(CDCHAVEREG)
                 INTO V_UNID
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = REGC385.SGUNIDADE
                  AND CDREGISTRO = '0190'
                  AND CDESTAB = LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'));
               IF (V_UNID IS NULL) AND (REGC385.SGUNIDADE IS NOT NULL) THEN
                  V_SEQESTAB := NVL(V_SEQESTAB,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
                  VALUES
                     ('0190', V_SEQESTAB, REGC385.SGUNIDADE,NULL,LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000')));
               END IF;
               /* CODIGO DA CONTA CONTÁBIL */
               BEGIN
                  SELECT MAX(CDCHAVEREG)
                    INTO V_COD_CC
                    FROM TMP_REGDADOSSPED_PIS
                   WHERE CDCHAVEREG = REGC385.COD_CTA
                     AND CDREGISTRO = '0500';
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_COD_CC := NULL;
               END;
               IF (V_COD_CC IS NULL) AND (REGC385.COD_CTA IS NOT NULL) THEN
                  V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
                  VALUES
                     ('0500', V_SEQCCTBL, REGC385.COD_CTA, NULL);
               END IF;
            END LOOP;
            /*INSERE O VALOR REFERENTE AO PIS PARA SAÍDAS(DÉBITO)*/
            /*SEPARA OS VALORES DO C381 POR REGIME, PARA GERAR O M200 CORRETAMENTE*/
            FOR REGC381_VR IN (SELECT CDTPCREDPICOITE,
                                      SUM(DECODE(CDFISCALIT,'1',VRBASECALCIT,0)) AS VRBASECALCIT,
                                      ROUND(VRALIQITEM,4) AS VRALIQITEM,
                                      SUM(ROUND(DECODE(CDFISCALIT,'1',VRIMPOSTOIT,0),2)) AS VRIMPOSTOIT,
                                      CDSITUTRIBITNFE,
                                      MAX(CDCAMPO7) AS CDFILIEMIT,
                                      CDNATUBCALPCIT,
                                      SUM(ROUND(IP.VRTOTAITEM,2)) AS VRTOTAITEM,
                                      CDNATUREC,
                                      IDCUMUPISCOFIL,
                                      CONTCTBL_SPED('S',IP.CDPRODUTO,TMP.CDCAMPO9,TMP.CDCAMPO7) AS COD_CTA
                                 FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, TMP_REGDADOSSPED_PIS TMP, IMPOSTO IM, RELACPRODITGEN R, FILIAL F
                                WHERE IT.CDIMPOSTO    = IM.CDIMPOSTO
                                  AND IM.CDIMPOSTONFE = P_PIS
                                  AND IT.NRLANCTONF   = IP.NRLANCTONF
                                  AND IT.CDFILIAL     = IP.CDFILIAL
                                  AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                                  AND IT.NRITPROIMPOS = '1'
                                  AND TMP.CDREGISTRO  = 'C380'
                                  AND TMP.CDCAMPO4    = IT.CDFILIAL
                                  AND TMP.CDCAMPO5    = IT.NRLANCTONF
                                  AND TMP.CDCAMPO4    = IP.CDFILIAL
                                  AND TMP.CDCAMPO5    = IP.NRLANCTONF
                                  AND TMP.CDESTAB     = C_REGC380.ESTABELECIMENTO
                                  AND TMP.CDCAMPO1    = C_REGC380.DTEMISSAO
                                  AND IP.CDPRODUTO    = R.CDPRODUTO(+)
                                  AND P_LIVROMAG      = R.CDLIVROMAG(+)
                                  AND CDCAMPO7        = F.CDFILIAL
                                GROUP BY CDTPCREDPICOITE, ROUND(VRALIQITEM,4), CDSITUTRIBITNFE, CDNATUBCALPCIT, CDNATUREC,
                                      IDCUMUPISCOFIL, CONTCTBL_SPED('S',IP.CDPRODUTO,TMP.CDCAMPO9,TMP.CDCAMPO7)) LOOP
            V_TMPBLCM:= NVL(V_TMPBLCM,0)+1;
            INSERT INTO TMP_REGBLOCOM_PIS
               (CHAVENOTA, CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT,VRIMPRETIDO,VRTOTNF,CDNATUREC,CDESTAB,NRINSJUREST,CDCONTCTBL)
            VALUES
               ('C381'||REGC381_VR.CDFILIEMIT,'M200',V_TMPBLCM,REGC381_VR.CDTPCREDPICOITE,REGC381_VR.VRBASECALCIT,REGC381_VR.VRALIQITEM,'P',REGC381_VR.VRIMPOSTOIT,REGC381_VR.CDSITUTRIBITNFE, REGC381_VR.CDFILIEMIT,REGC381_VR.CDNATUBCALPCIT,'0',REGC381_VR.VRTOTAITEM,REGC381_VR.CDNATUREC,LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000')),C_REGC380.NRINSJUREST,REGC381_VR.COD_CTA);
            END LOOP;
            /*INSERE O VALOR REFERENTE AO COFINS SAÍDAS(DÉBITO)*/
            /*SEPARA OS VALORES DO C385 POR REGIME, PARA GERAR O M600 CORRETAMENTE*/
            FOR REGC385_VR IN (SELECT CDTPCREDPICOITE,
                                      SUM(DECODE(CDFISCALIT,'1',VRBASECALCIT,0)) AS VRBASECALCIT,
                                      ROUND(VRALIQITEM,4) AS VRALIQITEM,
                                      SUM(ROUND(DECODE(CDFISCALIT,'1',VRIMPOSTOIT,0),2)) AS VRIMPOSTOIT,
                                      CDSITUTRIBITNFE,
                                      MAX(CDCAMPO7) AS CDFILIEMIT,
                                      CDNATUBCALPCIT,
                                      SUM(ROUND(IP.VRTOTAITEM,2)) AS VRTOTAITEM,
                                      CDNATUREC,
                                      IDCUMUPISCOFIL,
                                      CONTCTBL_SPED('S',IP.CDPRODUTO,TMP.CDCAMPO9,TMP.CDCAMPO7) AS COD_CTA
                                 FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, TMP_REGDADOSSPED_PIS TMP, IMPOSTO IM, RELACPRODITGEN R, FILIAL F
                                WHERE IT.CDIMPOSTO    = IM.CDIMPOSTO
                                  AND IM.CDIMPOSTONFE = P_COFINS
                                  AND IT.NRLANCTONF   = IP.NRLANCTONF
                                  AND IT.CDFILIAL     = IP.CDFILIAL
                                  AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                                  AND IT.NRITPROIMPOS = '1'
                                  AND TMP.CDREGISTRO  = 'C380'
                                  AND TMP.CDCAMPO4    = IT.CDFILIAL
                                  AND TMP.CDCAMPO5    = IT.NRLANCTONF
                                  AND TMP.CDCAMPO4    = IP.CDFILIAL
                                  AND TMP.CDCAMPO5    = IP.NRLANCTONF
                                  AND TMP.CDESTAB     = C_REGC380.ESTABELECIMENTO
                                  AND TMP.CDCAMPO1    = C_REGC380.DTEMISSAO
                                  AND IP.CDPRODUTO    = R.CDPRODUTO(+)
                                  AND P_LIVROMAG      = R.CDLIVROMAG(+)
                                  AND CDCAMPO7        = F.CDFILIAL
                                GROUP BY CDTPCREDPICOITE, ROUND(VRALIQITEM,4), CDSITUTRIBITNFE, CDNATUBCALPCIT, CDNATUREC,
                                      IDCUMUPISCOFIL, CONTCTBL_SPED('S',IP.CDPRODUTO,TMP.CDCAMPO9,TMP.CDCAMPO7)) LOOP
               V_TMPBLCM:= NVL(V_TMPBLCM,0)+1;
               INSERT INTO TMP_REGBLOCOM_PIS
                  (CHAVENOTA,CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT,VRIMPRETIDO,VRTOTNF, CDNATUREC,CDESTAB,NRINSJUREST,CDCONTCTBL)
               VALUES
                  ('C385'||REGC385_VR.CDFILIEMIT,'M600',V_TMPBLCM,REGC385_VR.CDTPCREDPICOITE,REGC385_VR.VRBASECALCIT,REGC385_VR.VRALIQITEM,'P',REGC385_VR.VRIMPOSTOIT,REGC385_VR.CDSITUTRIBITNFE,REGC385_VR.CDFILIEMIT,REGC385_VR.CDNATUBCALPCIT,'0',REGC385_VR.VRTOTAITEM,REGC385_VR.CDNATUREC,LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000')),C_REGC380.NRINSJUREST,REGC385_VR.COD_CTA);
            END LOOP;
         END LOOP;
     -----------------------------------------------------------------/*GERAÇÃO DAS ROTINAS DE ECF*/-----------------------------------------------------------------------
         V_TOTBLCC := SPED_PIS_COFINS_BLOCOC_ECF(V_CONTEST,P_NRSEQARQMAG,P_DTINICIAL,P_DTFINAL,P_CDEMPRESA,P_PIS,P_COFINS,P_LIVROMAG,NVL(V_SEQC,0),V_COUNTBL0ECF,V_CONTEST);
         V_SEQC    := NVL(V_TOTBLCC,0);
         V_TOTBLC0 := NVL(V_TOTBLC0,0) + NVL(V_COUNTBL0ECF,0);
      END IF;/*FIM ESCRITURAÇÃO DETALHADA*/
   --------------------------------------------------------------------------------   /*CHAMADA DO BLOCO F */------------------------------------------------------------
      V_TOTALBCLF:= SPED_PIS_COFINS_BLOCOF(P_CDEMPRESA,P_NRSEQARQMAG,P_DTINICIAL,P_DTFINAL,P_CDINCTRIB,P_CRTESCRITUR,P_PIS,P_PIS_RET_E,P_PIS_RET_S,P_COFINS,P_COFINS_RET_E,P_COFINS_RET_S,V_NEWESTAB,P_LIVROMAG,V_SEQESTABBLCF);
      V_SEQESTAB:= NVL(V_SEQESTAB,0) +  NVL(V_SEQESTABBLCF,0);
      V_TOTBLC0:= NVL(V_TOTBLC0,0)  + NVL(V_SEQESTABBLCF,0);
   -------------------------------------------/*GERA O 0140 PARA ARQUIVOS SEM MOVIMENTO*/---------------------------------------------------------------------------------
      IF ((V_SEMMOVIMENTO = 'S') AND (NVL(V_TOTBLCC,0) <= 0) AND (NVL(V_TOTALBCLF,0) <= 0))  THEN /*VERIFICA SE O ARQUIVO NÃO TEVE NENHUMA NOTA FISCAL PARA GERAR O 0140*/
         SELECT '|0140'         ||'|'||
                LTRIM(TO_CHAR(V_NEWESTAB,'000'))      ||'|'||
                E.NMRAZSOCEMPR  ||'|'||
                LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(E.NRINSJUREMPR,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0') ||'|'||
                E.SGESTADO     ||'|'||
                ''/*REPLACE(REPLACE(REPLACE(REPLACE(IE.CDINSCESTA,.,),/,),-,),\,)*/ ||'|'||
                M.CDMUNICIBGE   ||'|'||
                ''             ||'|'||
                ''             ||'|' AS REG,
                LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(E.NRINSJUREMPR,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0') AS INSJUREST
           INTO V_REG_0140, V_INSJUREST
           FROM EMPRESA E, MUNICIPIO M
          WHERE E.CDEMPRESA    = P_CDEMPRESA
            AND E.CDPAIS       = M.CDPAIS
            AND E.SGESTADO     = M.SGESTADO
            AND E.CDMUNICIPIO  = M.CDMUNICIPIO;
         V_TOTBLC0  := NVL(V_TOTBLC0,0)+1;
         V_TOTLINHAS:= NVL(V_TOTLINHAS,0)+1;
         V_CONTEST  := NVL(V_CONTEST,0)+1;
         INSERT INTO ARQMAGPISCOFINS
            (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
            (P_NRSEQARQMAG,'104'||LTRIM(TO_CHAR(V_CONTEST,'000')),V_REG_0140);
         V_SEQESTAB:= NVL(V_SEQESTAB,0)+1;
         INSERT INTO TMP_REGDADOSSPED_PIS
           (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
         VALUES
           ('0140', V_SEQESTAB, V_INSJUREST ,NULL,LTRIM(TO_CHAR(V_CONTEST,'000')));
      END IF;
   ------------------------------------------/*REGISTRO 0111 - RATEIO PROPORCIONAL*/-------------------------------------------------------------------------------------
      /*REGISTRO 0111*/
      IF P_INDAPROCRED = '2' THEN
         FOR REG_0111 IN (SELECT '|0111'                                                                ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRRECNCINT),   '9999999999900.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRRECNCUMISEN),'9999999999900.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(RECNCUMEXP),   '9999999999900.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRRECCUM),     '9999999999900.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(NVL(VRRECNCINT,0)+NVL(VRRECNCUMISEN,0)+NVL(RECNCUMEXP,0)+NVL(VRRECCUM,0)),'9999999999900.00')),'.',',') ||'|' AS REG0111
                            FROM (SELECT  CASE WHEN CSTPISCOFINS NOT IN ('06','07', '08','09') THEN DECODE(IDCUMUPISCOFIL,'S',SUM(VRCRED),0) ELSE 0 END  AS VRRECNCINT,
                                          CASE WHEN CSTPISCOFINS IN ('06','07', '08','09') THEN SUM(VRCRED) ELSE 0 END AS VRRECNCUMISEN,
                                          '0' AS RECNCUMEXP,
                                          DECODE(IDCUMUPISCOFIL,'N',SUM(VRCRED),0) AS VRRECCUM
                                     FROM TMP_REGBLOCOM_PIS T, FILIAL F
                                    WHERE CDREGISTRO = 'M200'
                                      AND T.CDFILIAL = F.CDFILIAL
                                    GROUP BY IDCUMUPISCOFIL, CSTPISCOFINS)
                           GROUP BY '|0111')LOOP
            V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
            V_TOTBLC0   := NVL(V_TOTBLC0,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'103'||LPAD(RTRIM(V_TOTLINHAS),22,'0'),REG_0111.REG0111);
         END LOOP;
      END IF;
--------------------------/*CHAMADA DO BLOCO M - APURAÇÃO DO PIS E COFINS*/-----------------------------------------------
      /*GERA BLOCO M*/
      V_TOTBLCM:= SPED_PIS_COFINS_BLOCOM(V_CONTEST,P_CDEMPRESA,P_NRSEQARQMAG,P_DTINICIAL,P_DTFINAL,P_LIVROMAG,P_CDINCTRIB,P_GERABCLP,P_PIS,P_COFINS, V_GERADEVOLVEND,P_VERSAO,V_CONTBLC0M);
      V_TOTBLC0 := NVL(V_TOTBLC0,0) + NVL(V_CONTBLC0M,0);
   END IF;
-------------------------------------------------/*CHAMADA DO BLOCO P*/---------------------------------------------------
   IF P_GERABCLP IN ('1','2') THEN
      V_RESULTADO:= SPED_PIS_COFINS_BLOCOP(P_CDEMPRESA,P_NRSEQARQMAG,P_DTINICIAL,P_DTFINAL,V_SEQESTAB,V_CONTEST,V_COUNTBL0P);
      V_TOTBLCP  := SUBSTR(V_RESULTADO,1,20);
      V_TOTBLC0  := NVL(V_TOTBLC0,0) + NVL(V_COUNTBL0P,0);
   END IF;
------------------------------------------------/*INSERE ABERTURA E FECHAMENTO DOS BLOCOS*/ ------------------------------
   /*O A ABERTURA DO BLOCO A */
   IF V_TOTBLCA > 0 THEN
      V_REG_A001 := '|A001|0|';
   ELSE
      V_REG_A001 := '|A001|1|';
   END IF;
   /*INSERE O REGISTRO A001*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'201',V_REG_A001);
   V_TOTLINHAS:= NVL(V_TOTLINHAS,0)+2; /*INSERE 2 DEVIDO AO ENCERRAMENTO*/
   V_TOTBLCA:= NVL(V_TOTBLCA,0)+2;
   V_SEQA:= NVL(V_SEQA,0)+2;
   /*INSERE O BLOCO A990 - ENCERRAMENTO*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'208','|A990|'||NVL(V_SEQA,2)||'|');
   /*O A ABERTURA DO BOCO C */
   IF V_TOTBLCC > 0 THEN
      V_REG_C001 := '|C001|0|';
   ELSE
      V_REG_C001 := '|C001|1|';
   END IF;
   /*INSERE O REGISTRO C001*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'301',V_REG_C001);
   V_TOTLINHAS:= NVL(V_TOTLINHAS,0)+2; /*INSERE 2 DEVIDO AO ENCERRAMENTO*/
   V_SEQC:= NVL(V_SEQC,0)+2;
   /*INSERE O BLOCO C990 - ENCERRAMENTO*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'318','|C990|'||NVL(V_SEQC,2)||'|');
   /*O A ABERTURA DO BOCO D */
   IF V_TOTBLCD > 0 THEN
      V_REG_D001 := '|D001|0|';
   ELSE
      V_REG_D001 := '|D001|1|';
   END IF;
   /*INSERE O REGISTRO D001*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'401',V_REG_D001);
   V_TOTLINHAS:= NVL(V_TOTLINHAS,0)+2; /*INSERE 2 DEVIDO AO ENCERRAMENTO*/
   V_SEQD:= NVL(V_SEQD,0)+2;
   /*INSERE O BLOCO D990 - ENCERRAMENTO*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'416','|D990|'||NVL(V_SEQD,2)||'|');
   /*ABERTURA DO BLOCO F*/
   IF V_TOTALBCLF > 0 THEN
      V_REG_F001 := '|F001|0|';
   ELSE
      V_REG_F001 := '|F001|1|';
   END IF;
   /*INSERE O REGISTRO F001*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'501',V_REG_F001);
   V_TOTLINHAS := NVL(V_TOTLINHAS,0)+2; /*INSERE 2 DEVIDO AO ENCERRAMENTO*/
   V_TOTALBCLF := NVL(V_TOTALBCLF,0) + 2;
   /*INSERE O BLOCO F990 - ENCERRAMENTO*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'509','|F990|'||NVL(V_TOTALBCLF,2)||'|');
   IF V_TOTBLCM > 0 THEN
      V_REG_M001 := '|M001|0|';
   ELSE
      V_REG_M001 := '|M001|1|';
   END IF;
   /*INSERE O REGISTRO M001*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'601',V_REG_M001);
   V_TOTLINHAS:= NVL(V_TOTLINHAS,0)+2; /*INSERE 2 DEVIDO AO ENCERRAMENTO*/
   V_TOTBLCM:= NVL(V_TOTBLCM,0)+2;/*INSERE 2 DEVIDO AO ENCERRAMENTO*/
   /*INSERE O BLOCO M990 - ENCERRAMENTO*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'690','|M990|'||V_TOTBLCM||'|');
   IF P_GERABCLP IN ('1','2') THEN
      IF V_TOTBLCP > 0 THEN
         V_REG_P001 := '|P001|0|';
      ELSE
         V_REG_P001 := '|P001|1|';
      END IF;
   END IF;
   IF P_GERABCLP IN ('1','2') THEN
      /*INSERE O REGISTRO P001*/
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'701',V_REG_P001);
      V_TOTLINHAS:= NVL(V_TOTLINHAS,0)+2; /*INSERE 2 DEVIDO AO ENCERRAMENTO*/
      V_TOTBLCP:= NVL(V_TOTBLCP,0) + 2;
      /*INSERE O BLOCO P990 - ENCERRAMENTO*/
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'709','|P990|'||V_TOTBLCP||'|');
   END IF;
   SELECT COUNT(*) AS QTDE
     INTO V_CONTREG1
     FROM ARQMAGPISCOFINS
    WHERE SUBSTR(DSREGARQMAG,2,1) = '1'
      AND NRSEQARQMAG = P_NRSEQARQMAG;
   IF P_VERSAO >= '005' THEN
      /* REGISTRO 1050 */
      FOR C_REG1050 IN (SELECT '|1050'         ||'|'||
                               TO_CHAR(NVL(A.DTAJUSTE,P_DTFINAL),'DDMMYYYY') ||'|'||
                               A.CDAJUSTEBC    ||'|'||
                               I.NRINSJURIEST  ||'|'||
                               REPLACE(LTRIM(TO_CHAR(SUM(NVL(A.VRBASECALCAJ,0)),'999999999990.00')),'.',',') ||'|'||
                               REPLACE(LTRIM(TO_CHAR(SUM(DECODE(A.CDSITUTRIBITNFE,'01',NVL(A.VRBASECALCAJ,0),0)),'999999999990.00')),'.',',') ||'|'||
                               REPLACE(LTRIM(TO_CHAR(SUM(DECODE(A.CDSITUTRIBITNFE,'02',NVL(A.VRBASECALCAJ,0),0)),'999999999990.00')),'.',',') ||'|'||
                               REPLACE(LTRIM(TO_CHAR(SUM(DECODE(A.CDSITUTRIBITNFE,'03',NVL(A.VRBASECALCAJ,0),0)),'999999999990.00')),'.',',') ||'|'||
                               REPLACE(LTRIM(TO_CHAR(SUM(DECODE(A.CDSITUTRIBITNFE,'04',NVL(A.VRBASECALCAJ,0),0)),'999999999990.00')),'.',',') ||'|'||
                               REPLACE(LTRIM(TO_CHAR(SUM(DECODE(A.CDSITUTRIBITNFE,'05',NVL(A.VRBASECALCAJ,0),0)),'999999999990.00')),'.',',') ||'|'||
                               REPLACE(LTRIM(TO_CHAR(SUM(DECODE(A.CDSITUTRIBITNFE,'06',NVL(A.VRBASECALCAJ,0),0)),'999999999990.00')),'.',',') ||'|'||
                               REPLACE(LTRIM(TO_CHAR(SUM(DECODE(A.CDSITUTRIBITNFE,'07',NVL(A.VRBASECALCAJ,0),0)),'999999999990.00')),'.',',') ||'|'||
                               REPLACE(LTRIM(TO_CHAR(SUM(DECODE(A.CDSITUTRIBITNFE,'08',NVL(A.VRBASECALCAJ,0),0)),'999999999990.00')),'.',',') ||'|'||
                               REPLACE(LTRIM(TO_CHAR(SUM(DECODE(A.CDSITUTRIBITNFE,'09',NVL(A.VRBASECALCAJ,0),0)),'999999999990.00')),'.',',') ||'|'||
                               REPLACE(LTRIM(TO_CHAR(SUM(DECODE(A.CDSITUTRIBITNFE,'49',NVL(A.VRBASECALCAJ,0),0)),'999999999990.00')),'.',',') ||'|'||
                               REPLACE(LTRIM(TO_CHAR(SUM(DECODE(A.CDSITUTRIBITNFE,'99',NVL(A.VRBASECALCAJ,0),0)),'999999999990.00')),'.',',') ||'|'||
                               A.IDAPROPRIACAO ||'|'||
                               A.NRRECIBO      ||'|'||
                               ''              ||'|' AS REG_1050
                          FROM AJUSTEAPURCONTR A, FILIAL F, INSCRESTAD I, MAPAAPURAC M
                         WHERE M.CDEMPRESA     = P_CDEMPRESA
                           AND M.CDIMPOSTO     IN (P_PIS, P_COFINS)
                           AND M.DTINIPERIODO  = P_DTINICIAL
                           AND M.DTFIMPERIODO  = P_DTFINAL
                           AND M.NRSEQUMAPAPU  = A.NRSEQUMAPAPU
                           AND A.CDFILIAL      = F.CDFILIAL
                           AND F.CDEMPRESA     = I.CDEMPRESA
                           AND F.CDINSCESTA    = I.CDINSCESTA
                           AND A.IDINDICAJUSTE = 'DB'
                         GROUP BY A.DTAJUSTE, A.CDAJUSTEBC, I.NRINSJURIEST, A.IDAPROPRIACAO, A.NRRECIBO) LOOP
         V_CONTREG1:= NVL(V_CONTREG1,0)+1;
         INSERT INTO ARQMAGPISCOFINS
            (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
            (P_NRSEQARQMAG,'8010'||V_CONTREG1,C_REG1050.REG_1050);
      END LOOP;
   END IF;
   IF (((P_GERABCLP IS NULL) OR (P_GERABCLP IN ('0','1'))) AND (P_CRTESCRITUR IN ('1','2'))) THEN
      BEGIN
         SELECT NRSEQUMAPAPU AS NRSEQUMAPPIS
           INTO V_NRSEQUMAPPIS
           FROM MAPAAPURAC MP
          WHERE MP.CDEMPRESA = P_CDEMPRESA
            AND MP.CDIMPOSTO = P_PIS
            AND MP.DTINIPERIODO BETWEEN P_DTINICIAL AND P_DTFINAL;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_NRSEQUMAPPIS := NULL;
      END;
      /* REGISTRO 1900 */
      FOR C_1900 IN (SELECT '|1900'         ||'|'||
                            CNPJ            ||'|'||
                            COD_MOD         ||'|'||
                            SER             ||'|'||
                            SUB_SER         ||'|'||
                            COD_SIT         ||'|'||
                            REPLACE(LTRIM(TO_CHAR(ROUND(SUM(VL_TOT_REC),2), '999999999990.00')), '.', ',') ||'|'||
                            SUM(QUANT_DOC)  ||'|'||
                            CST_PIS         ||'|'||
                            CST_COFINS      ||'|'||
                            CFOP            ||'|'||
                            INF_COMPL       ||'|'||
                            COD_CTA         ||'|' AS REGISTRO, COD_CTA,
                            TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(CNPJ,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')) AS CNPJ
                       FROM (SELECT CNPJ, COD_MOD, SER, SUB_SER, COD_SIT, SUM(VL_TOT_REC) AS VL_TOT_REC, QUANT_DOC, MAX(CST_PIS) AS CST_PIS,
                                    MAX(CST_COFINS) AS CST_COFINS, CFOP, INF_COMPL, COD_CTA
                               FROM (SELECT E.NRINSJUREMPR AS CNPJ,
                                            DECODE(SUBSTR(CDESTAB,LENGTH(CDESTAB)-2,3),'ISS','98',N.CDMODDOCFISC) AS COD_MOD,
                                            N.CDSERIE AS SER, '' AS SUB_SER,
                                            CASE WHEN N.IDSTATUS = 'C' THEN '02' WHEN N.IDSTATUS IN ('A','E') THEN '00' ELSE '99' END AS COD_SIT,
                                            SUM(DECODE(IM.CDIMPOSTONFE,P_PIS,I.VRCONTITIMP,0)) AS VL_TOT_REC,
                                            COUNT(DISTINCT N.NRLANCTONF) AS QUANT_DOC,
                                            DECODE(IM.CDIMPOSTONFE,P_PIS,I.CDSITUTRIBITNFE,'') AS CST_PIS,
                                            DECODE(IM.CDIMPOSTONFE,P_COFINS,I.CDSITUTRIBITNFE,'') AS CST_COFINS,
                                            I.CDFISCOPERIT AS CFOP,
                                            '' AS INF_COMPL,
                                            CONTCTBL_SPED(N.IDENTRSAIDOP,P.CDPRODUTO,N.CDTIPOOPER,DECODE(N.IDENTRSAIDOP,'E',N.CDFILIRECE,N.CDFILIEMIT)) AS COD_CTA
                                       FROM TMP_REGDADOSSPED_PIS T, NOTAFISCAL N, EMPRESA E, ITEMPROIMPOS I, ITEMPRODUTO P, IMPOSTO IM
                                      WHERE T.CDREGISTRO   = 'NOTA'
                                        AND T.CDCAMPO1     = N.CDFILIAL
                                        AND T.CDCAMPO2     = N.NRLANCTONF
                                        AND N.IDENTRSAIDOP = 'S'
                                        AND E.CDEMPRESA    = P_CDEMPRESA
                                        AND I.CDFILIAL     = N.CDFILIAL
                                        AND I.NRLANCTONF   = N.NRLANCTONF
                                        AND I.CDIMPOSTO    = IM.CDIMPOSTO
                                        AND I.CDFILIAL     = P.CDFILIAL
                                        AND I.NRLANCTONF   = P.NRLANCTONF
                                        AND I.NRSEQITPROD  = P.NRSEQITPROD
                                        AND IM.CDIMPOSTONFE IN (P_PIS,P_COFINS)
                                        AND NOT EXISTS (SELECT CDFILIAL, NRLANCTONF
                                                          FROM IMPBAIXAREC
                                                         WHERE CDFILIAL     = T.CDCAMPO1
                                                           AND NRLANCTONF   = T.CDCAMPO2
                                                           AND NRSEQUMAPAPU = V_NRSEQUMAPPIS)
                                      GROUP BY E.NRINSJUREMPR, DECODE(SUBSTR(CDESTAB,LENGTH(CDESTAB)-2,3),'ISS','98',N.CDMODDOCFISC), N.CDSERIE,
                                               CASE WHEN N.IDSTATUS = 'C' THEN '02' WHEN N.IDSTATUS IN ('A','E') THEN '00' ELSE '99' END,
                                               DECODE(IM.CDIMPOSTONFE,P_PIS,I.CDSITUTRIBITNFE,''), DECODE(IM.CDIMPOSTONFE,P_COFINS,I.CDSITUTRIBITNFE,''),
                                               I.CDFISCOPERIT, CONTCTBL_SPED(N.IDENTRSAIDOP,P.CDPRODUTO,N.CDTIPOOPER,DECODE(N.IDENTRSAIDOP,'E',N.CDFILIRECE,N.CDFILIEMIT)))
                              GROUP BY CNPJ, COD_MOD, SER, SUB_SER, COD_SIT, QUANT_DOC, CFOP, INF_COMPL, COD_CTA
                              UNION ALL
                             SELECT E.NRINSJUREMPR AS CNPJ,
                                    DECODE(SUBSTR(CDESTAB,LENGTH(CDESTAB)-2,3),'ISS','98',N.CDMODDOCFISC) AS COD_MOD,
                                    N.CDSERIE AS SER, '' AS SUB_SER,
                                    CASE WHEN N.IDSTATUS = 'C' THEN '02' WHEN N.IDSTATUS IN ('A','E') THEN '00' ELSE '99' END AS COD_SIT,
                                    SUM(VALOR_IMPOSTO_ITEM_NFE_CAIXA(N.CDFILIAL,N.NRLANCTONF,P_PIS,'C',I.DTBAIXAREC,'',I.CDFISCOPERNF,I.CDSITUTRIBITNFE,I.NRSEQUENCIAL)) AS VL_TOT_REC,
                                    COUNT(DISTINCT N.NRLANCTONF) AS QUANT_DOC,
                                    I.CDSITUTRIBITNFE AS CST_PIS,
                                    I.CDSITUTRIBITNFE AS CST_COFINS,
                                    I.CDFISCOPERNF AS CFOP,
                                    '' AS INF_COMPL,
                                    CONTCTBL_SPED(N.IDENTRSAIDOP,'',N.CDTIPOOPER,N.CDFILIEMIT) AS COD_CTA
                               FROM TMP_REGDADOSSPED_PIS T, NOTAFISCAL N, EMPRESA E, IMPBAIXAREC I, IMPOSTO IM
                              WHERE T.CDREGISTRO    = 'NOTA'
                                AND T.CDCAMPO1      = N.CDFILIAL
                                AND T.CDCAMPO2      = N.NRLANCTONF
                                AND N.IDENTRSAIDOP  = 'S'
                                AND E.CDEMPRESA     = P_CDEMPRESA
                                AND I.CDFILIAL      = N.CDFILIAL
                                AND I.NRLANCTONF    = N.NRLANCTONF
                                AND I.CDIMPOSTO     = IM.CDIMPOSTO
                                AND IM.CDIMPOSTONFE = P_PIS
                                AND I.NRSEQUMAPAPU  = V_NRSEQUMAPPIS
                              GROUP BY E.NRINSJUREMPR, DECODE(SUBSTR(CDESTAB,LENGTH(CDESTAB)-2,3),'ISS','98',N.CDMODDOCFISC),
                                    N.CDSERIE, CASE WHEN N.IDSTATUS = 'C' THEN '02' WHEN N.IDSTATUS IN ('A','E') THEN '00' ELSE '99' END,
                                    I.CDSITUTRIBITNFE, I.CDSITUTRIBITNFE, I.CDFISCOPERNF, CONTCTBL_SPED(N.IDENTRSAIDOP,'',N.CDTIPOOPER,N.CDFILIEMIT)
                              UNION ALL
                             SELECT E.NRINSJUREMPR AS CNPJ,
                                    '99' AS COD_MOD,
                                    '' AS SER,
                                    '' AS SUB_SER,
                                    '99' AS COD_SIT,
                                    SUM(ABS(LC.VRLANCAMENT)) AS VL_TOT_REC,
                                    0 AS QUANT_DOC,
                                    GP.CDSITUTRIBPICO AS CST_PIS,
                                    GP.CDSITUTRIBPICO AS CST_COFINS,
                                    '' AS CFOP,
                                    '' AS INF_COMPL,
                                    CGP.CDCONTCTBL AS COD_CTA
                               FROM OUTRECCONT GP, OUTRECCONTCTBL CGP, LANCCONT LC, EMPRESA E
                              WHERE GP.CDEMPRESA    = P_CDEMPRESA
                                AND GP.CDEMPRESA    = CGP.CDEMPRESA
                                AND GP.CDOUTRECCONT =  CGP.CDOUTRECCONT
                                AND LC.CDCONTCTBL LIKE CGP.CDCONTCTBL||'%'
                                AND LC.IDLANCINTE   NOT IN ('F','S')
                                AND LC.DTLANCCONT BETWEEN P_DTINICIAL AND P_DTFINAL
                                AND LC.CDEMPRESA    = P_CDEMPRESA
                                AND LC.CDEMPRESA    = E.CDEMPRESA
                                AND LC.VRLANCAMENT  > 0
                              GROUP BY GP.CDSITUTRIBPICO,  CGP.CDCONTCTBL, E.NRINSJUREMPR
                              UNION ALL
                             SELECT NRINSJURIEST AS CNPJ,
                                    '99' AS COD_MOD,
                                    '' AS SER,
                                    '' AS SUB_SER,
                                    '99' AS COD_SIT,
                                    SUM(VRRECEITA) AS VL_TOT_REC,
                                    0 AS QUANT_DOC,
                                    CSTPIS,
                                    CSTCOFINS,
                                    CFOP,
                                    INFO_COMPL,
                                    COD_CTA
                               FROM(SELECT IT.VRPRODUTO  AS VRRECEITA,
                                           CDSITUTRIBNFE AS CSTPIS,
                                           CDSITUTRIBNFE AS CSTCOFINS,
                                           '' AS CFOP,
                                           CONTCTBL_SPED('S',IT.CDPRODUTO,P.CDTPOPERCNTREC,RZ.CDFILIAL) AS COD_CTA,
                                           '' AS INFO_COMPL,
                                           IE.NRINSJURIEST
                                      FROM ITEMVENOUTIMPOS IT, REDUCAOZ RZ, FILIAL F, IMPOSTO I, INSCRESTAD IE, PARAVEND P
                                     WHERE IT.CDFILIAL    = RZ.CDFILIAL
                                       AND IT.CDCAIXA     = RZ.CDCAIXA
                                       AND IT.DTREDUCAOZ  = RZ.DTREDUCAOZ
                                       AND RZ.CDFILIAL    = P.CDFILIAL
                                       AND IT.CDIMPOSTO   = I.CDIMPOSTO
                                       AND F.CDFILIAL     = RZ.CDFILIAL
                                       AND F.CDFILIAL     = IT.CDFILIAL
                                       AND F.CDEMPRESA    = P_CDEMPRESA
                                       AND F.CDEMPRESA    = IE.CDEMPRESA
                                       AND F.CDINSCESTA   = IE.CDINSCESTA
                                       AND I.CDIMPOSTONFE = P_PIS
                                       AND IT.DTREDUCAOZ BETWEEN P_DTINICIAL AND P_DTFINAL)
                              GROUP BY NRINSJURIEST, CSTPIS, CSTCOFINS, CFOP, INFO_COMPL, COD_CTA
                              UNION ALL
                              SELECT E.NRINSJUREMPR AS CNPJ,
                                    '59' AS COD_MOD,
                                    V.CDSERIENFCE AS SER, '' AS SUB_SER,
                                    CASE WHEN V.IDSTATUSNFCE = 'C' THEN '02' WHEN V.IDSTATUSNFCE IN ('A','E') THEN '00' ELSE '99' END AS COD_SIT,
                                    SUM(TRUNC((IT.QTPRODVEND*(NVL(IT.VRUNITVEND,0)+NVL(IT.VRUNITVENDCL,0)))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) AS VL_TOT_REC,
                                    COUNT(DISTINCT V.NRSEQVENDA) AS QUANT_DOC,
                                    I.CDCSTPRODPC AS CST_PIS,
                                    I.CDCSTPRODPC AS CST_COFINS,
                                    I.CDCFOPPROD AS CFOP,
                                    '' AS INF_COMPL,
                                    CONTCTBL_SPED('S',IT.CDPRODUTO,P.CDTPOPERCNTREC,IT.CDFILIAL) AS COD_CTA
                               FROM TMP_REGDADOSSPED_PIS T, VENDA V, EMPRESA E, ITVENDAIMPOS I, ITEMVENDA IT, PARAVEND P
                              WHERE T.CDREGISTRO   = 'SAT'
                                AND T.CDCAMPO1     = V.CDFILIAL
                                AND T.CDCAMPO2     = V.NRSEQVENDA
                                AND T.CDCAMPO3     = V.CDCAIXA
                                AND V.CDFILIAL     = P.CDFILIAL
                                AND E.CDEMPRESA    = P_CDEMPRESA
                                AND V.CDFILIAL     = I.CDFILIAL
                                AND V.NRSEQVENDA   = I.NRSEQVENDA
                                AND V.CDCAIXA      = I.CDCAIXA
                                AND I.CDFILIAL     = IT.CDFILIAL
                                AND I.NRSEQVENDA   = IT.NRSEQVENDA
                                AND I.CDCAIXA      = IT.CDCAIXA
                                AND I.NRSEQUITVEND = IT.NRSEQUITVEND
                              GROUP BY E.NRINSJUREMPR, V.CDSERIENFCE, I.CDCSTPRODPC, I.CDCSTPRODPC, I.CDCFOPPROD,
                                    CASE WHEN V.IDSTATUSNFCE = 'C' THEN '02' WHEN V.IDSTATUSNFCE IN ('A','E') THEN '00' ELSE '99' END,
                                    CONTCTBL_SPED('S',IT.CDPRODUTO,P.CDTPOPERCNTREC,IT.CDFILIAL)
                              UNION ALL
                             SELECT E.NRINSJUREMPR AS CNPJ,
                                    '65' AS COD_MOD,
                                    V.CDSERIENFCE AS SER, '' AS SUB_SER,
                                    CASE WHEN V.IDSTATUSNFCE = 'C' THEN '02' WHEN V.IDSTATUSNFCE IN ('A','E') THEN '00' ELSE '99' END AS COD_SIT,
                                    SUM(TRUNC((IT.QTPRODVEND*(NVL(IT.VRUNITVEND,0)+NVL(IT.VRUNITVENDCL,0)))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) AS VL_TOT_REC,
                                    COUNT(DISTINCT V.NRSEQVENDA) AS QUANT_DOC,
                                    I.CDCSTPRODPC AS CST_PIS,
                                    I.CDCSTPRODPC AS CST_COFINS,
                                    I.CDCFOPPROD AS CFOP,
                                    '' AS INF_COMPL,
                                    CONTCTBL_SPED('S',IT.CDPRODUTO,P.CDTPOPERCNTREC,IT.CDFILIAL) AS COD_CTA
                               FROM TMP_REGDADOSSPED_PIS T, VENDA V, EMPRESA E, ITVENDAIMPOS I, ITEMVENDA IT, PARAVEND P
                              WHERE T.CDREGISTRO   = 'NFCE'
                                AND T.CDCAMPO1     = V.CDFILIAL
                                AND T.CDCAMPO2     = V.NRSEQVENDA
                                AND T.CDCAMPO3     = V.CDCAIXA
                                AND V.CDFILIAL     = P.CDFILIAL
                                AND E.CDEMPRESA    = P_CDEMPRESA
                                AND V.CDFILIAL     = I.CDFILIAL
                                AND V.NRSEQVENDA   = I.NRSEQVENDA
                                AND V.CDCAIXA      = I.CDCAIXA
                                AND I.CDFILIAL     = IT.CDFILIAL
                                AND I.NRSEQVENDA   = IT.NRSEQVENDA
                                AND I.CDCAIXA      = IT.CDCAIXA
                                AND I.NRSEQUITVEND = IT.NRSEQUITVEND
                              GROUP BY E.NRINSJUREMPR, V.CDSERIENFCE, I.CDCSTPRODPC, I.CDCSTPRODPC, I.CDCFOPPROD,
                                    CASE WHEN V.IDSTATUSNFCE = 'C' THEN '02' WHEN V.IDSTATUSNFCE IN ('A','E') THEN '00' ELSE '99' END,
                                    CONTCTBL_SPED('S',IT.CDPRODUTO,P.CDTPOPERCNTREC,IT.CDFILIAL))
                      GROUP BY CNPJ, COD_MOD, SER, SUB_SER, COD_SIT, CST_PIS, CST_COFINS, CFOP, INF_COMPL, COD_CTA, TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(CNPJ,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),''))) LOOP
         V_CONTREG1:= NVL(V_CONTREG1,0)+1;
         INSERT INTO ARQMAGPISCOFINS
            (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
            (P_NRSEQARQMAG,'802'||V_CONTREG1,C_1900.REGISTRO);
         V_OLDESTAB := NULL;
         /*VERIFICA SE O ESTABELECIMENTO JA FOI INSERIDO*/
         SELECT MAX(CDESTAB)
           INTO V_OLDESTAB
           FROM TMP_REGDADOSSPED_PIS
          WHERE CDREGISTRO = '0140'
            AND CDCHAVEREG = C_1900.CNPJ;
         V_REG_0140 := '';
         IF V_OLDESTAB IS NULL THEN
            V_CONTEST := NVL(V_CONTEST,0)+1;
            BEGIN
               SELECT REG
                 INTO V_REG_0140
                 FROM (SELECT '|0140'         ||'|'||
                              LTRIM(TO_CHAR(V_CONTEST,'000')) ||'|'||
                              E.NMRAZSOCEMPR  ||'|'||
                              LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(E.NRINSJUREMPR,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0') ||'|'||
                              E.SGESTADO      ||'|'||
                              ''              ||'|'||
                              M.CDMUNICIBGE   ||'|'||
                              ''              ||'|'||
                              ''              ||'|' AS REG,
                              LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(E.NRINSJUREMPR,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0') AS INSJUREST
                         FROM MUNICIPIO M, EMPRESA E
                        WHERE E.CDEMPRESA   = P_CDEMPRESA
                          AND E.CDPAIS      = M.CDPAIS
                          AND E.SGESTADO    = M.SGESTADO
                          AND E.CDMUNICIPIO = M.CDMUNICIPIO);
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_REG_0140:= NULL;
            END;
            V_TOTBLC0 := NVL(V_TOTBLC0,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'104'||LTRIM(TO_CHAR(V_CONTEST,'000')),V_REG_0140);
            V_SEQESTAB:= NVL(V_SEQESTAB,0)+1;
            INSERT INTO TMP_REGDADOSSPED_PIS
               (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
             VALUES
               ('0140', V_SEQESTAB, C_1900.CNPJ ,NULL,LTRIM(TO_CHAR(V_CONTEST,'000')));
         ELSE
            V_CONTEST:= TO_NUMBER(V_OLDESTAB);
         END IF;
         /* CODIGO DA CONTA CONTÁBIL */
         BEGIN
            SELECT MAX(CDCHAVEREG)
              INTO V_COD_CC
              FROM TMP_REGDADOSSPED_PIS
             WHERE CDCHAVEREG = C_1900.COD_CTA
               AND CDREGISTRO = '0500';
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_COD_CC := NULL;
         END;
         IF (V_COD_CC IS NULL) AND (C_1900.COD_CTA IS NOT NULL) THEN
            V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1;
            INSERT INTO TMP_REGDADOSSPED_PIS
               (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
            VALUES
               ('0500', V_SEQCCTBL, C_1900.COD_CTA, NULL);
         END IF;
      END LOOP;
   END IF;
   /*INSERE O REGISTRO 1001*/
   IF V_CONTREG1 > 0 THEN
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'801','|1001|0|');
   ELSE
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'801','|1001|1|');
   END IF;
   V_CONTREG1:= NVL(V_CONTREG1,0)+1;
   /*INSERE O BLOCO 1990 - ENCERRAMENTO*/
   V_CONTREG1:= NVL(V_CONTREG1,0)+1;
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'803'||V_CONTREG1,'|1990|'||V_CONTREG1||'|');
   V_TOTLINHAS:= NVL(SPED_PIS_COFINS_BLOCO9(NVL(V_TOTBLCA,0),NVL(V_TOTBLCC,0),NVL(V_TOTBLCD,0),NVL(V_TOTBLC0,0),P_GERABCLP,P_LIVROMAG,P_NRSEQARQMAG,P_DTINICIAL,P_DTFINAL),0);
   RETURN(V_TOTLINHAS);
END;