                                REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', VALOR_ENCARGO_NFE(NF.CDFILIAL, NF.NRLANCTONF, V_IDOUTROS, '04'))),2), '999999999990.00')), '.', ',') || '|' || -- Campo 20 outras obrigações acessórias
                                REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', NF.VRBASECALCNF)),2), '999999999990.00')), '.', ',') || '|' || -- campo 21
                                REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', NF.VRIMPOSTONF)),2), '999999999990.00')), '.', ',') || '|' || -- campo 22
                                REPLACE(LTRIM(TO_CHAR(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS,'C','',VALOR_IMPOSTO_NFE(NF.CDFILIAL, NF.NRLANCTONF,'80','B','1'))), '999999999990.00')), '.', ',') || '|' || -- base de calc susbt. trib
                                REPLACE(LTRIM(TO_CHAR(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS,'C','',VALOR_IMPOSTO_NFE(NF.CDFILIAL, NF.NRLANCTONF,'80','I','1') + VALOR_FECP_NFE(NF.CDFILIAL, NF.NRLANCTONF,'80','I','1'))), '999999999990.00')), '.', ',') || '|' || -- valor do icms retido susbt. trib
                                REPLACE(LTRIM(TO_CHAR(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS,'C','',VALOR_IMPOSTO_NFE(NF.CDFILIAL, NF.NRLANCTONF,'10','I','1'))), '999999999990.00')), '.', ',') || '|' || -- valor do IPI
                                REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', VALOR_IMPOSTO_NFE(NF.CDFILIAL, NF.NRLANCTONF, '50', 'I','1'))),2), '999999999990.00')), '.', ',') || '|' || -- valor do PIS
                                REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', VALOR_IMPOSTO_NFE(NF.CDFILIAL, NF.NRLANCTONF, '60', 'I','1'))),2), '999999999990.00')), '.', ',') || '|' || -- valor do COFINS
                                DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', '0,00')) || '|' || -- pis retido por subst. trib.
                                DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', '0,00')) || '|'  ) AS DADOS_3,
                                NF.CDFILIAL AS CDFILIAL, NF.NRLANCTONF AS NRLANCTONF, NF.NRINSJURTRAN, NF.IDTPIJURTRAN, NF.VRPBRUTOVOLU, NF.VRPLIQUVOLU,
                                NF.NRPLACAVEIC, NF.DSQTDEVOLU, NF.DSESPECVOLU, NF.DSMARCAVOLU, NF.DSNUMEVOLU, NF.CDFISCOPERNF, NF.NRNOTAFISC AS NRNOTAFISC,
                                NF.DTEMISSAO, NF.DTENTRSAID, NF.IDENTRSAIDOP, NF.VRIMPOSTONF, NF.CDMODDOCFISC, NF.IDSTATUS, NF.IDORIGDESTNF,
                                NF.IDORIGDESTNF||DECODE(NF.IDORIGDESTNF, 'F', NF.CDFORNECED, DECODE(NF.IDORIGDESTNF, 'C', NF.CDCLIENTE , DECODE(NF.IDENTRSAIDOP, 'E', NF.CDFILIEMIT, NF.CDFILIRECE))) AS COD_PAR,
                                DECODE(IDSTATUS,'C','02',DECODE(NF.IDENTRSAIDOP,'S', (CASE WHEN DTEMISSAO < P_DTINICIAL THEN DECODE(NF.CDTIPOOPER,'03','07',TIPOOPER_COMPL_S,'07','01') ELSE DECODE(NF.CDTIPOOPER,'03','06',TIPOOPER_COMPL_S,'06','00') END),(CASE WHEN DTENTRSAID < P_DTINICIAL THEN DECODE(NF.CDTIPOOPER,'03','07',TIPOOPER_COMPL_E,'07','01')ELSE DECODE(NF.CDTIPOOPER,'03','06',TIPOOPER_COMPL_E,'06','00') END))) AS SITU_DOC,
                                NF.IDSTATUSNFE, NVL(NF.IDSIMPLESNACIONAL,'N') AS IDSIMPLESNACIONAL, NF.QTDEPARC, NF.CDTIPOOPER, DECODE(NF.IDENTRSAIDOP,'S',NF.CDFILIEMIT,NF.CDFILIRECE) AS FILIAL
                        FROM (/*NF SAÍDA SEM CARGA TRIBUTÁRIA*/
                              SELECT DECODE(N.IDENTRSAIDOP, 'E', '0','1') AS CAMPO2,
                                     DECODE(N.IDENTRSAIDOP, 'E', DECODE(IDSTATUSNFE,'A','0',DECODE(IDSTATUS,'E','0','1')), '0') AS CAMPO3, NRACESSONFE,
                                     I.CDFILIAL, I.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE) AS CDSERIE, NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS CDSERIEENTR,
                                     N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, TO_CHAR(N.VRPRODUTOS) AS VRPRODUTOS, N.IDPGTOFRETE,
                                     N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU,
                                     N.CDFILIEMIT, N.CDFILIRECE, N.DTEMISSAO, MAX(I.CDFISCOPERNF) AS CDFISCOPERNF, N.CDMODDOCFISC, N.CDCLIENTE, N.CDFORNECED, N.IDORIGDESTNF,
                                     TO_CHAR(SUM(I.VRCONTABILNF)) AS VRCONTABILNF, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'1',I.VRBASECALCNF,0))) AS VRBASECALCNF,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'1',I.VRIMPOSTONF,0)))  AS VRIMPOSTONF,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'3',I.VRCONTABILNF,0)))   AS VROUTRCRED,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'2',I.VRCONTABILNF,'1',DECODE(I.VRPERREDBCNF,0, 0,I.VRCONTABILNF-I.VRBASECALCNF), 0))) AS VRISENTRIB,
                                     N.NRNOTAFISCALELE, N.CDTIPOOPER, N.IDSTATUSNFE, DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'S') AS IDSIMPLESNACIONAL,
                                     MAX((SELECT COUNT(DISTINCT NRPARCELAREC)
                                            FROM CONTARECEBER C
                                           WHERE N.CDFILIAL = C.CDFILIAL
                                             AND N.NRLANCTONF = C.NRLANCTONF
                                             AND C.NRLANBOLREC IS NOT NULL)) AS QTDEPARC
                              FROM NOTAFISCAL N, IMPOSTONF I, IMPOSTO IP, PARAMFORNE PF, SERIENF SS, SERIEENTR SE
                              WHERE N.NRSEQUMAPAPUSN  = V_NRSEQUMAPAPU
                                AND N.CDINSCESTA      = P_CDINSCESTA
                                AND IP.CDIMPOSTONFE   = P_CDIMPOSTO
                                AND IP.CDIMPOSTO      = I.CDIMPOSTO
                                AND (NVL(N.IDSISTEMA,'DFS') <> 'REC'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS')
                                AND SE.CDSERIEENTR(+) = N.CDSERIEENTR
                                AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                AND SS.CDSERIE(+)     = N.CDSERIE
                                AND N.IDENTRSAIDOP    = 'S'
                                AND NVL(I.IDIMPOSTONF, '1') <> '3'
                                AND N.CDFILIAL        = I.CDFILIAL
                                AND N.NRLANCTONF      = I.NRLANCTONF
                                AND N.CDFORNECED      = PF.CDFORNECED(+)
                                AND ((N.IDSTATUS = 'A') OR (N.IDSTATUS = 'E'))
                                AND N.CDMODDOCFISC IN ('01','1B','04','55')
                                AND NVL(P_GERAFORSALE,'N') = 'N'
                                AND VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1') = 0
                              GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), I.CDFILIAL, I.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE), NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR),
                                     N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, TO_CHAR(N.VRPRODUTOS), N.IDPGTOFRETE,
                                     N.DTEMISSAO, N.CDMODDOCFISC, N.CDCLIENTE, N.CDFORNECED, N.IDORIGDESTNF,
                                     N.CDFILIEMIT, N.CDFILIRECE, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                     N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU, NRACESSONFE, N.NRNOTAFISCALELE, N.CDTIPOOPER, N.IDSTATUSNFE,
                                     DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'S')
                              UNION ALL
                              /*NF SAÍDA COM CARGA TRIBUTÁRIA*/
                              SELECT DECODE(N.IDENTRSAIDOP, 'E', '0','1') AS CAMPO2,
                                     DECODE(N.IDENTRSAIDOP, 'E', DECODE(IDSTATUSNFE,'A','0',DECODE(IDSTATUS,'E','0','1')), '0') AS CAMPO3, NRACESSONFE,
                                     I.CDFILIAL, I.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE) AS CDSERIE, NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS CDSERIEENTR,
                                     N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, TO_CHAR(N.VRPRODUTOS) AS VRPRODUTOS, N.IDPGTOFRETE,
                                     N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU,
                                     N.CDFILIEMIT, N.CDFILIRECE, N.DTEMISSAO, MAX(I.CDFISCOPERNF) AS CDFISCOPERNF, N.CDMODDOCFISC, N.CDCLIENTE, N.CDFORNECED, N.IDORIGDESTNF,
                                     TO_CHAR(SUM(I.VRCONTABILNF)) AS VRCONTABILNF, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                     TO_CHAR(DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','B','1')))) AS VRBASECALCNF,
                                     TO_CHAR(DECODE(V_IDTPCARGATRIB,'O',0,VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1')))  AS VRIMPOSTONF,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'3',I.VRCONTABILNF,0)))   AS VROUTRCRED,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'2',I.VRCONTABILNF,'1',DECODE(I.VRPERREDBCNF,0, 0,I.VRCONTABILNF-I.VRBASECALCNF), 0))) AS VRISENTRIB,
                                     N.NRNOTAFISCALELE, N.CDTIPOOPER, N.IDSTATUSNFE, DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'S') AS IDSIMPLESNACIONAL,
                                     MAX((SELECT COUNT(DISTINCT NRPARCELAREC)
                                            FROM CONTARECEBER C
                                           WHERE N.CDFILIAL = C.CDFILIAL
                                             AND N.NRLANCTONF = C.NRLANCTONF
                                             AND C.NRLANBOLREC IS NOT NULL)) AS QTDEPARC
                              FROM NOTAFISCAL N, IMPOSTONF I, IMPOSTO IP, PARAMFORNE PF, SERIENF SS, SERIEENTR SE
                              WHERE N.NRSEQUMAPAPUSN  = V_NRSEQUMAPAPU
                                AND N.CDINSCESTA      = P_CDINSCESTA
                                AND IP.CDIMPOSTONFE   = P_CDIMPOSTO
                                AND IP.CDIMPOSTO      = I.CDIMPOSTO
                                AND (NVL(N.IDSISTEMA,'DFS') <> 'REC'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS')
                                AND SE.CDSERIEENTR(+) = N.CDSERIEENTR
                                AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                AND SS.CDSERIE(+)     = N.CDSERIE
                                AND N.IDENTRSAIDOP    = 'S'
                                AND NVL(I.IDIMPOSTONF, '1') <> '3'
                                AND N.CDFILIAL        = I.CDFILIAL
                                AND N.NRLANCTONF      = I.NRLANCTONF
                                AND N.CDFORNECED      = PF.CDFORNECED(+)
                                AND ((N.IDSTATUS = 'A') OR (N.IDSTATUS = 'E'))
                                AND N.CDMODDOCFISC IN ('01','1B','04','55')
                                AND NVL(P_GERAFORSALE,'N') = 'N'
                                AND VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1') > 0
                              GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), I.CDFILIAL, I.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE), NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR),
                                     N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, TO_CHAR(N.VRPRODUTOS), N.IDPGTOFRETE,
                                     N.DTEMISSAO, N.CDMODDOCFISC, N.CDCLIENTE, N.CDFORNECED, N.IDORIGDESTNF,
                                     N.CDFILIEMIT, N.CDFILIRECE, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                     N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU, NRACESSONFE, N.NRNOTAFISCALELE, N.CDTIPOOPER, N.IDSTATUSNFE,
                                     DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'S'), VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','B','1'), VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1')
                              UNION ALL
                              /******** NOTA CANCELADA *******/
                              SELECT DECODE(N.IDENTRSAIDOP, 'E', '0','1') AS CAMPO2,
                                     '0' AS CAMPO3, NRACESSONFE,
                                     N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC,NVL(SS.CDSERIENFE,N.CDSERIE) AS CDSERIE, NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS CDSERIEENTR,
                                     '' AS NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, '' AS VRPRODUTOS, N.IDPGTOFRETE,
                                     N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU,
                                     '' AS CDFILIEMIT, '' AS CDFILIRECE, N.DTEMISSAO, '' AS CDFISCOPERNF, N.CDMODDOCFISC, '' AS CDCLIENTE, '' AS CDFORNECED, N.IDORIGDESTNF,
                                     '' AS VRCONTABILNF, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                     '' AS VRBASECALCNF,
                                     '' AS VRIMPOSTONF,
                                     '' AS VROUTRCRED,
                                     '' AS VRISENTRIB,
                                     NRNOTAFISCALELE,
                                     N.CDTIPOOPER, N.IDSTATUSNFE, 'N' AS IDSIMPLESNACIONAL, 0 AS QTDEPARC
                               FROM NOTAFISCAL N, SERIENF SS, SERIEENTR SE
                              WHERE (NVL(N.IDSISTEMA,'DFS') <> 'REC'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS')
                                AND SE.CDSERIEENTR(+) = N.CDSERIEENTR
                                AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                AND SS.CDSERIE(+)     = N.CDSERIE
                                AND N.IDENTRSAIDOP = 'S'
                                AND N.IDSTATUS = 'C'
                                AND N.CDMODDOCFISC IN ('01','1B','04','55')
                                AND N.DTEMISSAO BETWEEN P_DTINICIAL AND P_DTFINAL
                                AND N.CDINSCESTA = P_CDINSCESTA
                                AND N.CDEMPRESA = P_CDEMPRESA
                              GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE), NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR),
                                       N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, N.IDPGTOFRETE, N.CDMODDOCFISC, N.CDCLIENTE,
                                       N.CDFORNECED, N.IDORIGDESTNF, N.CDFILIEMIT, N.CDFILIRECE, N.DTEMISSAO, N.NRINSJURTRAN, N.IDTPIJURTRAN,
                                       N.VRPBRUTOVOLU, N.VRPLIQUVOLU, N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU,
                                       N.DSNUMEVOLU, N.NRACESSONFE, N.CDTIPOOPER, N.IDSTATUSNFE, N.NRNOTAFISCALELE
                              UNION ALL
                              /*NF ENTRADA SEM CARGA TRIBUTÁRIA*/
                              SELECT DECODE(N.IDENTRSAIDOP, 'E', '0','1') AS CAMPO2,
                                     DECODE(N.IDENTRSAIDOP, 'E', DECODE(IDSTATUSNFE,'A','0',DECODE(IDSTATUS,'E','0','1')), '0') AS CAMPO3, NRACESSONFE,
                                     I.CDFILIAL, I.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE) AS CDSERIE, NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS CDSERIEENTR,
                                     N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, TO_CHAR(N.VRPRODUTOS) AS VRPRODUTOS, N.IDPGTOFRETE,
                                     N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU,
                                     N.CDFILIEMIT, N.CDFILIRECE, N.DTEMISSAO, MAX(I.CDFISCOPERNF) AS CDFISCOPERNF, N.CDMODDOCFISC, N.CDCLIENTE, N.CDFORNECED, N.IDORIGDESTNF,
                                     TO_CHAR(SUM(I.VRCONTABILNF)) AS VRCONTABILNF, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'1',I.VRBASECALCNF,0))) AS VRBASECALCNF,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'1',I.VRIMPOSTONF,0)))  AS VRIMPOSTONF,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'3',I.VRCONTABILNF,0)))   AS VROUTRCRED,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'2',I.VRCONTABILNF,'1',DECODE(I.VRPERREDBCNF,0, 0,I.VRCONTABILNF-I.VRBASECALCNF), 0))) AS VRISENTRIB,
                                     N.NRNOTAFISCALELE, N.CDTIPOOPER, N.IDSTATUSNFE, DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'N') AS IDSIMPLESNACIONAL,
                                     MAX((SELECT COUNT(DISTINCT C.NRPARCELAPAG)
                                            FROM CONTAPAGAR C
                                           WHERE N.CDFILIAL   = C.CDFILIAL
                                             AND N.NRLANCTONF = C.NRLANCTONF
                                             AND C.NRLANBOLPAG IS NOT NULL)) AS QTDEPARC
                              FROM NOTAFISCAL N, IMPOSTONF I, IMPOSTO IP, PARAMFORNE PF, SERIENF SS, SERIEENTR SE
                              WHERE N.NRSEQUMAPAPUSN  = V_NRSEQUMAPAPU
                                AND N.CDINSCESTA      = P_CDINSCESTA
                                AND IP.CDIMPOSTONFE   = P_CDIMPOSTO
                                AND IP.CDIMPOSTO      = I.CDIMPOSTO
                                AND (NVL(N.IDSISTEMA,'DFS')  <> 'REC'
                                AND NVL(N.IDSISTEMA, 'DFS')  <> 'PAG'
                                AND NVL(N.IDSISTEMA, 'DFS')  <> 'CMP'
                                AND NVL(N.IDSISTEMA, 'DFS')  <> 'SUP'
                                AND NVL(N.IDSISTEMA, 'DFS')  <> 'TMP'
                                AND NVL(N.IDSISTEMA, 'DFS')  <> 'FIS')
                                AND SE.CDSERIEENTR(+) = N.CDSERIEENTR
                                AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                AND SS.CDSERIE(+)     = N.CDSERIE
                                AND N.IDENTRSAIDOP    = 'E'
                                AND PF.CDFORNECED(+)  = N.CDFORNECED
                                AND NVL(I.IDIMPOSTONF, '1') <> '3'
                                AND N.CDFILIAL        = I.CDFILIAL
                                AND N.NRLANCTONF      = I.NRLANCTONF
                                AND ((N.IDSTATUS = 'A') OR (N.IDSTATUS = 'E'))
                                AND N.CDMODDOCFISC IN ('01','1B','04','55')
                                AND NVL(P_GERAFORSALE,'N') = 'N'
                                AND VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1') = 0
                              GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), I.CDFILIAL, I.NRLANCTONF, N.IDENTRSAIDOP,
                                     N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE), NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR), N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, NRACESSONFE,
                                     N.VRNOTAFISC, TO_CHAR(N.VRPRODUTOS), N.IDPGTOFRETE, N.DTEMISSAO , N.CDMODDOCFISC, N.CDCLIENTE,
                                     N.CDFORNECED, N.IDORIGDESTNF, N.CDFILIEMIT, N.CDFILIRECE, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                     N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU, NRACESSONFE, N.NRNOTAFISCALELE, N.CDTIPOOPER, IDSTATUSNFE,
                                     DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'N')
                              UNION ALL
                              /*NF ENTRADA COM CARGA TRIBUTÁRIA*/
                              SELECT DECODE(N.IDENTRSAIDOP, 'E', '0','1') AS CAMPO2,
                                     DECODE(N.IDENTRSAIDOP, 'E', DECODE(IDSTATUSNFE,'A','0',DECODE(IDSTATUS,'E','0','1')), '0') AS CAMPO3, NRACESSONFE,
                                     I.CDFILIAL, I.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE) AS CDSERIE, NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS CDSERIEENTR,
                                     N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, TO_CHAR(N.VRPRODUTOS) AS VRPRODUTOS, N.IDPGTOFRETE,
                                     N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU,
                                     N.CDFILIEMIT, N.CDFILIRECE, N.DTEMISSAO, MAX(I.CDFISCOPERNF) AS CDFISCOPERNF, N.CDMODDOCFISC, N.CDCLIENTE, N.CDFORNECED, N.IDORIGDESTNF,
                                     TO_CHAR(SUM(I.VRCONTABILNF)) AS VRCONTABILNF, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'1',I.VRBASECALCNF,0)+DECODE(V_IDTPCARGATRIB,'O',0,CASE WHEN V_SGESTADO <> 'SP' THEN VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','B','1') ELSE 0 END))) AS VRBASECALCNF,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'1',I.VRIMPOSTONF, 0)+DECODE(V_IDTPCARGATRIB,'O',0,CASE WHEN V_SGESTADO <> 'SP' THEN VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1') ELSE 0 END))) AS VRIMPOSTONF,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'3',I.VRCONTABILNF,0)))   AS VROUTRCRED,
                                     TO_CHAR(SUM(DECODE(I.CDFISCALNF,'2',I.VRCONTABILNF,'1',DECODE(I.VRPERREDBCNF,0, 0,I.VRCONTABILNF-I.VRBASECALCNF), 0))) AS VRISENTRIB,
                                     N.NRNOTAFISCALELE, N.CDTIPOOPER, N.IDSTATUSNFE, DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'N') AS IDSIMPLESNACIONAL,
                                     MAX((SELECT COUNT(DISTINCT NRPARCELAPAG)
                                            FROM CONTAPAGAR C
                                           WHERE N.CDFILIAL = C.CDFILIAL
                                             AND N.NRLANCTONF = C.NRLANCTONF
                                             AND C.NRLANBOLPAG IS NOT NULL)) AS QTDEPARC
                              FROM NOTAFISCAL N, IMPOSTONF I, IMPOSTO IP, PARAMFORNE PF, SERIENF SS, SERIEENTR SE
                              WHERE N.NRSEQUMAPAPUSN  = V_NRSEQUMAPAPU
                                AND N.CDINSCESTA      = P_CDINSCESTA
                                AND IP.CDIMPOSTONFE   = P_CDIMPOSTO
                                AND IP.CDIMPOSTO      = I.CDIMPOSTO
                                AND (NVL(N.IDSISTEMA,'DFS')  <> 'REC'
                                AND NVL(N.IDSISTEMA, 'DFS')  <> 'PAG'
                                AND NVL(N.IDSISTEMA, 'DFS')  <> 'CMP'
                                AND NVL(N.IDSISTEMA, 'DFS')  <> 'SUP'
                                AND NVL(N.IDSISTEMA, 'DFS')  <> 'TMP'
                                AND NVL(N.IDSISTEMA, 'DFS')  <> 'FIS')
                                AND SE.CDSERIEENTR(+) = N.CDSERIEENTR
                                AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                AND SS.CDSERIE(+)     = N.CDSERIE
                                AND N.IDENTRSAIDOP    = 'E'
                                AND PF.CDFORNECED(+)  = N.CDFORNECED
                                AND NVL(I.IDIMPOSTONF, '1') <> '3'
                                AND N.CDFILIAL        = I.CDFILIAL
                                AND N.NRLANCTONF      = I.NRLANCTONF
                                AND ((N.IDSTATUS = 'A') OR (N.IDSTATUS = 'E'))
                                AND N.CDMODDOCFISC IN ('01','1B','04','55')
                                AND NVL(P_GERAFORSALE,'N') = 'N'
                                AND VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1') > 0
                              GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), I.CDFILIAL, I.NRLANCTONF, N.IDENTRSAIDOP,
                                     N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE), NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR), N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, NRACESSONFE,
                                     N.VRNOTAFISC, TO_CHAR(N.VRPRODUTOS), N.IDPGTOFRETE, N.DTEMISSAO , N.CDMODDOCFISC, N.CDCLIENTE,
                                     N.CDFORNECED, N.IDORIGDESTNF, N.CDFILIEMIT, N.CDFILIRECE, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                     N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU, NRACESSONFE, N.NRNOTAFISCALELE, N.CDTIPOOPER, IDSTATUSNFE,
                                     DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'N')
                              UNION
                              /*******NOTAS FISCAIS FORSALE - C100 FOS ***********/
                              SELECT DECODE(NF.IDENTRSAIDOP, 'E', '0','1') AS CAMPO2,
                                     DECODE(NF.IDENTRSAIDOP, 'E', DECODE(IDSTATUS,'E','0','1'), '0') AS CAMPO3, NRACESSONFE,
                                     NF.CDFILIAL, NF.NRLANCTONF, NF.IDENTRSAIDOP, NF.NRNOTAFISC, NF.CDSERIE, NF.CDSERIEENTR,
                                     NF.NRINSJURNF, NF.IDSTATUS, NF.DTENTRSAID, NF.VRNOTAFISC, TO_CHAR(NF.VRPRODUTOS) AS VRPRODUTOS, NF.IDPGTOFRETE,
                                     NF.NRPLACAVEIC, NF.DSQTDEVOLU, NF.DSESPECVOLU, NF.DSMARCAVOLU, NF.DSNUMEVOLU,
                                     NF.CDFILIEMIT, NF.CDFILIRECE, NF.DTEMISSAO, MAX(NF.CDFISCOPERNF) AS CDFISCOPERNF, NF.CDMODDOCFISC, NF.CDCLIENTE, NF.CDFORNECED, NF.IDORIGDESTNF,
                                     NF.VRCONTABILNF AS VRCONTABILNF,
                                     NF.NRINSJURTRAN, NF.IDTPIJURTRAN, NF.VRPBRUTOVOLU, NF.VRPLIQUVOLU,
                                     TO_CHAR(VRBASECALCNF) AS VRBASECALCNF,
                                     TO_CHAR(VRIMPOSTONF),
                                     TO_CHAR(VROUTRCRED),
                                     TO_CHAR(VRISENTRIB),
                                     NF.NRNOTAFISCALELE,
                                     NF.CDTIPOOPER, '' AS IDSTATUSNFE, NF.IDSIMPLESNACIONAL, NF.QTDEPARC
                               FROM  ENDECLIE EC, ENDEFORN EF, ENDEFILI EFI,
                                (SELECT DECODE(NVL(N.IDORIGDESTNF,DECODE(N.IDENTRSAIDOP,'S','C','F')),'C',CL.NRINSJURCLIE,'F',FO.NRINSJURFORN,'L',FI.NRINSJURFILI) AS NRINSJURNF,
                                        DECODE(NVL(N.IDORIGDESTNF,DECODE(N.IDENTRSAIDOP,'S','C','F')),'C',CL.NRINSESTCLIE,'F',FO.NRINSESTFORN,'L',FI.CDINSCESTA  ) AS NRINSEST,
                                        N.IDORIGDESTNF, N.CDCLIENTE, N.CDFORNECED, N.CDFILIEMIT, N.CDFILIRECE, N.NRNOTAFISC, I.CDFISCOPERNF,
                                        N.NRLANCTONF,N.CDFILIAL, N.IDENTRSAIDOP, DECODE(N.CDMODDOCFISC,'2D','55',N.CDMODDOCFISC) AS CDMODDOCFISC,
                                        NVL(SS.CDSERIENFE,N.CDSERIE) AS CDSERIE, NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS CDSERIEENTR, N.DTENTRSAID, N.DTEMISSAO,
                                        TO_CHAR(SUM(VRCONTABILNF)) AS VRCONTABILNF,
                                        DECODE(I.CDFISCALNF,'1',SUM(VRBASECALCNF),0) AS VRBASECALCNF,
                                        DECODE(I.CDFISCALNF,'2',SUM(VRCONTABILNF),'1',SUM(DECODE(I.VRPERREDBCNF,0, 0,I.VRCONTABILNF-I.VRBASECALCNF)),0) AS VRISENTRIB,
                                        DECODE(I.CDFISCALNF,'3',SUM(VRCONTABILNF),0) AS VROUTRCRED,
                                        DECODE(I.CDFISCALNF,'1',SUM(VRIMPOSTONF ),0) AS VRIMPOSTONF,
                                        SUM(N.VRPRODUTOS) AS VRPRODUTOS,
                                        N.NRINSJURTRAN,N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU, N.NRNOTAFISCALELE, I.VRPERREDBCNF,N.IDSTATUS,N.IDPGTOFRETE,
                                        N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU,N.VRNOTAFISC, NRACESSONFE, N.CDTIPOOPER,
                                        DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'S') AS IDSIMPLESNACIONAL,
                                        MAX((SELECT COUNT(DISTINCT NRPARCELAREC)
                                               FROM CONTARECEBER C
                                              WHERE N.CDFILIAL    = C.CDFILIAL
                                                AND N.NRLANCTONF  = C.NRLANCTONF
                                                AND C.NRLANBOLREC IS NOT NULL)) AS QTDEPARC
                                   FROM NOTAFISCAL N, IMPOSTONF I, IMPOSTO IMP, CLIENTE CL, FORNECEDOR FO, FILIAL FI, PARAMFORNE PF, SERIENF SS, SERIEENTR SE
                                  WHERE N.CDFILIAL     = I.CDFILIAL
                                    AND N.NRLANCTONF   = I.NRLANCTONF
                                    AND IMP.CDIMPOSTO  = I.CDIMPOSTO
                                    AND N.CDCLIENTE    = CL.CDCLIENTE(+)
                                    AND N.CDFORNECED   = FO.CDFORNECED(+)
                                    AND N.CDFORNECED   = PF.CDFORNECED(+)
                                    AND N.CDFILIRECE   = FI.CDFILIAL(+)
                                    AND N.CDFILIEMIT   = FI.CDFILIAL(+)
                                    AND DTEMISSAO BETWEEN P_DTINICIAL AND P_DTFINAL
                                    AND ((N.IDSTATUS   = 'A' OR N.IDSTATUS = 'E') OR (N.IDSTATUSNFE = 'A' OR N.IDSTATUSNFE = 'T'))
                                    AND N.CDINSCESTA   = P_CDINSCESTA
                                    AND IMP.CDIMPOSTONFE = P_CDIMPOSTO
                                    AND (I.IDIMPOSTONF <> '3' OR IDIMPOSTONF IS NULL)
                                    AND (NVL(N.IDSISTEMA, 'DFS') <> 'REC'
                                    AND NVL(N.IDSISTEMA, 'DFS')  <> 'PAG'
                                    AND NVL(N.IDSISTEMA, 'DFS')  <> 'CMP'
                                    AND NVL(N.IDSISTEMA, 'DFS')  <> 'SUP'
                                    AND NVL(N.IDSISTEMA, 'DFS')  <> 'TMP'
                                    AND NVL(N.IDSISTEMA, 'DFS')  <> 'FIS')
                                    AND SE.CDSERIEENTR(+) = N.CDSERIEENTR
                                    AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                    AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                    AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                    AND SS.CDSERIE(+)     = N.CDSERIE
                                    AND N.CDMODDOCFISC IN ('01','1B','04','55','2D')
                                    AND N.IDENTRSAIDOP = 'S'
                                    AND NVL(P_GERAFORSALE,'N') = 'S'
                                  GROUP BY DECODE(NVL(N.IDORIGDESTNF,DECODE(N.IDENTRSAIDOP,'S','C','F')),'C',CL.NRINSJURCLIE,'F',FO.NRINSJURFORN,'L',FI.NRINSJURFILI),
                                           DECODE(NVL(N.IDORIGDESTNF,DECODE(N.IDENTRSAIDOP,'S','C','F')),'C',CL.NRINSESTCLIE,'F',FO.NRINSESTFORN,'L',FI.CDINSCESTA),N.IDORIGDESTNF,
                                           N.CDCLIENTE, N.CDFORNECED, N.CDFILIEMIT, N.CDFILIRECE, N.NRNOTAFISC, I.CDFISCOPERNF, N.NRLANCTONF,
                                           N.CDFILIAL, N.IDENTRSAIDOP, N.CDMODDOCFISC, NVL(SS.CDSERIENFE,N.CDSERIE), NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR),
                                           N.DTENTRSAID, N.DTEMISSAO,  I.CDFISCALNF, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU,
                                           N.VRPLIQUVOLU,N.NRNOTAFISCALELE,I.VRPERREDBCNF,N.IDSTATUS,IDPGTOFRETE,
                                           N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU,N.VRNOTAFISC,NRACESSONFE,N.CDTIPOOPER,DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'S'))NF
                              WHERE NF.CDCLIENTE    = EC.CDCLIENTE(+)
                                AND NF.CDFORNECED   = EF.CDFORNECED(+)
                                AND NF.CDFILIEMIT   = EFI.CDFILIAL(+)
                                AND NF.CDFILIRECE   = EFI.CDFILIAL(+)
                                AND IDTPENDECLIE(+) = 'P'
                                AND IDTPENDEFORN(+) = 'P'
                                AND IDTPENDEFILI(+) = 'P'
                                AND NVL(P_GERAFORSALE,'N') = 'S'
                              GROUP BY DECODE(NF.IDENTRSAIDOP, 'E', '0','1'),
                                       DECODE(NF.IDENTRSAIDOP, 'E', DECODE(IDSTATUS,'E','0','1'), '0'), NRACESSONFE,
                                       NF.CDFILIAL, NF.NRLANCTONF, NF.IDENTRSAIDOP, NF.NRNOTAFISC, NF.CDSERIE, NF.CDSERIEENTR,
                                       NF.NRINSJURNF, NF.IDSTATUS, NF.DTENTRSAID, NF.VRNOTAFISC, TO_CHAR(NF.VRPRODUTOS), NF.IDPGTOFRETE,
                                       NF.NRPLACAVEIC, NF.DSQTDEVOLU, NF.DSESPECVOLU, NF.DSMARCAVOLU, NF.DSNUMEVOLU,
                                       NF.CDFILIEMIT, NF.CDFILIRECE, NF.DTEMISSAO, NF.CDMODDOCFISC, NF.CDCLIENTE, NF.CDFORNECED, NF.IDORIGDESTNF,
                                       NF.VRCONTABILNF, NF.NRINSJURTRAN, NF.IDTPIJURTRAN, NF.VRPBRUTOVOLU, NF.VRPLIQUVOLU,
                                       TO_CHAR(VRBASECALCNF), TO_CHAR(VRIMPOSTONF), TO_CHAR(VROUTRCRED), TO_CHAR(VRISENTRIB),
                                       NF.NRNOTAFISCALELE,NF.CDTIPOOPER,NF.IDSIMPLESNACIONAL, NF.QTDEPARC)NF )LOOP
           IF C_REGC100.IDSTATUS = 'C' THEN
              V_DADOS_2 := '|';
           ELSE
              IF C_REGC100.IDENTRSAIDOP = 'E' THEN
                 V_DADOS_2 := TO_CHAR(C_REGC100.DTENTRSAID,'ddmmyyyy') || '|';
              ELSE
                 V_DADOS_2 := TO_CHAR(C_REGC100.DTEMISSAO,'ddmmyyyy') || '|';
              END IF;
           END IF;
          V_VRDEBESP := 0;
          /* valor total de imposto fora do periodo - nf saida */
          V_VRFORAPER := 0;
          IF (C_REGC100.SITU_DOC IN ('01', '07')) AND (C_REGC100.IDENTRSAIDOP = 'S') THEN
             BEGIN
                SELECT SUM(VRIMPOSTONF)
                INTO V_VRFORAPER
                FROM IMPOSTONF
                WHERE CDFILIAL = C_REGC100.CDFILIAL
                  AND NRLANCTONF = C_REGC100.NRLANCTONF
                  AND CDFISCALNF = '1'
                  AND NVL(IDIMPOSTONF,'1') <> '3';
             EXCEPTION
                WHEN NO_DATA_FOUND THEN
                   V_VRFORAPER := 0;
             END;
             V_TOTFORPER_S :=  NVL(V_TOTFORPER_S,0)+NVL(V_VRFORAPER,0);
          END IF;

          INSERT INTO ARQMAGNETICO
            (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
          VALUES
            ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC100.DADOS_1||V_DADOS_2||C_REGC100.DADOS_3, P_NRSEQARQMAG);
          V_CONTREGC :=  NVL(V_CONTREGC,0) + 1;
          V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');

          /* CODIGO DO PARTICIPANTE */
          SELECT MAX(CDCHAVEREG)
            INTO V_COD_PAR
            FROM TMP_REGDADOSSPED
           WHERE CDCHAVEREG = C_REGC100.COD_PAR
             AND CDREGISTRO = '0150';

          IF (V_COD_PAR IS NULL) AND (C_REGC100.COD_PAR IS NOT NULL) THEN
             V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
             INSERT INTO TMP_REGDADOSSPED
               (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
             VALUES
               ('0150', V_SEQUPROD, C_REGC100.COD_PAR);
          END IF;
          V_COD_PAR := NULL;
          /*REGISTRO C110 - OBSERVAÇÃO DO DOCUMENTO*/
          FOR C_REGC110 IN (SELECT '|C110'                                  ||'|'||
                                   LPAD(RTRIM(TO_CHAR(V_SEQADIC)),6,'0')    ||'|'||
                                   'CUPOM FISCAL REFERENCIADO - COO NÚMERO '||TRIM(D.NRCOOCUPOMNF)||'|'  AS DSREGC110,
                                   '|C114'                                  ||'|'||
                                   '2D'                                     ||'|'||
                                   SUBSTR(D.NRSERIEIMPNF,1,21)              ||'|'||
                                   SUBSTR(LPAD(D.NRCOOCUPOMNF,10,'0'),5,6)  ||'|'||
                                   TO_CHAR(C_REGC100.DTEMISSAO,'DDMMYYYY')  ||'|' AS DSREGC114
                              FROM DADOSNF D, NOTAFISCAL N
                             WHERE D.NRLANCTONF  = C_REGC100.NRLANCTONF
                               AND D.CDFILIAL    = C_REGC100.CDFILIAL
                               AND D.NRECFCUPOMNF IS NOT NULL
                               AND D.NRLANCTONF  = N.NRLANCTONF
                               AND D.CDFILIAL    = N.CDFILIAL
                               AND NOT ((N.IDSTATUSNFE = 'A') OR (N.CDMODDOCFISC = '55')))LOOP

             INSERT INTO ARQMAGNETICO
                (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
              VALUES ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC110.DSREGC110 , P_NRSEQARQMAG);
                   V_CONTREGC :=  NVL(V_CONTREGC,0) + 1;
                   V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');

             /*REGISTRO C114 - CUPOM FISCAL REFERENCIADO*/
             INSERT INTO ARQMAGNETICO
                (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
              VALUES ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC110.DSREGC114 , P_NRSEQARQMAG);
                   V_CONTREGC :=  NVL(V_CONTREGC,0) + 1;
                   V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');
              V_SEQADIC := V_SEQADIC +1;
          END LOOP;

          /*REGISTRO C110 - OBSERVAÇÃO DO DOCUMENTO -- DADOSADIC*/
          FOR C_REGC110 IN (SELECT D.DSDADOADIC AS DSREGC110
                              FROM DADOSADIC D, NOTAFISCAL N
                             WHERE D.NRLANCTONF  = C_REGC100.NRLANCTONF
                               AND D.CDFILIAL    = C_REGC100.CDFILIAL
                               AND D.NRLANCTONF  = N.NRLANCTONF
                               AND D.CDFILIAL    = N.CDFILIAL
                               AND NOT ((N.IDSTATUSNFE = 'A') OR (N.CDMODDOCFISC = '55')))LOOP
             V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;

             INSERT INTO ARQMAGNETICO (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
             VALUES ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), '|C110|'||LPAD(RTRIM(TO_CHAR(V_SEQADIC)),6,'0')||'|'||TRIM(SUBSTR(C_REGC110.DSREGC110, 0,499))||'|', P_NRSEQARQMAG);
             V_CONTREGC :=  NVL(V_CONTREGC,0) + 1;
             V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');

             INSERT INTO TMP_REGDADOSSPED (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
             VALUES ('0450', V_SEQUPROD, LPAD(RTRIM(TO_CHAR(V_SEQADIC)),6,'0'), TRIM(SUBSTR(C_REGC110.DSREGC110, 0, 499)));
             V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');
             V_SEQADIC := V_SEQADIC +1;
          END LOOP;

          /*QUANDO A OPERAÇÃO FOR A PRAZO PARA AS ENTRADAS NOS MODELOS 1 E 1A DEVER SER GERADOS OS REGISTROS REFERENTES A FATURA*/
          IF (C_REGC100.CDMODDOCFISC IN ('01','1A')) AND (C_REGC100.QTDEPARC > 1) THEN
             /*REGISTRO C140*/
             FOR C_REGC140 IN (SELECT '|C140'                                                               ||'|'||
                                      DECODE(N.IDENTRSAIDOP,'E','1','S','0')                                ||'|'||
                                      DECODE(F.IDTPTITULOCRED,'XX','',F.IDTPTITULOCRED)                     ||'|'||
                                      DECODE(F.IDTPTITULOCRED,'99',F.DSTPTITULOCRED,'')                     ||'|'||
                                      LTRIM(N.NRNOTAFISC,'0')                                               ||'|'||
                                      LPAD(RTRIM(TO_CHAR(C_REGC100.QTDEPARC)),2,'0')                        ||'|'||
                                      REPLACE(LTRIM(TO_CHAR(SUM(C.VRORIGPAG),'999999999990.00')), '.', ',') ||'|' AS DSREG_C140
                                 FROM NOTAFISCAL N, FORNECEDOR F, CONTAPAGAR C
                                WHERE N.CDFILIAL   = C_REGC100.CDFILIAL
                                  AND N.NRLANCTONF = C_REGC100.NRLANCTONF
                                  AND N.CDFORNECED = F.CDFORNECED
                                  AND N.CDFILIAL   = C.CDFILIAL
                                  AND N.NRLANCTONF = C.NRLANCTONF
                                GROUP BY N.IDENTRSAIDOP, F.IDTPTITULOCRED, F.DSTPTITULOCRED,
                                      N.NRNOTAFISC, C_REGC100.QTDEPARC) LOOP

                INSERT INTO ARQMAGNETICO
                   (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                VALUES
                   ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC140.DSREG_C140, P_NRSEQARQMAG);
                V_CONTREGC   := NVL(V_CONTREGC,0) + 1;
             END LOOP;

             /*REGISTRO C141*/
             FOR C_REGC141 IN (SELECT '|C141'                                                               ||'|'||
                                      LPAD(RTRIM(TO_CHAR(C.NRPARCELAPAG)),2,'0')                            ||'|'||
                                      TO_CHAR(C.DTORIGVENPAG,'DDMMYYYY')                                    ||'|'||
                                      REPLACE(LTRIM(TO_CHAR(SUM(C.VRORIGPAG),'999999999990.00')), '.', ',') ||'|' AS DSREG_C141
                                 FROM CONTAPAGAR C
                                WHERE C.CDFILIAL   = C_REGC100.CDFILIAL
                                  AND C.NRLANCTONF = C_REGC100.NRLANCTONF
                                GROUP BY C.NRPARCELAPAG, C.DTORIGVENPAG
                                ORDER BY C.NRPARCELAPAG) LOOP

                INSERT INTO ARQMAGNETICO
                   (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                VALUES
                   ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC141.DSREG_C141, P_NRSEQARQMAG);
                V_CONTREGC   := NVL(V_CONTREGC,0) + 1;
             END LOOP;
          END IF;

          BEGIN
            SELECT IDATUESTTPOP
              INTO V_IDATUESTTPOP
              FROM TIPOOPERAC
             WHERE CDTIPOOPER   = C_REGC100.CDTIPOOPER
               AND IDENTRSAIDOP = C_REGC100.IDENTRSAIDOP;
          EXCEPTION
             WHEN NO_DATA_FOUND THEN
                V_IDATUESTTPOP := 'N';
          END;

          /*REGISTRO C170*/
          FOR C_REGC170 IN (SELECT COD_ITEM       || '|' ||
                                  DESCR_COMPL    || '|' ||
                                  QTD            || '|' ||
                                  UNID           || '|' ||
                                  VL_ITEM        || '|' ||
                                  VL_DESC        || '|' ||
                                  IND_MOV        || '|' ||
                                  CST_ICMS       || '|' ||
                                  CFOP           || '|' ||
                                  CFOP           || '|' || -- natureza da operacao campo 12
                                  VL_BC_ICMS     || '|' ||
                                  ALIQ_ICMS      || '|' ||
                                  VL_ICMS        || '|' ||
                                  VL_BC_ICMS_ST  || '|' || --16
                                  ALIQ_ST        || '|' || --17
                                  VL_ICMS_ST     || '|' || --18
                                  ''             || '|' || -- indicador de apurao do IPI CAMPO 19
                                  CST_IPI        || '|' || -- cst ipi campo 20
                                  '' 		       || '|' || -- Cdigo enquadramento IPI campo 21
                                  VL_BC_IPI      || '|' || --22
                                  ALIQ_IPI       || '|' || --23
                                  VL_IPI         || '|' || --24
                                  CST_PIS        || '|' || -- cst pis   campo 25
                                  VL_BC_PIS      || '|' ||
                                  ALIQ_PIS       || '|' ||
                                  ''  			    || '|' || -- quantidade base de calculo
                                  ''             || '|' || -- aliquota pis quantidade
                                  VL_PIS         || '|' ||
                                  CST_COFINS     || '|' || -- cst cofins campo 31
                                  VL_BC_COFINS   || '|' ||
                                  ALIQ_COFINS    || '|' ||
                                  ''    	       || '|' || -- quantidade base de calculo
                                  ''             || '|' || -- aliquota cofins quantidade
                                  VL_COFINS      || '|' ||
                                  COD_CTA        || '|' ||
                                  CASE WHEN P_VERSAO >= '013' THEN VL_ABAT_NT || '|' ELSE '' END AS ARQ_C170,  -- codigo da conta analitica contabil deb/cred
                                  CDPRODUTO, UNID, CFOP AS CDFISCOPERIT, DSCDFISOPEIT, CDCLASFISC, COD_CTA
                             FROM (/* NOTAS NÃO ELETRÓNICAS SEM CARGA TRIBUTÁRIA */
                                   SELECT PR.CDARVPROD AS COD_ITEM,
                                           DECODE(C_REGC100.IDENTRSAIDOP, 'E', TRIM(RETIRA_CARACTER_ESPECIAL(IT.DSPRODEMIS, 'S'))) AS DESCR_COMPL,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(IT.QTITEMPROD,3), '999999999990.000')), '.', ',') AS QTD,
                                           PR.SGUNIDADE  AS UNID,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(IT.VRTOTAITEM,2), '999999999990.00')), '.', ',') AS VL_ITEM,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(NVL(IT.VRENCARGODESC,0),2), '999999999990.00')), '.', ',') AS VL_DESC,
                                           DECODE(NVL(V_IDATUESTTPOP,'N'),'N','1','0') AS IND_MOV,
                                           LPAD(NVL(IP.CDSITUTRIBIT,0),3,'0') AS CST_ICMS,
                                           IP.CDFISCOPERIT AS CFOP,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', IP.VRBASECALCIT, 0),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', IP.VRALIQITEM, 0),2), '999999999990.00')), '.', ',')   AS ALIQ_ICMS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', IP.VRIMPOSTOIT, 0),2), '999999999990.00')), '.', ',')  AS VL_ICMS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS_ST,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_ST,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_ICMS_ST,
                                           (SELECT MAX(CDSITUTRIBITNFE)
                                              FROM ITEMPROIMPOS N, IMPOSTO IM
                                             WHERE IP.CDFILIAL     = N.CDFILIAL
                                               AND IP.NRLANCTONF   = N.NRLANCTONF
                                               AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                               AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                               AND N.NRITPROIMPOS  = '1'
                                               AND IM.CDIMPOSTONFE = V_IPI) AS CST_IPI,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_IPI,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_IPI,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_IPI,
                                           (SELECT MAX(CDSITUTRIBITNFE)
                                              FROM ITEMPROIMPOS N, IMPOSTO IM
                                             WHERE IP.CDFILIAL     = N.CDFILIAL
                                               AND IP.NRLANCTONF   = N.NRLANCTONF
                                               AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                               AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                               AND N.NRITPROIMPOS  = '1'
                                               AND IM.CDIMPOSTONFE = V_PIS) AS CST_PIS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_PIS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_PIS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_PIS,
                                           (SELECT MAX(CDSITUTRIBITNFE)
                                              FROM ITEMPROIMPOS N, IMPOSTO IM
                                             WHERE IP.CDFILIAL     = N.CDFILIAL
                                               AND IP.NRLANCTONF   = N.NRLANCTONF
                                               AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                               AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                               AND N.NRITPROIMPOS  = '1'
                                               AND IM.CDIMPOSTONFE = V_COFINS) AS CST_COFINS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_COFINS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_COFINS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_COFINS,
                                           CONTCTBL_SPED(C_REGC100.IDENTRSAIDOP, PR.CDPRODUTO, C_REGC100.CDTIPOOPER, C_REGC100.FILIAL)  AS COD_CTA,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.IDIMPDESONERAIT,'S',NVL(IP.VRIMPOSTOIT,0),0),2), '999999999990.00')), '.', ',') AS VL_ABAT_NT,
                                           PR.CDPRODUTO, IT.DSCDFISOPEIT, IT.CDPRODNCMTRANS AS CDCLASFISC
                                   FROM ITEMPRODUTO IT, PRODUTO PR, ITEMPROIMPOS IP, IMPOSTO IM
                                   WHERE IT.CDFILIAL      = C_REGC100.CDFILIAL
                                     AND IT.NRLANCTONF    = C_REGC100.NRLANCTONF
                                     AND IM.CDIMPOSTONFE  = P_CDIMPOSTO
                                     AND IM.CDIMPOSTO     = IP.CDIMPOSTO
                                     AND IT.CDFILIAL      = IP.CDFILIAL
                                     AND IT.NRLANCTONF    = IP.NRLANCTONF
                                     AND IT.NRSEQITPROD   = IP.NRSEQITPROD
                                     AND IT.CDPRODUTO     = PR.CDPRODUTO
                                     AND IP.NRITPROIMPOS  =  '1'
                                     AND C_REGC100.CDMODDOCFISC <> '55'
                                     AND ROUND(IT.QTITEMPROD,3) > 0
                                     AND VALOR_IMPOSTO_NFE(IP.CDFILIAL,IP.NRLANCTONF,'03','I','1') = 0
                                   UNION ALL
                                   /* NOTAS NÃO ELETRÓNICAS COM CARGA TRIBUTÁRIA */
                                   SELECT PR.CDARVPROD AS COD_ITEM,
                                           DECODE(C_REGC100.IDENTRSAIDOP, 'E', TRIM(RETIRA_CARACTER_ESPECIAL(IT.DSPRODEMIS, 'S'))) AS DESCR_COMPL,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(IT.QTITEMPROD,3), '999999999990.000')), '.', ',') AS QTD,
                                           PR.SGUNIDADE AS UNID,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(IT.VRTOTAITEM,2), '999999999990.00')), '.', ',')  AS VL_ITEM,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(NVL(IT.VRENCARGODESC,0),2), '999999999990.00')), '.', ',') AS VL_DESC,
                                           DECODE(NVL(V_IDATUESTTPOP,'N'),'N','1','0') AS IND_MOV,
                                           LPAD(NVL(IP.CDSITUTRIBIT,0),3,'0') AS CST_ICMS,
                                           IP.CDFISCOPERIT AS CFOP,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', IP.VRBASECALCIT, 0) + DECODE(V_IDTPCARGATRIB,'O',0,CASE WHEN V_SGESTADO <> 'SP' THEN VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'03','B','1') ELSE 0 END),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', IP.VRALIQITEM, 0),2), '999999999990.00')), '.', ',') AS ALIQ_ICMS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', IP.VRIMPOSTOIT,  0) + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(C_REGC100.IDENTRSAIDOP, 'S', VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'03','I','1'), CASE WHEN V_SGESTADO <> 'SP' THEN VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'03','I','1') ELSE 0 END)),2), '999999999990.00')), '.', ',') AS VL_ICMS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS_ST,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_ST,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_ICMS_ST,
                                           (SELECT MAX(CDSITUTRIBITNFE)
                                              FROM ITEMPROIMPOS N, IMPOSTO IM
                                             WHERE IP.CDFILIAL     = N.CDFILIAL
                                               AND IP.NRLANCTONF   = N.NRLANCTONF
                                               AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                               AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                               AND N.NRITPROIMPOS  = '1'
                                               AND IM.CDIMPOSTONFE = V_IPI) AS CST_IPI,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_IPI,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_IPI,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_IPI,
                                           (SELECT MAX(CDSITUTRIBITNFE)
                                              FROM ITEMPROIMPOS N, IMPOSTO IM
                                             WHERE IP.CDFILIAL     = N.CDFILIAL
                                               AND IP.NRLANCTONF   = N.NRLANCTONF
                                               AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                               AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                               AND N.NRITPROIMPOS  = '1'
                                               AND IM.CDIMPOSTONFE = V_PIS) AS CST_PIS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_PIS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_PIS, 
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_PIS,

                                           (SELECT MAX(CDSITUTRIBITNFE)
                                              FROM ITEMPROIMPOS N, IMPOSTO IM
                                             WHERE IP.CDFILIAL     = N.CDFILIAL
                                               AND IP.NRLANCTONF   = N.NRLANCTONF
                                               AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                               AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                               AND N.NRITPROIMPOS  = '1'
                                               AND IM.CDIMPOSTONFE = V_COFINS) AS CST_COFINS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_COFINS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_COFINS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_COFINS,
                                           CONTCTBL_SPED(C_REGC100.IDENTRSAIDOP, PR.CDPRODUTO, C_REGC100.CDTIPOOPER, C_REGC100.FILIAL)  AS COD_CTA,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.IDIMPDESONERAIT,'S',NVL(IP.VRIMPOSTOIT,0),0),2), '999999999990.00')), '.', ',') AS VL_ABAT_NT,
                                           PR.CDPRODUTO, IT.DSCDFISOPEIT, IT.CDPRODNCMTRANS AS CDCLASFISC
                                   FROM ITEMPRODUTO IT, PRODUTO PR, ITEMPROIMPOS IP, IMPOSTO IM
                                   WHERE IT.CDFILIAL      = C_REGC100.CDFILIAL
                                     AND IT.NRLANCTONF    = C_REGC100.NRLANCTONF
                                     AND IM.CDIMPOSTONFE  = P_CDIMPOSTO
                                     AND IM.CDIMPOSTO     = IP.CDIMPOSTO
                                     AND IT.CDFILIAL      = IP.CDFILIAL
                                     AND IT.NRLANCTONF    = IP.NRLANCTONF
                                     AND IT.NRSEQITPROD   = IP.NRSEQITPROD
                                     AND IT.CDPRODUTO     = PR.CDPRODUTO
                                     AND IP.NRITPROIMPOS  =  '1'
                                     AND C_REGC100.CDMODDOCFISC <> '55'
                                     AND ROUND(IT.QTITEMPROD,3) > 0
                                     AND VALOR_IMPOSTO_NFE(IP.CDFILIAL,IP.NRLANCTONF,'03','I','1') > 0
                                   UNION ALL
                                   /* NOTAS DE ENTRADA ELETRÓNICAS SEM CARGA TRIBUTÁRIA */
                                   SELECT PR.CDARVPROD AS COD_ITEM,
                                           DECODE(C_REGC100.IDENTRSAIDOP, 'E', TRIM(RETIRA_CARACTER_ESPECIAL(IT.DSPRODEMIS, 'S'))) AS DESCR_COMPL,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(IT.QTITEMPROD,3), '999999999990.000')), '.', ',') AS QTD,
                                           PR.SGUNIDADE AS UNID,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(IT.VRTOTAITEM,2), '999999999990.00')), '.', ',') AS VL_ITEM,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(NVL(IT.VRENCARGODESC,0),2), '999999999990.00')), '.', ',') AS VL_DESC,
                                           DECODE(NVL(V_IDATUESTTPOP,'N'),'N','1','0') AS IND_MOV,
                                           DECODE(C_REGC100.IDSIMPLESNACIONAL,'S',(DECODE(LENGTH(IT.CDFISCOPERSN),4,SUBSTR(IT.CDFISCOPERSN,2,3),LPAD(NVL(IT.CDFISCOPERSN,0),3,'0'))),LPAD(NVL(IP.CDSITUTRIBIT,0),3,'0')) AS CST_ICMS,
                                           IP.CDFISCOPERIT AS CFOP,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', IP.VRBASECALCIT, 0),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', IP.VRALIQITEM, 0),2), '999999999990.00')), '.', ',') AS ALIQ_ICMS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', IP.VRIMPOSTOIT, 0),2), '999999999990.00')), '.', ',') AS VL_ICMS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS_ST,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_ST,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_ICMS_ST,
                                           (SELECT MAX(CDSITUTRIBITNFE)
                                              FROM ITEMPROIMPOS N, IMPOSTO IM
                                             WHERE IP.CDFILIAL     = N.CDFILIAL
                                               AND IP.NRLANCTONF   = N.NRLANCTONF
                                               AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                               AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                               AND N.NRITPROIMPOS  = '1'
                                               AND IM.CDIMPOSTONFE = V_IPI) AS CST_IPI,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_IPI,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_IPI,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_IPI,
                                           (SELECT MAX(CDSITUTRIBITNFE)
                                              FROM ITEMPROIMPOS N, IMPOSTO IM
                                             WHERE IP.CDFILIAL     = N.CDFILIAL
                                               AND IP.NRLANCTONF   = N.NRLANCTONF
                                               AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                               AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                               AND N.NRITPROIMPOS  = '1'
                                               AND IM.CDIMPOSTONFE = V_PIS) AS CST_PIS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_PIS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_PIS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_PIS,
                                           (SELECT MAX(CDSITUTRIBITNFE)
                                              FROM ITEMPROIMPOS N, IMPOSTO IM
                                             WHERE IP.CDFILIAL     = N.CDFILIAL
                                               AND IP.NRLANCTONF   = N.NRLANCTONF
                                               AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                               AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                               AND N.NRITPROIMPOS  = '1'
                                               AND IM.CDIMPOSTONFE = V_COFINS) AS CST_COFINS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_COFINS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_COFINS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_COFINS,
                                           CONTCTBL_SPED(C_REGC100.IDENTRSAIDOP, PR.CDPRODUTO, C_REGC100.CDTIPOOPER, C_REGC100.FILIAL)  AS COD_CTA,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.IDIMPDESONERAIT,'S',NVL(IP.VRIMPOSTOIT,0),0),2), '999999999990.00')), '.', ',') AS VL_ABAT_NT,
                                           PR.CDPRODUTO, IT.DSCDFISOPEIT, IT.CDPRODNCMTRANS AS CDCLASFISC
                                    FROM ITEMPRODUTO IT, PRODUTO PR, ITEMPROIMPOS IP, IMPOSTO IM
                                   WHERE IT.CDFILIAL      = C_REGC100.CDFILIAL
                                     AND IT.NRLANCTONF    = C_REGC100.NRLANCTONF
                                     AND IM.CDIMPOSTONFE  = P_CDIMPOSTO
                                     AND IM.CDIMPOSTO     = IP.CDIMPOSTO
                                     AND IT.CDFILIAL      = IP.CDFILIAL
                                     AND IT.NRLANCTONF    = IP.NRLANCTONF
                                     AND IT.NRSEQITPROD   = IP.NRSEQITPROD
                                     AND IT.CDPRODUTO     = PR.CDPRODUTO
                                     AND IP.NRITPROIMPOS  =  '1'
                                     AND C_REGC100.IDENTRSAIDOP = 'E'
                                     AND C_REGC100.CDMODDOCFISC = '55'
                                     AND C_REGC100.IDSTATUSNFE <> 'A'
                                     AND ROUND(IT.QTITEMPROD,3) > 0
                                     AND VALOR_IMPOSTO_NFE(IP.CDFILIAL,IP.NRLANCTONF,'03','I','1') = 0
                                   UNION ALL
                                   /* NOTAS DE ENTRADA ELETRÓNICAS COM CARGA TRIBUTÁRIA */
                                   SELECT PR.CDARVPROD AS COD_ITEM,
                                           DECODE(C_REGC100.IDENTRSAIDOP, 'E', TRIM(RETIRA_CARACTER_ESPECIAL(IT.DSPRODEMIS,'S'))) AS DESCR_COMPL,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(IT.QTITEMPROD,3), '999999999990.000')), '.', ',') AS QTD,
                                           PR.SGUNIDADE AS UNID,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(IT.VRTOTAITEM,2), '999999999990.00')), '.', ',') AS VL_ITEM,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(NVL(IT.VRENCARGODESC,0),2), '999999999990.00')), '.', ',') AS VL_DESC,
                                           DECODE(NVL(V_IDATUESTTPOP,'N'),'N','1','0') AS IND_MOV,
                                           DECODE(C_REGC100.IDSIMPLESNACIONAL,'S',(DECODE(LENGTH(IT.CDFISCOPERSN),4,SUBSTR(IT.CDFISCOPERSN,2,3),LPAD(NVL(IT.CDFISCOPERSN,0),3,'0'))), LPAD(NVL(IP.CDSITUTRIBIT,0),3,'0')) AS CST_ICMS,
                                           IP.CDFISCOPERIT AS CFOP,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', IP.VRBASECALCIT, 0) + DECODE(V_IDTPCARGATRIB,'O',0,CASE WHEN V_SGESTADO <> 'SP' THEN VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'03','B','1') ELSE 0 END),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', IP.VRALIQITEM, 0),2), '999999999990.00')), '.', ',') AS ALIQ_ICMS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', IP.VRIMPOSTOIT,  0) + DECODE(V_IDTPCARGATRIB,'O',0,CASE WHEN V_SGESTADO <> 'SP' THEN VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'03','I','1') ELSE 0 END),2), '999999999990.00')), '.', ',') AS VL_ICMS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS_ST,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_ST,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_ICMS_ST,
                                           (SELECT MAX(CDSITUTRIBITNFE)
                                              FROM ITEMPROIMPOS N, IMPOSTO IM
                                             WHERE IP.CDFILIAL     = N.CDFILIAL
                                               AND IP.NRLANCTONF   = N.NRLANCTONF
                                               AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                               AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                               AND N.NRITPROIMPOS  = '1'
                                               AND IM.CDIMPOSTONFE = V_IPI) AS CST_IPI,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_IPI,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_IPI,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_IPI,
                                           (SELECT MAX(CDSITUTRIBITNFE)
                                              FROM ITEMPROIMPOS N, IMPOSTO IM
                                             WHERE IP.CDFILIAL     = N.CDFILIAL
                                               AND IP.NRLANCTONF   = N.NRLANCTONF
                                               AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                               AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                               AND N.NRITPROIMPOS  = '1'
                                               AND IM.CDIMPOSTONFE = V_PIS) AS CST_PIS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_PIS, 
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_PIS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_PIS,

                                           (SELECT MAX(CDSITUTRIBITNFE)
                                              FROM ITEMPROIMPOS N, IMPOSTO IM
                                             WHERE IP.CDFILIAL     = N.CDFILIAL
                                               AND IP.NRLANCTONF   = N.NRLANCTONF
                                               AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                               AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                               AND N.NRITPROIMPOS  = '1'
                                               AND IM.CDIMPOSTONFE = V_COFINS) AS CST_COFINS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_COFINS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_COFINS,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_COFINS,
                                           CONTCTBL_SPED(C_REGC100.IDENTRSAIDOP, PR.CDPRODUTO, C_REGC100.CDTIPOOPER, C_REGC100.FILIAL)  AS COD_CTA,
                                           REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.IDIMPDESONERAIT,'S',NVL(IP.VRIMPOSTOIT,0),0),2), '999999999990.00')), '.', ',') AS VL_ABAT_NT,
                                           PR.CDPRODUTO, IT.DSCDFISOPEIT, IT.CDPRODNCMTRANS AS CDCLASFISC
                                    FROM ITEMPRODUTO IT, PRODUTO PR, ITEMPROIMPOS IP, IMPOSTO IM
                                   WHERE IT.CDFILIAL      = C_REGC100.CDFILIAL
                                     AND IT.NRLANCTONF    = C_REGC100.NRLANCTONF
                                     AND IM.CDIMPOSTONFE  = P_CDIMPOSTO
                                     AND IM.CDIMPOSTO     = IP.CDIMPOSTO
                                     AND IT.CDFILIAL      = IP.CDFILIAL
                                     AND IT.NRLANCTONF    = IP.NRLANCTONF
                                     AND IT.NRSEQITPROD   = IP.NRSEQITPROD
                                     AND IT.CDPRODUTO     = PR.CDPRODUTO
                                     AND IP.NRITPROIMPOS  =  '1'
                                     AND C_REGC100.IDENTRSAIDOP = 'E'
                                     AND C_REGC100.CDMODDOCFISC = '55'
                                     AND C_REGC100.IDSTATUSNFE <> 'A'
                                     AND ROUND(IT.QTITEMPROD,3) > 0
                                     AND VALOR_IMPOSTO_NFE(IP.CDFILIAL,IP.NRLANCTONF,'03','I','1') > 0)) LOOP
            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), '|C170'|| '|' ||V_SEQUENCIAL|| '|' || C_REGC170.ARQ_C170, P_NRSEQARQMAG);
            V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER(RTRIM(V_SEQUENCIAL))+1)), 3,'0');
            V_CONTREGC :=  NVL(V_CONTREGC,0) + 1;

            /* CODIGO DO CFOP */
            SELECT MAX(CDCHAVEREG)
              INTO V_COD_NAT
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_REGC170.CDFISCOPERIT
               AND CDREGISTRO = '0400';

            IF (V_COD_NAT IS NULL) AND (C_REGC170.CDFISCOPERIT IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1, CDCAMPO2)
               VALUES
                 ('0400', V_SEQUPROD, C_REGC170.CDFISCOPERIT, C_REGC170.DSCDFISOPEIT, C_REGC100.IDENTRSAIDOP);
            END IF;
            V_COD_NAT := NULL;

            /* UNIDADE DE MEDIDA */
            SELECT MAX(CDCHAVEREG)
              INTO V_UNID
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_REGC170.UNID
               AND CDREGISTRO = '0190';

            IF (V_UNID IS NULL) AND (C_REGC170.UNID IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
               VALUES
                 ('0190', V_SEQUPROD, C_REGC170.UNID);
            END IF;
            V_UNID := NULL;

            /* CODIGO DO PRODUTO */
            SELECT MAX(CDCHAVEREG)
              INTO V_PRODUTO
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_REGC170.CDPRODUTO
               AND CDREGISTRO = '0200';

            IF (V_PRODUTO IS NULL) AND (C_REGC170.CDPRODUTO IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
               VALUES
                 ('0200', V_SEQUPROD, C_REGC170.CDPRODUTO, C_REGC170.CDCLASFISC);
            END IF;
            V_PRODUTO := NULL;

            /* PLANO DE CONTAS REFERENCIAL */
            SELECT MAX(CDCHAVEREG)
              INTO V_CONTCTBL
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_REGC170.COD_CTA
               AND CDREGISTRO = '0500';

            IF (V_CONTCTBL IS NULL) AND (C_REGC170.COD_CTA IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
               VALUES
                  ('0500', V_SEQUPROD, C_REGC170.COD_CTA);
            END IF;
            V_CONTCTBL := NULL;
          END LOOP;

          IF P_VERSAO NOT IN ( '001', '002') THEN
             /*REGISTRO C190*/
             IF (C_REGC100.IDSIMPLESNACIONAL <> 'S') OR (C_REGC100.IDSIMPLESNACIONAL = 'S' AND C_REGC100.CDMODDOCFISC <> '55') THEN
                 FOR C_REGC190 IN(SELECT ('|C190'      || '|' ||
                                          T.CST_ICMS   || '|' ||
                                          T.CFOP       || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.ALIQ_ICMS,2), '999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_OPR,2),    '999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_BC_ICMS,2),'999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_ICMS,2),   '999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.BC_ST,2),     '999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.IMP_ST,2),    '999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_RED_BC,2), '999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(VL_IPI,2),      '999999999990.00')), '.', ',') || '|' ||
                                          '' || '|') ARQ_C190,
                                          T.VL_ICMS, T.CFOP AS COD_NAT, T.CST_ICMS, T.ALIQ_ICMS
                                  FROM (/* NOTAS DE SAÍDA SEM CARGA TRIBUTÁRIA */
                                        SELECT I.CDSITUTRIBIT AS CST_ICMS,
                                               I.CDFISCOPERIT AS CFOP,
                                               DECODE(I.CDFISCALIT, '1', I.VRALIQITEM, 0) AS ALIQ_ICMS,
                                               SUM(I.VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL)),0) VL_OPR,
                                               SUM(DECODE(I.CDFISCALIT, '1', I.VRBASECALCIT, 0)) AS VL_BC_ICMS,
                                               SUM(DECODE(I.CDFISCALIT, '1', I.VRIMPOSTOIT, 0)) AS VL_ICMS,
                                               NVL(SUM(DECODE(I.CDFISCALIT,'1',VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL),0)),0) AS VL_RED_BC,
                                               SUM((SELECT NVL(SUM(VRIMPOSTOIT),0)
                                                      FROM ITEMPROIMPOS IT, IMPOSTO IM
                                                     WHERE (IT.CDFILIAL     = I.CDFILIAL           ) AND
                                                           (IT.NRLANCTONF   = I.NRLANCTONF         ) AND
                                                           (IT.CDIMPOSTO    = IM.CDIMPOSTO         ) AND
                                                           (IT.NRITPROIMPOS = '1'                  ) AND
                                                           (IT.CDFISCALIT   = '1'                  ) AND
                                                           (IM.CDIMPOSTONFE = '10'                 ) AND
                                                           I.NRSEQITPROD = IT.NRSEQITPROD         )) AS VL_IPI,
                                               '' AS COD_OBS,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','B','1')) AS BC_ST,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1') + VALOR_FECP_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1')) AS IMP_ST
                                          FROM ITEMPROIMPOS I, IMPOSTO IM
                                         WHERE I.CDFILIAL      = C_REGC100.CDFILIAL
                                           AND I.NRLANCTONF    = C_REGC100.NRLANCTONF
                                           AND C_REGC100.IDENTRSAIDOP = 'S'
                                           AND I.NRITPROIMPOS  = '1'
                                           AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                           AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                           AND VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1') = 0
                                         GROUP BY I.CDSITUTRIBIT, CDFISCOPERIT, DECODE(CDFISCALIT, '1', VRALIQITEM, 0)
                                        UNION ALL
                                        /* NOTAS DE SAÍDA COM CARGA TRIBUTÁRIA */
                                        SELECT I.CDSITUTRIBIT AS CST_ICMS,
                                               I.CDFISCOPERIT AS CFOP,
                                               DECODE(I.CDFISCALIT, '1', I.VRALIQITEM, 0) AS ALIQ_ICMS,
                                               SUM(I.VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL)),0) VL_OPR,
                                               DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'03','B','1')))) AS VL_BC_ICMS,
                                               SUM(DECODE(V_IDTPCARGATRIB,'O',0,VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'03','I','1'))) AS VL_ICMS,
                                               NVL(SUM(DECODE(I.CDFISCALIT,'1',VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL),0)),0) AS VL_RED_BC,
                                               SUM((SELECT NVL(SUM(VRIMPOSTOIT),0)
                                                      FROM ITEMPROIMPOS IT, IMPOSTO IM
                                                     WHERE (IT.CDFILIAL     = I.CDFILIAL           ) AND
                                                           (IT.NRLANCTONF   = I.NRLANCTONF         ) AND
                                                           (IT.CDIMPOSTO    = IM.CDIMPOSTO         ) AND
                                                           (IT.NRITPROIMPOS = '1'                  ) AND
                                                           (IT.CDFISCALIT   = '1'                  ) AND
                                                           (IM.CDIMPOSTONFE = '10'                 ) AND
                                                           I.NRSEQITPROD = IT.NRSEQITPROD         )) AS VL_IPI,
                                               '' AS COD_OBS,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','B','1')) AS BC_ST,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1') + VALOR_FECP_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1')) AS IMP_ST
                                          FROM ITEMPROIMPOS I, IMPOSTO IM
                                         WHERE I.CDFILIAL      = C_REGC100.CDFILIAL
                                           AND I.NRLANCTONF    = C_REGC100.NRLANCTONF
                                           AND C_REGC100.IDENTRSAIDOP = 'S'
                                           AND I.NRITPROIMPOS  = '1'
                                           AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                           AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                           AND VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1') > 0
                                         GROUP BY I.CDSITUTRIBIT, CDFISCOPERIT, DECODE(CDFISCALIT, '1', VRALIQITEM, 0)
                                        UNION ALL
                                        /* NOTAS DE ENTRADA SEM CARGA TRIBUTÁRIA */
                                        SELECT I.CDSITUTRIBIT AS CST_ICMS,
                                               I.CDFISCOPERIT AS CFOP,
                                               DECODE(I.CDFISCALIT, '1', I.VRALIQITEM, 0) AS ALIQ_ICMS,
                                               SUM(I.VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL)),0) VL_OPR,
                                               SUM(DECODE(CDFISCALIT, '1', VRBASECALCIT, 0)) AS VL_BC_ICMS,
                                               SUM(DECODE(CDFISCALIT, '1', VRIMPOSTOIT, 0)) AS VL_ICMS,
                                               NVL(SUM(DECODE(I.CDFISCALIT,'1',VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL),0)),0) AS VL_RED_BC,
                                               SUM((SELECT NVL(SUM(VRIMPOSTOIT),0)
                                                      FROM ITEMPROIMPOS IT, IMPOSTO IM
                                                     WHERE (IT.CDFILIAL     = I.CDFILIAL           ) AND
                                                           (IT.NRLANCTONF   = I.NRLANCTONF         ) AND
                                                           (IT.CDIMPOSTO    = IM.CDIMPOSTO         ) AND
                                                           (IT.NRITPROIMPOS = '1'                  ) AND
                                                           (IT.CDFISCALIT   = '1'                  ) AND
                                                           (IM.CDIMPOSTONFE = '10'                 ) AND
                                                           I.NRSEQITPROD = IT.NRSEQITPROD         )) AS VL_IPI,
                                               '' AS COD_OBS,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','B','1')) AS BC_ST,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1') + VALOR_FECP_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1')) AS IMP_ST
                                          FROM ITEMPROIMPOS I, IMPOSTO IM
                                         WHERE I.CDFILIAL      = C_REGC100.CDFILIAL
                                           AND I.NRLANCTONF    = C_REGC100.NRLANCTONF
                                           AND C_REGC100.IDENTRSAIDOP = 'E'
                                           AND I.NRITPROIMPOS  = '1'
                                           AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                           AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                           AND VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1') = 0
                                         GROUP BY I.CDSITUTRIBIT, CDFISCOPERIT, DECODE(CDFISCALIT, '1', VRALIQITEM, 0)
                                        UNION ALL
                                        /* NOTAS DE ENTRADA COM CARGA TRIBUTÁRIA */
                                        SELECT I.CDSITUTRIBIT AS CST_ICMS,
                                               I.CDFISCOPERIT AS CFOP,
                                               DECODE(I.CDFISCALIT, '1', I.VRALIQITEM, 0) AS ALIQ_ICMS,
                                               SUM(I.VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL)),0) VL_OPR,
                                               SUM(DECODE(CDFISCALIT,'1',VRBASECALCIT, 0) + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(CDFISCALIT, '1', CASE WHEN V_SGESTADO <> 'SP' THEN VRBASECALCIT ELSE 0 END, 0))) AS VL_BC_ICMS,
                                               SUM(DECODE(CDFISCALIT,'1',VRIMPOSTOIT,  0) + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(CDFISCALIT, '1', CASE WHEN V_SGESTADO <> 'SP' THEN VRIMPOSTOIT  ELSE 0 END, 0))) AS VL_ICMS,
                                               NVL(SUM(DECODE(I.CDFISCALIT,'1',VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL),0)),0) AS VL_RED_BC,
                                               SUM((SELECT NVL(SUM(VRIMPOSTOIT),0)
                                                      FROM ITEMPROIMPOS IT, IMPOSTO IM
                                                     WHERE (IT.CDFILIAL     = I.CDFILIAL           ) AND
                                                           (IT.NRLANCTONF   = I.NRLANCTONF         ) AND
                                                           (IT.CDIMPOSTO    = IM.CDIMPOSTO         ) AND
                                                           (IT.NRITPROIMPOS = '1'                  ) AND
                                                           (IT.CDFISCALIT   = '1'                  ) AND
                                                           (IM.CDIMPOSTONFE = '10'                 ) AND
                                                           I.NRSEQITPROD = IT.NRSEQITPROD         )) AS VL_IPI,
                                               '' AS COD_OBS,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','B','1')) AS BC_ST,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1') + VALOR_FECP_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1')) AS IMP_ST
                                          FROM ITEMPROIMPOS I, IMPOSTO IM
                                         WHERE I.CDFILIAL      = C_REGC100.CDFILIAL
                                           AND I.NRLANCTONF    = C_REGC100.NRLANCTONF
                                           AND C_REGC100.IDENTRSAIDOP = 'E'
                                           AND I.NRITPROIMPOS  = '1'
                                           AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                           AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                           AND VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1') > 0
                                         GROUP BY I.CDSITUTRIBIT, CDFISCOPERIT, DECODE(CDFISCALIT, '1', VRALIQITEM, 0) ) T ) LOOP
                    INSERT INTO ARQMAGNETICO
                      (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                    VALUES
                      ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC190.ARQ_C190, P_NRSEQARQMAG);
                    V_CONTREGC := NVL(V_CONTREGC,0) + 1;

                    IF P_VERSAO >= '013' THEN
                       FOR C_REGC191 IN (SELECT '|C191'          || '|' ||
                                                REPLACE(LTRIM(TO_CHAR(SUM(CASE WHEN SUBSTR(IT.CDSITUTRIBIT,2,2) IN ('00','10','20','51','70','90') AND IM.CDIMPOSTONFE = '00'
                                                     THEN ROUND(IT.VRADICFECP,2)
                                                     ELSE 0 END),'999999999990.00')), '.', ',') || '|' ||
                                                REPLACE(LTRIM(TO_CHAR(SUM(CASE WHEN SUBSTR(IT.CDSITUTRIBIT,2,2) IN ('10','30','70','90') AND IM.CDIMPOSTONFE = '80'
                                                     THEN ROUND(IT.VRADICFECP,2)
                                                     ELSE 0 END),'999999999990.00')), '.', ',') || '|' ||
                                                REPLACE(LTRIM(TO_CHAR(SUM(CASE WHEN SUBSTR(IT.CDSITUTRIBIT,2,2) IN ('60')
                                                     THEN ROUND(IT.VRADICFECP,2)
                                                     ELSE 0 END),'999999999990.00')), '.', ',') || '|' AS ARQ_C191, IT.CDFISCOPERIT
                                           FROM ITEMPROIMPOS IT, ITEMPROIMPOS II, IMPOSTO IM
                                          WHERE IT.CDFILIAL     = C_REGC100.CDFILIAL
                                            AND IT.NRLANCTONF   = C_REGC100.NRLANCTONF
                                            AND IT.CDFISCOPERIT = C_REGC190.COD_NAT
                                            AND IT.CDSITUTRIBIT = C_REGC190.CST_ICMS
                                            AND IT.VRALIQITEM   = C_REGC190.ALIQ_ICMS
                                            AND IT.NRITPROIMPOS = '1'
                                            AND IT.CDFILIAL     = II.CDFILIAL
                                            AND IT.NRLANCTONF   = II.NRLANCTONF
                                            AND IT.NRSEQITPROD  = II.NRSEQITPROD
                                            AND II.CDFISCOPERIT = C_REGC190.COD_NAT
                                            AND II.CDSITUTRIBIT = C_REGC190.CST_ICMS
                                            AND II.CDIMPOSTO    = IM.CDIMPOSTO
                                            AND IM.CDIMPOSTONFE IN ('00','80')
                                            AND II.VRADICFECP   > 0
                                          GROUP BY IT.CDFISCOPERIT) LOOP
                          INSERT INTO ARQMAGNETICO
                             (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                          VALUES
                             ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC191.ARQ_C191, P_NRSEQARQMAG);
                          V_CONTREGC := NVL(V_CONTREGC,0) + 1;
                       END LOOP;
                    END IF;
                 END LOOP;
             END IF;

             IF (C_REGC100.IDSIMPLESNACIONAL = 'S' AND C_REGC100.CDMODDOCFISC = '55') THEN
                 FOR C_REGC190 IN(SELECT ('|C190'      || '|' ||
                                          T.CST_ICMS   || '|' ||
                                          T.CFOP       || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.ALIQ_ICMS,2), '999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_OPR,2),    '999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_BC_ICMS,2),'999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_ICMS,2),   '999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.BC_ST,2),     '999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.IMP_ST,2),    '999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_RED_BC,2), '999999999990.00')), '.', ',') || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(ROUND(VL_IPI,2),      '999999999990.00')), '.', ',') || '|' ||
                                          '' || '|') ARQ_C190,
                                          T.VL_ICMS, T.CFOP AS COD_NAT, T.CST_ICMS, T.ALIQ_ICMS
                                  FROM (/* NOTAS DE SAÍDA SEM CARGA TRIBUTÁRIA */
                                        SELECT DECODE(LENGTH(IT.CDFISCOPERSN),4,SUBSTR(IT.CDFISCOPERSN,2,3),IT.CDFISCOPERSN) AS CST_ICMS,
                                               I.CDFISCOPERIT AS CFOP,
                                               DECODE(I.CDFISCALIT, '1', I.VRALIQITEM, 0) AS ALIQ_ICMS,
                                               SUM(I.VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, IT.CDFISCOPERSN, C_REGC100.CDMODDOCFISC, C_REGC100.IDSIMPLESNACIONAL)),0) VL_OPR,
                                               SUM(DECODE(I.CDFISCALIT, '1', I.VRBASECALCIT, 0)) AS VL_BC_ICMS,
                                               SUM(DECODE(I.CDFISCALIT, '1', I.VRIMPOSTOIT, 0)) AS VL_ICMS,
                                               NVL(SUM(DECODE(I.CDFISCALIT,'1',VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, IT.CDFISCOPERSN, C_REGC100.CDMODDOCFISC, C_REGC100.IDSIMPLESNACIONAL),0)),0) AS VL_RED_BC,
                                               SUM((SELECT NVL(SUM(VRIMPOSTOIT),0)
                                                      FROM ITEMPROIMPOS IT, IMPOSTO IM
                                                     WHERE (IT.CDFILIAL     = I.CDFILIAL           ) AND
                                                           (IT.NRLANCTONF   = I.NRLANCTONF         ) AND
                                                           (IT.CDIMPOSTO    = IM.CDIMPOSTO         ) AND
                                                           (IT.NRITPROIMPOS = '1'                  ) AND
                                                           (IT.CDFISCALIT   = '1'                  ) AND
                                                           (IM.CDIMPOSTONFE = '10'                 ) AND
                                                           I.NRSEQITPROD = IT.NRSEQITPROD         )) AS VL_IPI,
                                               '' AS COD_OBS,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','B','1')) AS BC_ST,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1') + VALOR_FECP_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1')) AS IMP_ST
                                          FROM ITEMPROIMPOS I, IMPOSTO IM, ITEMPRODUTO IT
                                         WHERE I.CDFILIAL      = C_REGC100.CDFILIAL
                                           AND I.NRLANCTONF    = C_REGC100.NRLANCTONF
                                           AND C_REGC100.IDENTRSAIDOP = 'S'
                                           AND I.NRITPROIMPOS  = '1'
                                           AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                           AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                           AND I.CDFILIAL      = IT.CDFILIAL
                                           AND I.NRLANCTONF    = IT.NRLANCTONF
                                           AND I.NRSEQITPROD   = IT.NRSEQITPROD
                                           AND VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1') = 0
                                         GROUP BY DECODE(LENGTH(IT.CDFISCOPERSN),4,SUBSTR(IT.CDFISCOPERSN,2,3),IT.CDFISCOPERSN), CDFISCOPERIT, DECODE(CDFISCALIT, '1', VRALIQITEM, 0)
                                        UNION ALL
                                        /* NOTAS DE SAÍDA COM CARGA TRIBUTÁRIA */
                                        SELECT DECODE(LENGTH(IT.CDFISCOPERSN),4,SUBSTR(IT.CDFISCOPERSN,2,3),IT.CDFISCOPERSN) AS CST_ICMS,
                                               I.CDFISCOPERIT AS CFOP,
                                               DECODE(I.CDFISCALIT, '1', I.VRALIQITEM, 0) AS ALIQ_ICMS,
                                               SUM(I.VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, IT.CDFISCOPERSN, C_REGC100.CDMODDOCFISC, C_REGC100.IDSIMPLESNACIONAL)),0) VL_OPR,
                                               DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'03','B','1')))) AS VL_BC_ICMS,
                                               SUM(DECODE(V_IDTPCARGATRIB,'O',0,VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'03','I','1'))) AS VL_ICMS,
                                               NVL(SUM(DECODE(I.CDFISCALIT,'1',VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, IT.CDFISCOPERSN, C_REGC100.CDMODDOCFISC, C_REGC100.IDSIMPLESNACIONAL),0)),0) AS VL_RED_BC,
                                               SUM((SELECT NVL(SUM(VRIMPOSTOIT),0)
                                                      FROM ITEMPROIMPOS IT, IMPOSTO IM
                                                     WHERE (IT.CDFILIAL     = I.CDFILIAL           ) AND
                                                           (IT.NRLANCTONF   = I.NRLANCTONF         ) AND
                                                           (IT.CDIMPOSTO    = IM.CDIMPOSTO         ) AND
                                                           (IT.NRITPROIMPOS = '1'                  ) AND
                                                           (IT.CDFISCALIT   = '1'                  ) AND
                                                           (IM.CDIMPOSTONFE = '10'                 ) AND
                                                           I.NRSEQITPROD = IT.NRSEQITPROD         )) AS VL_IPI,
                                               '' AS COD_OBS,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','B','1')) AS BC_ST,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1') + VALOR_FECP_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1')) AS IMP_ST
                                          FROM ITEMPROIMPOS I, IMPOSTO IM, ITEMPRODUTO IT
                                         WHERE I.CDFILIAL      = C_REGC100.CDFILIAL
                                           AND I.NRLANCTONF    = C_REGC100.NRLANCTONF
                                           AND C_REGC100.IDENTRSAIDOP = 'S'
                                           AND I.NRITPROIMPOS  = '1'
                                           AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                           AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                           AND I.CDFILIAL      = IT.CDFILIAL
                                           AND I.NRLANCTONF    = IT.NRLANCTONF
                                           AND I.NRSEQITPROD   = IT.NRSEQITPROD
                                           AND VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1') > 0
                                         GROUP BY DECODE(LENGTH(IT.CDFISCOPERSN),4,SUBSTR(IT.CDFISCOPERSN,2,3),IT.CDFISCOPERSN), CDFISCOPERIT, DECODE(CDFISCALIT, '1', VRALIQITEM, 0)
                                        UNION ALL
                                        /* NOTAS DE ENTRADA SEM CARGA TRIBUTÁRIA */
                                        SELECT DECODE(LENGTH(IT.CDFISCOPERSN),4,SUBSTR(IT.CDFISCOPERSN,2,3),IT.CDFISCOPERSN) AS CST_ICMS,
                                               I.CDFISCOPERIT AS CFOP,
                                               DECODE(I.CDFISCALIT, '1', I.VRALIQITEM, 0) AS ALIQ_ICMS,
                                               SUM(I.VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, IT.CDFISCOPERSN, C_REGC100.CDMODDOCFISC, C_REGC100.IDSIMPLESNACIONAL)),0) VL_OPR,
                                               SUM(DECODE(I.CDFISCALIT, '1', I.VRBASECALCIT, 0)) AS VL_BC_ICMS,
                                               SUM(DECODE(I.CDFISCALIT, '1', I.VRIMPOSTOIT, 0)) AS VL_ICMS,
                                               NVL(SUM(DECODE(I.CDFISCALIT,'1',VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, IT.CDFISCOPERSN, C_REGC100.CDMODDOCFISC, C_REGC100.IDSIMPLESNACIONAL),0)),0) AS VL_RED_BC,
                                               SUM((SELECT NVL(SUM(VRIMPOSTOIT),0)
                                                      FROM ITEMPROIMPOS IT, IMPOSTO IM
                                                     WHERE (IT.CDFILIAL     = I.CDFILIAL           ) AND
                                                           (IT.NRLANCTONF   = I.NRLANCTONF         ) AND
                                                           (IT.CDIMPOSTO    = IM.CDIMPOSTO         ) AND
                                                           (IT.NRITPROIMPOS = '1'                  ) AND
                                                           (IT.CDFISCALIT   = '1'                  ) AND
                                                           (IM.CDIMPOSTONFE = '10'                 ) AND
                                                           I.NRSEQITPROD = IT.NRSEQITPROD         )) AS VL_IPI,
                                               '' AS COD_OBS,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','B','1')) AS BC_ST,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1') + VALOR_FECP_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1')) AS IMP_ST
                                          FROM ITEMPROIMPOS I, IMPOSTO IM, ITEMPRODUTO IT
                                         WHERE I.CDFILIAL      = C_REGC100.CDFILIAL
                                           AND I.NRLANCTONF    = C_REGC100.NRLANCTONF
                                           AND C_REGC100.IDENTRSAIDOP = 'E'
                                           AND I.NRITPROIMPOS  = '1'
                                           AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                           AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                           AND I.CDFILIAL      = IT.CDFILIAL
                                           AND I.NRLANCTONF    = IT.NRLANCTONF
                                           AND I.NRSEQITPROD   = IT.NRSEQITPROD
                                           AND VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1') = 0
                                         GROUP BY DECODE(LENGTH(IT.CDFISCOPERSN),4,SUBSTR(IT.CDFISCOPERSN,2,3),IT.CDFISCOPERSN), CDFISCOPERIT, DECODE(CDFISCALIT, '1', VRALIQITEM, 0)
                                        UNION ALL
                                        /* NOTAS DE ENTRADA COM CARGA TRIBUTÁRIA */
                                        SELECT DECODE(LENGTH(IT.CDFISCOPERSN),4,SUBSTR(IT.CDFISCOPERSN,2,3),IT.CDFISCOPERSN) AS CST_ICMS,
                                               I.CDFISCOPERIT AS CFOP,
                                               DECODE(I.CDFISCALIT, '1', I.VRALIQITEM, 0) AS ALIQ_ICMS,
                                               SUM(I.VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, IT.CDFISCOPERSN, C_REGC100.CDMODDOCFISC, C_REGC100.IDSIMPLESNACIONAL)),0) VL_OPR,
                                               SUM(DECODE(CDFISCALIT,'1',VRBASECALCIT, 0) + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(CDFISCALIT,'1',CASE WHEN V_SGESTADO <> 'SP' THEN VRBASECALCIT ELSE 0 END, 0))) AS VL_BC_ICMS,
                                               SUM(DECODE(CDFISCALIT,'1',VRIMPOSTOIT,  0) + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(CDFISCALIT,'1',CASE WHEN V_SGESTADO <> 'SP' THEN VRIMPOSTOIT  ELSE 0 END, 0))) AS VL_ICMS,
                                               NVL(SUM(DECODE(I.CDFISCALIT,'1',VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, IT.CDFISCOPERSN, C_REGC100.CDMODDOCFISC, C_REGC100.IDSIMPLESNACIONAL),0)),0) AS VL_RED_BC,
                                               SUM((SELECT NVL(SUM(VRIMPOSTOIT),0)
                                                      FROM ITEMPROIMPOS IT, IMPOSTO IM
                                                     WHERE (IT.CDFILIAL     = I.CDFILIAL           ) AND
                                                           (IT.NRLANCTONF   = I.NRLANCTONF         ) AND
                                                           (IT.CDIMPOSTO    = IM.CDIMPOSTO         ) AND
                                                           (IT.NRITPROIMPOS = '1'                  ) AND
                                                           (IT.CDFISCALIT   = '1'                  ) AND
                                                           (IM.CDIMPOSTONFE = '10'                 ) AND
                                                           I.NRSEQITPROD = IT.NRSEQITPROD         )) AS VL_IPI,
                                               '' AS COD_OBS,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','B','1')) AS BC_ST,
                                               SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1') + VALOR_FECP_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1')) AS IMP_ST
                                          FROM ITEMPROIMPOS I, IMPOSTO IM, ITEMPRODUTO IT
                                         WHERE I.CDFILIAL      = C_REGC100.CDFILIAL
                                           AND I.NRLANCTONF    = C_REGC100.NRLANCTONF
                                           AND C_REGC100.IDENTRSAIDOP = 'E'
                                           AND I.NRITPROIMPOS  = '1'
                                           AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                           AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                           AND I.CDFILIAL      = IT.CDFILIAL
                                           AND I.NRLANCTONF    = IT.NRLANCTONF
                                           AND I.NRSEQITPROD   = IT.NRSEQITPROD
                                           AND VALOR_IMPOSTO_NFE(I.CDFILIAL,I.NRLANCTONF,'03','I','1') > 0
                                         GROUP BY DECODE(LENGTH(IT.CDFISCOPERSN),4,SUBSTR(IT.CDFISCOPERSN,2,3),IT.CDFISCOPERSN), CDFISCOPERIT, DECODE(CDFISCALIT, '1', VRALIQITEM, 0) ) T ) LOOP
                    INSERT INTO ARQMAGNETICO
                      (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                    VALUES
                      ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC190.ARQ_C190, P_NRSEQARQMAG);
                    V_CONTREGC := NVL(V_CONTREGC,0) + 1;

                    IF P_VERSAO >= '013' THEN
                       FOR C_REGC191 IN (SELECT '|C191'          || '|' ||
                                                REPLACE(LTRIM(TO_CHAR(SUM(CASE WHEN DECODE(LENGTH(IP.CDFISCOPERSN),4,SUBSTR(IP.CDFISCOPERSN,2,3),IP.CDFISCOPERSN) <> '500' AND IM.CDIMPOSTONFE = '00'
                                                     THEN ROUND(IT.VRADICFECP,2)
                                                     ELSE 0 END),'999999999990.00')), '.', ',') || '|' ||
                                                REPLACE(LTRIM(TO_CHAR(SUM(CASE WHEN DECODE(LENGTH(IP.CDFISCOPERSN),4,SUBSTR(IP.CDFISCOPERSN,2,3),IP.CDFISCOPERSN) IN ('201','202','203','900') AND IM.CDIMPOSTONFE = '80'
                                                     THEN ROUND(IT.VRADICFECP,2)
                                                     ELSE 0 END),'999999999990.00')), '.', ',') || '|' ||
                                                REPLACE(LTRIM(TO_CHAR(SUM(CASE WHEN DECODE(LENGTH(IP.CDFISCOPERSN),4,SUBSTR(IP.CDFISCOPERSN,2,3),IP.CDFISCOPERSN) = '500'
                                                     THEN ROUND(IT.VRADICFECP,2)
                                                     ELSE 0 END),'999999999990.00')), '.', ',') || '|' AS ARQ_C191, IT.CDFISCOPERIT
                                           FROM ITEMPROIMPOS IT, ITEMPROIMPOS II, IMPOSTO IM, ITEMPRODUTO IP
                                          WHERE IT.CDFILIAL     = C_REGC100.CDFILIAL
                                            AND IT.NRLANCTONF   = C_REGC100.NRLANCTONF
                                            AND IT.CDFISCOPERIT = C_REGC190.COD_NAT
                                            AND IT.VRALIQITEM   = C_REGC190.ALIQ_ICMS
                                            AND IT.NRITPROIMPOS = '1'
                                            AND IT.CDFILIAL     = II.CDFILIAL
                                            AND IT.NRLANCTONF   = II.NRLANCTONF
                                            AND IT.NRSEQITPROD  = II.NRSEQITPROD
                                            AND II.CDFISCOPERIT = C_REGC190.COD_NAT
                                            AND II.CDIMPOSTO    = IM.CDIMPOSTO
                                            AND IM.CDIMPOSTONFE IN ('00','80')
                                            AND II.VRADICFECP   > 0
                                            AND II.CDFILIAL     = IP.CDFILIAL
                                            AND II.NRLANCTONF   = IP.NRLANCTONF
                                            AND II.NRSEQITPROD  = IP.NRSEQITPROD
                                            AND DECODE(LENGTH(IP.CDFISCOPERSN),4,SUBSTR(IP.CDFISCOPERSN,2,3),IP.CDFISCOPERSN) = C_REGC190.CST_ICMS
                                          GROUP BY IT.CDFISCOPERIT) LOOP
                          INSERT INTO ARQMAGNETICO
                             (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                          VALUES
                             ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC191.ARQ_C191, P_NRSEQARQMAG);
                          V_CONTREGC := NVL(V_CONTREGC,0) + 1;
                       END LOOP;
                    END IF;
                 END LOOP;
             END IF;
          END IF;
          /* geracao dos registros com diferencial  de aliquota */
          IF P_IDDIFALIQ = 'S' THEN
             SELECT MAX(SGESTADO)
               INTO V_SGESTADO
               FROM INSCRESTAD
              WHERE CDEMPRESA = P_CDEMPRESA
                AND CDINSCESTA = P_CDINSCESTA;

             IF C_REGC100.IDENTRSAIDOP = 'E' THEN

                /*BUSCA O CÓDIGO DE AJUSTE CADASTRADO PARA ESTA IE*/
                BEGIN
                   SELECT CDAJUSTEC195, IDGERREGC197, IDDIFEALIQUOTA
                     INTO V_CDAJUSTEC195,V_IDGERREGC197, V_IDDIFEALIQUOTA
                     FROM PARAMESTSPED
                    WHERE CDEMPRESA  = P_CDEMPRESA
                      AND CDINSCESTA = P_CDINSCESTA;
                EXCEPTION
                   WHEN NO_DATA_FOUND THEN
                      V_CDAJUSTEC195:= NULL;
                      V_IDGERREGC197:= NULL;
                END;

                /* REGISTRO C195 */
                FOR C_REGC195 IN (SELECT REPLACE(LTRIM(TO_CHAR(ROUND(SUM(VRBASECALCIT),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND((SUM(VRIMPOSTOIT)/SUM(VRBASECALCIT))*100,2), '999999999990.00')), '.', ',') AS ALIQ_ICMS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(SUM(VRIMPOSTOIT),2), '999999999990.00')), '.', ',') AS VL_ICMS,
                                         0 AS VL_OUTROS,
                                         'Diferencial de Alíquota' AS DESCR_COMPL_AJ,
                                         V_CDAJUSTEC195 AS COD_AJ
                                    FROM ITEMPROIMPOS I, IMPOSTO IM
                                   WHERE NRITPROIMPOS    = '3'
                                     AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                     AND I.CDIMPOSTO     = IM.CDIMPOSTO
                                     AND I.NRLANCTONF    = C_REGC100.NRLANCTONF
                                     AND I.CDFILIAL      = C_REGC100.CDFILIAL
                                     AND V_CDAJUSTEC195  IS NOT NULL
                                     AND V_IDGERREGC197  = 'S'
                                     AND NVL(V_IDDIFEALIQUOTA,'DA') <> 'OD'
                                    GROUP BY V_CDAJUSTEC195,'Diferencial de Alíquota')LOOP
                   INSERT INTO ARQMAGNETICO
                     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                   VALUES
                     ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), '|C195'  || '|' || '000001' || '|' || ''  || '|', P_NRSEQARQMAG);
                   V_CONTREGC := NVL(V_CONTREGC,0) + 1;

                   IF NVL(V_IDGERREGC197,'N') = 'S' THEN
                      V_REG_C197 := '|C197'                   || '|' ||
                                    C_REGC195.COD_AJ          || '|' ||
                                    C_REGC195.DESCR_COMPL_AJ  || '|' ||
                                    ''                        || '|' ||
                                    C_REGC195.VL_BC_ICMS      || '|' ||
                                    C_REGC195.ALIQ_ICMS       || '|' ||
                                    C_REGC195.VL_ICMS         || '|' ||
                                    C_REGC195.VL_OUTROS       || '|' ;
                      INSERT INTO ARQMAGNETICO
                        (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                      VALUES
                        ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), V_REG_C197, P_NRSEQARQMAG);
                      V_CONTREGC := NVL(V_CONTREGC,0) + 1;
                   END IF;
                   SELECT MAX(CDCHAVEREG)
                     INTO V_COD_OBS
                     FROM TMP_REGDADOSSPED
                    WHERE CDCHAVEREG = '000001'
                      AND CDREGISTRO = '0460';

                   IF (V_COD_OBS IS NULL) THEN

                      V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                      INSERT INTO TMP_REGDADOSSPED
                        (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
                      VALUES
                        ('0460', V_SEQUPROD, '000001', 'Diferencial de Alíquota');
                   END IF;

                END LOOP;
             END IF;
          END IF;
       END LOOP;
   END IF;


   IF V_CDSITUCRT = '3' AND P_PERFIL = 'B' THEN
      FOR C_REGC300 IN (SELECT ('|C300'    || '|' ||
                               COD_MOD     || '|' ||
                               SERIE       || '|' ||
                               ''          || '|' ||
                               NUM_DOC     || '|' ||
                               NUM_DOC     || '|' ||
                               DT_DOC      || '|' ||
                               VL_DOC      || '|' ||
                               VL_PIS      || '|' ||
                               VL_COFINS   || '|' ||
                               COD_CTA     || '|' ) AS ARQ_C300, NRLANCTONF, CDFILIAL, COD_CTA
                          FROM (SELECT N.CDMODDOCFISC  AS COD_MOD,
                                       NVL(SS.CDSERIENFE,N.CDSERIE) AS SERIE,
                                       SUBSTR(LPAD(NRNOTAFISC,10,'0'),5,6) AS NUM_DOC,
                                       TO_CHAR(N.DTEMISSAO,'ddmmyyyy') AS DT_DOC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(N.VRNOTAFISC,2), '999999999990.00')), '.', ',') AS VL_DOC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '50', 'I','1'),2), '999999999990.00')), '.', ',') AS VL_PIS,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '60', 'I','1'),2), '999999999990.00')), '.', ',') AS VL_COFINS,
                                       MAX((SELECT MAX(CONTCTBL_SPED(N.IDENTRSAIDOP,I.CDPRODUTO,N.CDTIPOOPER,N.CDFILIEMIT))
                                              FROM ITEMPRODUTO I
                                             WHERE I.CDFILIAL   = N.CDFILIAL
                                               AND I.NRLANCTONF = N.NRLANCTONF)) AS COD_CTA,
                                       I.NRLANCTONF, I.CDFILIAL
                                  FROM IMPOSTONF I, NOTAFISCAL N, IMPOSTO IM, SERIENF SS
                                 WHERE IM.CDIMPOSTONFE   = P_CDIMPOSTO
                                   AND I.NRSEQUMAPAPU    = V_NRSEQUMAPAPU
                                   AND IM.CDIMPOSTO      = I.CDIMPOSTO
                                   AND N.CDMODDOCFISC    = '02'
                                   AND NVL(I.IDIMPOSTONF, '1') <> '3'
                                   AND I.CDFILIAL        = N.CDFILIAL
                                   AND I.NRLANCTONF      = N.NRLANCTONF
                                   AND N.IDENTRSAIDOP    = 'S'
                                   AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                   AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                   AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                   AND SS.CDSERIE(+)     = N.CDSERIE
                                   AND NVL(P_GERAFORSALE,'N')  = 'N'
                                   AND (NVL(N.IDSISTEMA,'DFS') <> 'REC'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS')
                                 GROUP BY N.CDMODDOCFISC,  NVL(SS.CDSERIENFE,N.CDSERIE), SUBSTR(LPAD(NRNOTAFISC,10,'0'),5,6), N.DTEMISSAO,N.VRNOTAFISC,
                                       VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '50', 'I','1'),
                                       VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '60', 'I','1'),
                                       I.NRLANCTONF, I.CDFILIAL)) LOOP
         INSERT INTO ARQMAGNETICO
           (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
           ('20'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC300.ARQ_C300, P_NRSEQARQMAG);
         V_CONTREGC := NVL(V_CONTREGC,0) + 1;

         /* PLANO DE CONTAS REFERENCIAL */
         SELECT MAX(CDCHAVEREG)
           INTO V_CONTCTBL
           FROM TMP_REGDADOSSPED
          WHERE CDCHAVEREG = C_REGC300.COD_CTA
            AND CDREGISTRO = '0500';

         IF (V_CONTCTBL IS NULL) AND (C_REGC300.COD_CTA IS NOT NULL) THEN
            V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
            INSERT INTO TMP_REGDADOSSPED
               (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
            VALUES
               ('0500', V_SEQUPROD, C_REGC300.COD_CTA);
         END IF;
         V_CONTCTBL := NULL;

         FOR C_REGC310 IN (SELECT ('|C310'       || '|' ||
                                  LTRIM(N.NRNOTAFISC, '0')  || '|'  ) AS ARQ_C310
                             FROM NOTAFISCAL N
                            WHERE N.CDFILIAL = C_REGC300.CDFILIAL
                              AND N.NRLANCTONF = C_REGC300.NRLANCTONF
                              AND N.IDENTRSAIDOP = 'S'
                              AND N.IDSTATUS = 'C') LOOP
            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('20'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC310.ARQ_C310, P_NRSEQARQMAG);
            V_CONTREGC := NVL(V_CONTREGC,0) + 1;
         END LOOP;

         FOR C_REGC320 IN(SELECT ('|C320'         || '|' ||
                                   CDSITUTRIBIT    || '|' ||
                                   CDFISCOPERIT    || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(ROUND(VRALIQITEM,2), '999999999990.00')), '.', ',')    || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(ABS(ROUND(SUM(VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(CDFILIAL, NRLANCTONF, CDSITUTRIBIT, NRSEQITPROD, CDFISCOPERIT, NULL, NULL, NULL)),0),2)), '999999999990.00')), '.', ',')    || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(ROUND(SUM(DECODE(CDFISCALIT,'1',VRBASECALCIT,0) + DECODE(V_IDTPCARGATRIB,'O',0,VALOR_IMPOSTO_ITEM_NFE(IT.CDFILIAL,IT.NRLANCTONF,IT.NRSEQITPROD,'03','B','1'))),2), '999999999990.00')), '.', ',')    || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(ROUND(SUM(DECODE(CDFISCALIT,'1',VRIMPOSTOIT, 0) + DECODE(V_IDTPCARGATRIB,'O',0,VALOR_IMPOSTO_ITEM_NFE(IT.CDFILIAL,IT.NRLANCTONF,IT.NRSEQITPROD,'03','I','1'))),2), '999999999990.00')), '.', ',')    || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(ABS(ROUND(NVL(SUM(VALOR_REDUCAO(CDFILIAL, NRLANCTONF, CDSITUTRIBIT, NRSEQITPROD, CDFISCOPERIT, NULL, NULL, NULL) ),0),2)), '999999999990.00')), '.', ',')    || '|' ||
                                   ''  || '|'  ) AS ARQ_C320, CDFILIAL, NRLANCTONF, CDSITUTRIBIT, CDFISCOPERIT, VRALIQITEM
                             FROM ITEMPROIMPOS IT, IMPOSTO IM
                            WHERE IT.CDFILIAL     = C_REGC300.CDFILIAL
                              AND IT.NRLANCTONF   = C_REGC300.NRLANCTONF
                              AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                              AND IM.CDIMPOSTO    = IT.CDIMPOSTO
                              AND IT.NRITPROIMPOS = '1'
                            GROUP BY CDSITUTRIBIT, CDFISCOPERIT, VRALIQITEM,
                                  CDFILIAL, NRLANCTONF) LOOP
             INSERT INTO ARQMAGNETICO 
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
             VALUES 
               ('20'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC320.ARQ_C320, P_NRSEQARQMAG); 
             V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
             FOR C_REGC321 IN(SELECT ('|C321'         || '|' ||
                                      P.CDARVPROD      || '|' ||
                                      REPLACE(LTRIM(TO_CHAR(ROUND(SUM(IT.QTITEMPROD),3), '999999999990.000')), '.', ',')  || '|' ||
                                      P.SGUNIDADE     || '|' ||
                                      REPLACE(LTRIM(TO_CHAR(ABS(ROUND(SUM(VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL)),0),2)), '999999999990.00')), '.', ',')    || '|' ||
                                      REPLACE(LTRIM(TO_CHAR(ROUND(SUM(IT.VRENCARGODESC),2), '999999999990.00')), '.', ',')    || '|' ||
                                      REPLACE(LTRIM(TO_CHAR(ROUND(SUM(DECODE(CDFISCALIT,'1',VRBASECALCIT, 0)+DECODE(V_IDTPCARGATRIB,'O',0,VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'03','B','1'))),2), '999999999990.00')), '.', ',')   || '|' ||
                                      REPLACE(LTRIM(TO_CHAR(ROUND(SUM(DECODE(CDFISCALIT,'1',I.VRIMPOSTOIT,0)+DECODE(V_IDTPCARGATRIB,'O',0,VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'03','I','1'))),2), '999999999990.00')), '.', ',')    || '|' ||
                                      REPLACE(LTRIM(TO_CHAR(ROUND(SUM(VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '50', 'I','1')),2), '999999999990.00')), '.', ',')    || '|' ||
                                      REPLACE(LTRIM(TO_CHAR(ROUND(SUM(VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '60', 'I','1')),2), '999999999990.00')), '.', ',')    || '|'  ) AS ARQ_C321,
                                      P.CDPRODUTO, P.SGUNIDADE UNID, IT.CDPRODNCMTRANS AS CDCLASFISC
                                 FROM ITEMPROIMPOS I, ITEMPRODUTO IT, PRODUTO P, IMPOSTO IM
                                WHERE IT.CDFILIAL     = C_REGC320.CDFILIAL
                                  AND IT.NRLANCTONF   = C_REGC320.NRLANCTONF
                                  AND I.CDFILIAL      = IT.CDFILIAL
                                  AND I.NRLANCTONF    = IT.NRLANCTONF
                                  AND I.NRSEQITPROD   = IT.NRSEQITPROD
                                  AND IT.CDPRODUTO    = P.CDPRODUTO
                                  AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                  AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                  AND VRALIQITEM      = C_REGC320.VRALIQITEM
                                  AND CDSITUTRIBIT    = C_REGC320.CDSITUTRIBIT
                                  AND CDFISCOPERIT    = C_REGC320.CDFISCOPERIT
                                  AND NRITPROIMPOS    = '1'
                                GROUP BY P.CDARVPROD, P.CDPRODUTO, P.SGUNIDADE, IT.CDPRODNCMTRANS) LOOP
                   INSERT INTO ARQMAGNETICO 
                     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
                   VALUES 
                     ('20'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC321.ARQ_C321, P_NRSEQARQMAG); 
                   V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
                /* CODIGO DO PRODUTO */
                SELECT MAX(CDCHAVEREG) 
                  INTO V_PRODUTO 
                  FROM TMP_REGDADOSSPED 
                 WHERE CDCHAVEREG = C_REGC321.CDPRODUTO 
                   AND CDREGISTRO = '0200';
                IF (V_PRODUTO IS NULL) AND (C_REGC321.CDPRODUTO IS NOT NULL) THEN
                   V_SEQUPROD := NVL(V_SEQUPROD,0) + 1; 
                   INSERT INTO TMP_REGDADOSSPED 
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
                   VALUES 
                     ('0200', V_SEQUPROD, C_REGC321.CDPRODUTO, C_REGC321.CDCLASFISC);
                END IF; 
                V_PRODUTO := NULL; 
                /* UNIDADE DE MEDIDA */
                SELECT MAX(CDCHAVEREG) 
                  INTO V_UNID 
                  FROM TMP_REGDADOSSPED 
                 WHERE CDCHAVEREG = C_REGC321.UNID 
                   AND CDREGISTRO = '0190'; 
                IF (V_UNID IS NULL) AND (C_REGC321.UNID IS NOT NULL) THEN 
                   V_SEQUPROD := NVL(V_SEQUPROD,0) + 1; 
                   INSERT INTO TMP_REGDADOSSPED 
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG) 
                   VALUES 
                     ('0190', V_SEQUPROD, C_REGC321.UNID); 
                END IF; 
                V_UNID := NULL; 
             END LOOP; 
          END LOOP; 
       END LOOP; 
   END IF; 
 
   IF V_CDSITUCRT <> '3' AND P_PERFIL = 'B' THEN /*SIMPLES NACIONAL*/
      FOR C_REGC300 IN (SELECT '|C300'     || '|' ||
                               COD_MOD     || '|' ||
                               SERIE       || '|' ||
                               ''          || '|' ||
                               NUM_DOC     || '|' ||
                               NUM_DOC     || '|' ||
                               DT_DOC      || '|' ||
                               VL_DOC      || '|' ||
                               VL_PIS      || '|' ||
                               VL_COFINS   || '|' ||
                               COD_CTA     || '|'  AS ARQ_C300, NRLANCTONF, CDFILIAL, COD_CTA
                          FROM (SELECT N.CDMODDOCFISC AS COD_MOD,
                                       NVL(SS.CDSERIENFE,N.CDSERIE) AS SERIE,
                                       SUBSTR(LPAD(NRNOTAFISC,10,'0'),5,6) AS NUM_DOC,
                                       TO_CHAR(N.DTEMISSAO,'ddmmyyyy') AS DT_DOC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(N.VRNOTAFISC,2), '999999999990.00')), '.', ',') AS VL_DOC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '50', 'I','1'),2), '999999999990.00')), '.', ',') AS VL_PIS,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '60', 'I','1'),2), '999999999990.00')), '.', ',') AS VL_COFINS,
                                       MAX((SELECT MAX(CONTCTBL_SPED(N.IDENTRSAIDOP,I.CDPRODUTO,N.CDTIPOOPER,N.CDFILIEMIT))
                                              FROM ITEMPRODUTO I
                                             WHERE I.CDFILIAL   = N.CDFILIAL
                                               AND I.NRLANCTONF = N.NRLANCTONF)) AS COD_CTA, I.NRLANCTONF, I.CDFILIAL
                                  FROM IMPOSTONF I, NOTAFISCAL N, IMPOSTO IM, SERIENF SS
                                 WHERE IM.CDIMPOSTONFE = P_CDIMPOSTO
                                   AND N.NRSEQUMAPAPUSN  = V_NRSEQUMAPAPU
                                   AND N.CDINSCESTA    = P_CDINSCESTA
                                   AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                   AND N.CDMODDOCFISC  = '02'
                                   AND NVL(I.IDIMPOSTONF, '1') <> '3'
                                   AND I.CDFILIAL      = N.CDFILIAL
                                   AND I.NRLANCTONF    = N.NRLANCTONF
                                   AND N.IDENTRSAIDOP  = 'S'
                                   AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                   AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                   AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                   AND SS.CDSERIE(+)     = N.CDSERIE
                                   AND NVL(P_GERAFORSALE,'N') = 'N'
                                   AND (NVL(N.IDSISTEMA,'DFS') <> 'REC'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS')
                                 GROUP BY N.CDMODDOCFISC, NVL(SS.CDSERIENFE,N.CDSERIE), SUBSTR(LPAD(NRNOTAFISC,10,'0'),5,6), N.DTEMISSAO,N.VRNOTAFISC,
                                       VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '50', 'I','1'), VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '60', 'I','1'),
                                       I.NRLANCTONF, I.CDFILIAL)) LOOP

         INSERT INTO ARQMAGNETICO
            (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
            ('20'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC300.ARQ_C300, P_NRSEQARQMAG);
         V_CONTREGC := NVL(V_CONTREGC,0) + 1;

         /* PLANO DE CONTAS REFERENCIAL */
         SELECT MAX(CDCHAVEREG)
           INTO V_CONTCTBL
           FROM TMP_REGDADOSSPED
          WHERE CDCHAVEREG = C_REGC300.COD_CTA
            AND CDREGISTRO = '0500';

         IF (V_CONTCTBL IS NULL) AND (C_REGC300.COD_CTA IS NOT NULL) THEN
            V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
            INSERT INTO TMP_REGDADOSSPED
               (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
            VALUES
               ('0500', V_SEQUPROD, C_REGC300.COD_CTA);
         END IF;
         V_CONTCTBL := NULL;

         FOR C_REGC310 IN (SELECT ('|C310'       || '|' ||
                                  LTRIM(N.NRNOTAFISC, '0')  || '|'  ) AS ARQ_C310
                             FROM NOTAFISCAL N
                            WHERE N.CDFILIAL = C_REGC300.CDFILIAL
                              AND N.NRLANCTONF = C_REGC300.NRLANCTONF
                              AND N.IDENTRSAIDOP = 'S'
                              AND N.IDSTATUS = 'C') LOOP
            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('20'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC310.ARQ_C310, P_NRSEQARQMAG);
            V_CONTREGC := NVL(V_CONTREGC,0) + 1;
         END LOOP;

         FOR C_REGC320 IN (SELECT ('|C320'         || '|' ||
                                  CDSITUTRIBIT    || '|' ||
                                  CDFISCOPERIT    || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(VRALIQITEM,2), '999999999990.00')), '.', ',')    || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ABS(ROUND(SUM(VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(CDFILIAL, NRLANCTONF, CDSITUTRIBIT, NRSEQITPROD, CDFISCOPERIT, NULL, NULL, NULL)),0),2)), '999999999990.00')), '.', ',')    || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(SUM(DECODE(CDFISCALIT,'1',VRBASECALCIT,0)+DECODE(V_IDTPCARGATRIB,'O',0,VALOR_IMPOSTO_ITEM_NFE(IT.CDFILIAL,IT.NRLANCTONF,IT.NRSEQITPROD,'03','I','1'))),2), '999999999990.00')), '.', ',')    || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(SUM(DECODE(CDFISCALIT,'1',VRIMPOSTOIT, 0)+DECODE(V_IDTPCARGATRIB,'O',0,VALOR_IMPOSTO_ITEM_NFE(IT.CDFILIAL,IT.NRLANCTONF,IT.NRSEQITPROD,'03','I','1'))),2), '999999999990.00')), '.', ',')    || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ABS(ROUND(NVL(SUM(VALOR_REDUCAO(CDFILIAL, NRLANCTONF, CDSITUTRIBIT, NRSEQITPROD, CDFISCOPERIT, NULL, NULL, NULL) ),0),2)), '999999999990.00')), '.', ',')    || '|' ||
                                  ''  || '|'  ) AS ARQ_C320, CDFILIAL, NRLANCTONF, CDSITUTRIBIT, CDFISCOPERIT, VRALIQITEM
                             FROM ITEMPROIMPOS IT, IMPOSTO IM
                            WHERE IT.CDFILIAL     = C_REGC300.CDFILIAL
                              AND IT.NRLANCTONF   = C_REGC300.NRLANCTONF
                              AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                              AND IM.CDIMPOSTO    = IT.CDIMPOSTO
                              AND IT.NRITPROIMPOS = '1'
                            GROUP BY CDSITUTRIBIT, CDFISCOPERIT, VRALIQITEM,
                                  CDFILIAL, NRLANCTONF) LOOP

            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('20'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC320.ARQ_C320, P_NRSEQARQMAG);
            V_CONTREGC := NVL(V_CONTREGC,0) + 1;

            FOR C_REGC321 IN (SELECT ('|C321'         || '|' ||
                                     P.CDARVPROD      || '|' ||
                                     ROUND(SUM(IT.QTITEMPROD),3)   || '|' ||
                                     P.SGUNIDADE     || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ABS(ROUND(SUM(VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL)),0),2)), '999999999990.00')), '.', ',')    || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(SUM(IT.VRENCARGODESC),2), '999999999990.00')), '.', ',')    || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(SUM(DECODE(CDFISCALIT,'1',VRBASECALCIT, 0)+DECODE(V_IDTPCARGATRIB,'O',0,VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'03','I','1'))),2), '999999999990.00')), '.', ',')   || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(SUM(DECODE(CDFISCALIT,'1',I.VRIMPOSTOIT,0)+DECODE(V_IDTPCARGATRIB,'O',0,VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'03','I','1'))),2), '999999999990.00')), '.', ',')   || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(SUM(VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '50', 'I','1')),2), '999999999990.00')), '.', ',')    || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(SUM(VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '60', 'I','1')),2), '999999999990.00')), '.', ',')    || '|'  ) AS ARQ_C321,
                                     P.CDPRODUTO, P.SGUNIDADE AS UNID, IT.CDPRODNCMTRANS AS CDCLASFISC
                                FROM ITEMPROIMPOS I, ITEMPRODUTO IT, PRODUTO P, IMPOSTO IM
                               WHERE IT.CDFILIAL     = C_REGC320.CDFILIAL
                                 AND IT.NRLANCTONF   = C_REGC320.NRLANCTONF
                                 AND I.CDFILIAL      = IT.CDFILIAL
                                 AND I.NRLANCTONF    = IT.NRLANCTONF
                                 AND I.NRSEQITPROD   = IT.NRSEQITPROD
                                 AND IT.CDPRODUTO    = P.CDPRODUTO
                                 AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                 AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                 AND VRALIQITEM      = C_REGC320.VRALIQITEM
                                 AND CDSITUTRIBIT    = C_REGC320.CDSITUTRIBIT
                                 AND CDFISCOPERIT    = C_REGC320.CDFISCOPERIT
                                 AND NRITPROIMPOS    = '1'
                               GROUP BY P.CDARVPROD, P.CDPRODUTO, P.SGUNIDADE, IT.CDPRODNCMTRANS) LOOP

               INSERT INTO ARQMAGNETICO
                  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                  ('20'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC321.ARQ_C321, P_NRSEQARQMAG);
               V_CONTREGC := NVL(V_CONTREGC,0) + 1;

               /* CODIGO DO PRODUTO */
               SELECT MAX(CDCHAVEREG)
                 INTO V_PRODUTO
                 FROM TMP_REGDADOSSPED
                WHERE CDCHAVEREG = C_REGC321.CDPRODUTO
                  AND CDREGISTRO = '0200';
               IF (V_PRODUTO IS NULL) AND (C_REGC321.CDPRODUTO IS NOT NULL) THEN
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED
                    (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
                  VALUES
                    ('0200', V_SEQUPROD, C_REGC321.CDPRODUTO, C_REGC321.CDCLASFISC);
               END IF;
               V_PRODUTO := NULL;

               /* UNIDADE DE MEDIDA */
               SELECT MAX(CDCHAVEREG)
                 INTO V_UNID
                 FROM TMP_REGDADOSSPED
                WHERE CDCHAVEREG = C_REGC321.UNID
                  AND CDREGISTRO = '0190';
               IF (V_UNID IS NULL) AND (C_REGC321.UNID IS NOT NULL) THEN
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED
                    (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
                  VALUES
                    ('0190', V_SEQUPROD, C_REGC321.UNID);
               END IF;
               V_UNID := NULL;
            END LOOP;
         END LOOP;
      END LOOP;
   END IF;

   IF V_CDSITUCRT = '3' AND P_PERFIL = 'A' THEN
      /*REGISTRO C350*/
      FOR C_REGC350 IN (SELECT '|C350'       || '|' ||
                               SERIE         || '|' ||
                               ''            || '|' ||
                               NUM_DOC       || '|' ||
                               DT_DOC        || '|' ||
                               CNPJ_CPF      || '|' || --CPF_CNPJ
                               VL_MERC       || '|' ||
                               VL_DOC        || '|' ||
                               VL_DESC       || '|' ||
                               VL_PIS        || '|' ||
                               VL_COFINS     || '|' ||
                               COD_CTA       || '|' AS ARQ_C350, NRLANCTONF, CDFILIAL, CDCLIENTE, CDCAIXA, COD_CTA
                          FROM (SELECT NVL(SS.CDSERIENFE,N.CDSERIE) AS SERIE,
                                       SUBSTR(LPAD(NRNOTAFISC,10,'0'),5,6) AS NUM_DOC,
                                       TO_CHAR(N.DTEMISSAO,'ddmmyyyy') AS DT_DOC,
                                       NVL(SUBSTR(REPLACE(REPLACE(REPLACE(REPLACE(CASE WHEN (LENGTH(N.NRINSJURNF) = 14 OR LENGTH(N.NRINSJURNF) = 11) THEN N.NRINSJURNF ELSE N.NRINSJURNFPAULI END,'.'),'-'),'/'),' '),1,14),'') AS CNPJ_CPF,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(N.VRPRODUTOS,2), '999999999990.00')), '.', ',') AS VL_MERC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(N.VRNOTAFISC,2), '999999999990.00')), '.', ',') AS VL_DOC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(SUM(T.VRITEMENCA),2), '999999999990.00')), '.', ',') AS VL_DESC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '50', 'I','1'),2), '999999999990.00')), '.', ',') AS VL_PIS,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '60', 'I','1'),2), '999999999990.00')), '.', ',') AS VL_COFINS,
                                       MAX((SELECT MAX(CONTCTBL_SPED(N.IDENTRSAIDOP,I.CDPRODUTO,N.CDTIPOOPER,N.CDFILIEMIT))
                                                     FROM ITEMPRODUTO I
                                                    WHERE I.CDFILIAL   = N.CDFILIAL
                                                      AND I.NRLANCTONF = N.NRLANCTONF)) AS COD_CTA,
                                       I.NRLANCTONF, I.CDFILIAL, N.CDCLIENTE, '' AS  CDCAIXA
                                  FROM IMPOSTONF I, NOTAFISCAL N, ENCARGO E, ITEMENCARGO T, IMPOSTO IM, SERIENF SS
                                 WHERE I.CDIMPOSTO      = IM.CDIMPOSTO
                                   AND IM.CDIMPOSTONFE  = P_CDIMPOSTO
                                   AND I.NRSEQUMAPAPU   = V_NRSEQUMAPAPU
                                   AND N.CDFILIAL       = T.CDFILIAL
                                   AND N.NRLANCTONF     = T.NRLANCTONF
                                   AND E.CDENCARGO      = T.CDENCARGO
                                   AND E.IDENCARGO      = 'D'
                                   AND N.CDMODDOCFISC   = '02'
                                   AND NVL(I.IDIMPOSTONF, '1') <> '3'
                                   AND I.CDFILIAL       = N.CDFILIAL
                                   AND I.NRLANCTONF     = N.NRLANCTONF
                                   AND N.IDENTRSAIDOP   = 'S'
                                   AND SS.CDEMPRESA(+)  = N.CDEMPRESA
                                   AND SS.CDINSCESTA(+) = N.CDINSCESTA
                                   AND SS.CDINSCMUNI(+) = N.CDINSCMUNI
                                   AND SS.CDSERIE(+)    = N.CDSERIE
                                   AND NVL(P_GERAFORSALE,'N') = 'N'
                                   AND (NVL(N.IDSISTEMA,'DFS') <> 'REC'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS')
                                 GROUP BY NVL(SS.CDSERIENFE,N.CDSERIE), SUBSTR(LPAD(NRNOTAFISC,10,'0'),5,6), TO_CHAR(N.DTEMISSAO,'ddmmyyyy'),
                                       N.CDCLIENTE, N.VRPRODUTOS, N.VRNOTAFISC,
                                       VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '50', 'I','1'),
                                       VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '60', 'I','1'),
                                       I.NRLANCTONF, I.CDFILIAL, '',
                                       NVL(SUBSTR(REPLACE(REPLACE(REPLACE(REPLACE(CASE WHEN (LENGTH(N.NRINSJURNF) = 14 OR LENGTH(N.NRINSJURNF) = 11) THEN N.NRINSJURNF ELSE N.NRINSJURNFPAULI END,'.'),'-'),'/'),' '),1,14),'')
                                 UNION
                                 /*GERA C350 PARA O FORSALE - C300 FOS*/
                                SELECT 'D' AS SERIE,
                                       SUBSTR(LPAD(NRNOTAFISC,10,'0'),5,6) AS NUM_DOC,
                                       TO_CHAR(DTEMISSAO,'DDMMYYYY') AS DT_DOC,
                                       NVL(REPLACE(REPLACE(REPLACE(REPLACE(NRINSCRCONS,'.'),'-'),'/'),' '),'') AS CNPJ_CPF,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VRNOTAFISC+VRDESITVEND,2), '999999999990.00')), '.', ',') AS VL_MERC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VRNOTAFISC,2), '999999999990.00')), '.', ',')  AS VL_DOC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VRDESITVEND,2), '999999999990.00')), '.', ',') AS VL_DESC,
                                       '0,00' AS VL_PIS,
                                       '0,00' AS VL_COFINS,
                                       CONTCTBL_SPED('S','',CDTIPOOPER,CDFILIAL) AS COD_CTA,
                                       NRLANCTONF, CDFILIAL, '' CDCLIENTE, CDCAIXA
                                  FROM (SELECT VE.DTENTRVENDA AS DTEMISSAO, VE.NRSERIEVND AS CDSERIE ,VE.NRSUBSERIEVND ,VE.NRORDEMVND AS NRNOTAFISC,
                                               SUM(TRUNC(IT.QTPRODVEND * (IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0)),2) - NVL(IT.VRDESITVEND,0) + NVL(IT.VRACRITVEND,0)) AS VRNOTAFISC,
                                               SUM(VRDESITVEND) AS VRDESITVEND, PV.CDTPOPERCNTREC AS CDTIPOOPER,
                                               VE.CDFILIAL, VE.NRSEQVENDA AS NRLANCTONF, VE.CDCAIXA, VE.NRINSCRCONS
                                          FROM VENDA VE, ITEMVENDA IT, PARAVEND PV
                                         WHERE VE.CDEMPRESA     =  P_CDEMPRESA
                                           AND VE.CDFILIAL      = IT.CDFILIAL
                                           AND VE.NRSEQVENDA    = IT.NRSEQVENDA
                                           AND VE.CDCAIXA       = IT.CDCAIXA
                                           AND VE.DTENTRVENDA   BETWEEN P_DTINICIAL AND P_DTFINAL
                                           AND VE.IDSITUVENDA   = 'O'
                                           AND VE.NRORDEMVND    IS NOT NULL
                                           AND VE.NRSUBSERIEVND IS NOT NULL
                                           AND VE.NRSERIEVND    IS NOT NULL
                                           AND NVL(P_GERAFORSALE,'N') = 'S'
                                           AND VE.CDFILIAL      = PV.CDFILIAL(+)
                                         GROUP BY VE.DTENTRVENDA, VE.NRSERIEVND, VE.NRSUBSERIEVND, VE.NRORDEMVND, VE.NRSEQVENDA,
                                               VE.CDFILIAL, VE.CDCAIXA, VE.NRINSCRCONS, PV.CDTPOPERCNTREC))) LOOP
         INSERT INTO ARQMAGNETICO
            (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
            ('24'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC350.ARQ_C350, P_NRSEQARQMAG);
         V_CONTREGC := NVL(V_CONTREGC,0) + 1;

         /* PLANO DE CONTAS REFERENCIAL */
         SELECT MAX(CDCHAVEREG)
           INTO V_CONTCTBL
           FROM TMP_REGDADOSSPED
          WHERE CDCHAVEREG = C_REGC350.COD_CTA
            AND CDREGISTRO = '0500';

         IF (V_CONTCTBL IS NULL) AND (C_REGC350.COD_CTA IS NOT NULL) THEN
            V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
            INSERT INTO TMP_REGDADOSSPED
               (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
            VALUES
               ('0500', V_SEQUPROD, C_REGC350.COD_CTA);
         END IF;
         V_CONTCTBL := NULL;

         V_NRSEQITEM := 0;
         FOR C_REGC370 IN(SELECT (P.CDARVPROD  || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(IT.QTITEMPROD,3), '99999999990.000')), '.', ',')  ||'|'||
                                  P.SGUNIDADE               || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND((SUM(I.VRCONTITIMP)),2), '999999999990.00')), '.', ',')    || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND((SUM(IT.VRENCARGODESC)),2), '999999999990.00')), '.', ',')    || '|' ) AS ARQ_C370,
                                  P.CDPRODUTO, P.SGUNIDADE AS UNID, IT.CDPRODNCMTRANS AS CDCLASFISC
                            FROM ITEMPROIMPOS I, ITEMPRODUTO IT, PRODUTO P, IMPOSTO IM
                           WHERE IT.CDFILIAL      = C_REGC350.CDFILIAL
                             AND IT.NRLANCTONF    = C_REGC350.NRLANCTONF
                             AND I.CDIMPOSTO      = IM.CDIMPOSTO
                             AND I.CDFILIAL       = IT.CDFILIAL
                             AND I.NRLANCTONF     = IT.NRLANCTONF
                             AND I.NRSEQITPROD    = IT.NRSEQITPROD
                             AND IT.CDPRODUTO     = P.CDPRODUTO
                             AND IM.CDIMPOSTONFE  = P_CDIMPOSTO
                             AND NVL(P_GERAFORSALE,'N') = 'N'
                           GROUP BY SUBSTR(I.NRSEQITPROD,2,3), P.CDARVPROD, IT.QTITEMPROD, P.SGUNIDADE, P.CDPRODUTO, IT.CDPRODNCMTRANS
                           UNION
                          SELECT CDARVPROD    ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(QTPRODVEND,3), '99999999990.000')), '.', ',')  ||'|'||
                                 SGUNIDADE    ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VR_TOT_IT,2), '999999999990.00')), '.', ',')   ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VRDESITVEND,2), '999999999990.00')), '.', ',') ||'|' AS ARQ_C370,
                                 CDPRODUTO, SGUNIDADE AS UNID, CDCLASFISC
                           FROM (SELECT NRSEQUITVEND,
                                        CDARVPROD,
                                        QTPRODVEND,
                                        P.SGUNIDADE,
                                        (IV.VRUNITVEND+NVL(IV.VRUNITVENDCL,0)+NVL(IV.VRACRITVEND,0)) AS VR_TOT_IT,
                                        VRDESITVEND, P.CDPRODUTO, IV.CDCLASFISC
                                   FROM ITEMVENDA IV, PRODUTO P
                                  WHERE IV.CDFILIAL = C_REGC350.CDFILIAL
                                    AND IV.CDCAIXA = C_REGC350.CDCAIXA
                                    AND IV.NRSEQVENDA =  C_REGC350.NRLANCTONF
                                    AND NVL(P_GERAFORSALE,'N') = 'S'
                                    AND IV.CDPRODUTO = P.CDPRODUTO)NF) LOOP

               V_NRSEQITEM := NVL(V_NRSEQITEM,0)+1;
               INSERT INTO ARQMAGNETICO
                 (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
               VALUES
                 ('24'||LPAD(RTRIM(V_CONTREGC), 8, '0'), '|C370|'||LPAD(V_NRSEQITEM,3,'0')||'|'||C_REGC370.ARQ_C370, P_NRSEQARQMAG);
               V_CONTREGC := NVL(V_CONTREGC,0) + 1;
 
               /* CODIGO DO PRODUTO */
               SELECT MAX(CDCHAVEREG)
                 INTO V_PRODUTO
                 FROM TMP_REGDADOSSPED
                WHERE CDCHAVEREG = C_REGC370.CDPRODUTO
                  AND CDREGISTRO = '0200';

               IF (V_PRODUTO IS NULL) AND (C_REGC370.CDPRODUTO IS NOT NULL) THEN
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1; 
                  INSERT INTO TMP_REGDADOSSPED
                    (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
                  VALUES
                    ('0200', V_SEQUPROD, C_REGC370.CDPRODUTO, C_REGC370.CDCLASFISC);
               END IF;
               V_PRODUTO := NULL;

               /* UNIDADE DE MEDIDA */
               SELECT MAX(CDCHAVEREG)
                 INTO V_UNID 
                 FROM TMP_REGDADOSSPED
                WHERE CDCHAVEREG = C_REGC370.UNID
                  AND CDREGISTRO = '0190';

               IF (V_UNID IS NULL) AND (C_REGC370.UNID IS NOT NULL) THEN
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED
                    (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
                  VALUES
                    ('0190', V_SEQUPROD, C_REGC370.UNID);
               END IF;
               V_UNID := NULL;
         END LOOP;

         FOR C_REGC390 IN(SELECT ('|C390'         || '|' ||
                                  NF.CDSITUTRIBNF|| '|' ||
                                  NF.CDFISCOPERNF    || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRALIQNF,2),     '999999999990.00')), '.', ',')  || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRCONTABILNF,2), '999999999990.00')), '.', ',')  || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRBASECALCNF + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(NF.VRBASECARGA,0))),2), '999999999990.00')), '.', ',')  || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRIMPOSTONF  + DECODE(V_IDTPCARGATRIB,'O',0,NVL(NF.VRIMPCARGA, 0)),2), '999999999990.00')), '.', ',')  || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRREDBCALC,2),   '999999999990.00')), '.', ',')  || '|' ||
                                  ''  || '|'  ) AS ARQ_C390, CDFISCOPERNF
                            FROM (SELECT NVL(CDSITUTRIBNF,'000') AS CDSITUTRIBNF,
                                         CDFISCOPERNF,
                                         VRALIQNF,
                                         SUM(VRCONTABILNF) AS VRCONTABILNF,
                                         SUM((SELECT SUM(VRBASECALCNF)
                                                FROM IMPOSTONF IP
                                               WHERE IP.CDFILIAL     = I.CDFILIAL
                                                 AND IP.NRLANCTONF   = I.NRLANCTONF
                                                 AND IP.CDFISCOPERNF = I.CDFISCOPERNF
                                                 AND IP.CDIMPOSTO    = IM.CDIMPCARGATRIB)) AS VRBASECARGA,
                                         SUM(VRBASECALCNF) AS VRBASECALCNF,
                                         SUM(VRIMPCARGATRIBI) AS VRIMPCARGA,
                                         SUM(VRIMPOSTONF) AS VRIMPOSTONF,
                                         SUM(DECODE(IDIMPOSTONF, '2', VRCONTABILNF, '0')) AS VRREDBCALC
                                    FROM IMPOSTONF I, IMPOSTO IM
                                   WHERE I.CDFILIAL      = C_REGC350.CDFILIAL
                                     AND I.NRLANCTONF    = C_REGC350.NRLANCTONF
                                     AND I.CDIMPOSTO     = IM.CDIMPOSTO
                                     AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                     AND IDIMPOSTONF     <> '3'
                                     AND NVL(P_GERAFORSALE,'N') = 'N' 
                                   GROUP BY NVL(CDSITUTRIBNF,'000'), CDFISCOPERNF, VRALIQNF)NF
                           UNION
                          /*GERA REGISTRO C390 PARA O FOS - C390 FOS*/
                          SELECT '|C390'      ||'|'||
                                 CDSITUTRIBIT ||'|'||
                                 CDFISCOPERIT ||'|'||
                                 VRALIQITEM   ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VR_OPER,2), '999999999990.00')), '.', ',')    ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VR_BC_ICMS,2), '999999999990.00')), '.', ',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VR_ICMS,2), '999999999990.00')), '.', ',')    ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VR_RED,2), '999999999990.00')), '.', ',')     ||'|'||
                                 COD_OB       ||'|' AS ARQ_C390, CDFISCOPERIT AS CDFISCOPERNF
                            FROM (SELECT (NVL(LPAD(IVI.CDCSTPRODI,3,'0'), CASE WHEN IP.IDTPIMPOSFIS = 'T' THEN '000'
                                                                               WHEN IP.IDTPIMPOSFIS = 'I' THEN '040'
                                                                               WHEN IP.IDTPIMPOSFIS = 'F' THEN '060'
                                                                               WHEN IP.IDTPIMPOSFIS = 'N' THEN '041' END)) AS CDSITUTRIBIT,
                                         NVL(IVI.CDCSTPRODPC,'5102')  AS CDFISCOPERIT,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(IVI.VRPEALPRODIT,2), '999999999990.00')), '.', ',') AS VRALIQITEM,
                                         (CASE WHEN IP.CDIMPOSTONFE = P_CDIMPOSTO
                                               THEN SUM(TRUNC(IV.QTPRODVEND * (IV.VRUNITVEND+NVL(IV.VRUNITVENDCL,0)),2) - NVL(IV.VRDESITVEND,0) + NVL(IV.VRACRITVEND,0))
                                               ELSE 0 END) AS VR_OPER,
                                         (CASE WHEN IP.IDTPIMPOSFIS = 'T' AND IP.CDIMPOSTONFE = P_CDIMPOSTO
                                               THEN SUM(TRUNC(IV.QTPRODVEND * (IV.VRUNITVEND+NVL(IV.VRUNITVENDCL,0)),2) - NVL(IV.VRDESITVEND,0) + NVL(IV.VRACRITVEND,0))
                                               ELSE 0 END) AS VR_BC_ICMS,
                                         (CASE WHEN IP.IDTPIMPOSFIS = 'T' AND IP.CDIMPOSTONFE = P_CDIMPOSTO
                                               THEN SUM(IVI.VRIMPOPRODIT)
                                               ELSE 0 END) AS VR_ICMS,
                                         0 AS VR_RED,'' AS COD_OB, IP.CDIMPOSTONFE
                                    FROM ITEMVENDA IV, ITVENDAIMPOS IVI, IMPOSTO IP
                                   WHERE IV.CDFILIAL     = IVI.CDFILIAL
                                     AND IV.CDCAIXA      = IVI.CDCAIXA
                                     AND IV.NRSEQUITVEND = IVI.NRSEQUITVEND
                                     AND IV.NRSEQVENDA   = IVI.NRSEQVENDA
                                     AND IV.CDFILIAL     = C_REGC350.CDFILIAL
                                     AND IV.CDCAIXA      =  C_REGC350.CDCAIXA
                                     AND IV.NRSEQVENDA   = C_REGC350.NRLANCTONF
                                     AND NVL(P_GERAFORSALE,'N') = 'S'
                                     AND IP.CDIMPOSTO    = IVI.CDIMPOSTO
                                   GROUP BY IVI.CDCSTPRODI, IVI.CDCSTPRODPC, IP.IDTPIMPOSFIS, IVI.VRPEALPRODIT, IP.CDIMPOSTONFE)NF
                           WHERE NF.CDIMPOSTONFE = P_CDIMPOSTO) LOOP
            INSERT INTO ARQMAGNETICO
              (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
              ('24'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC390.ARQ_C390, P_NRSEQARQMAG);
            V_CONTREGC := NVL(V_CONTREGC,0) + 1;
         END LOOP;
      END LOOP;
   END IF;

   IF V_CDSITUCRT <> '3' AND P_PERFIL = 'A' THEN  /*SIMPLES NACIONAL*/
      /*REGISTRO C350*/
      FOR C_REGC350 IN (SELECT '|C350'     || '|' ||
                               SERIE       || '|' ||
                               ''          || '|' ||
                               NUM_DOC     || '|' ||
                               DT_DOC      || '|' ||
                               CNPJ_CPF    || '|' ||
                               VL_MERC     || '|' ||
                               VL_DOC      || '|' ||
                               VL_DESC     || '|' ||
                               VL_PIS      || '|' ||
                               VL_COFINS   || '|' ||
                               COD_CTA     || '|' AS ARQ_C350, NRLANCTONF, CDFILIAL, CDCLIENTE, CDCAIXA, COD_CTA
                          FROM (SELECT NVL(SS.CDSERIENFE,N.CDSERIE) AS SERIE,
                                       LTRIM(NRNOTAFISC, '0') AS NUM_DOC,
                                       TO_CHAR(N.DTEMISSAO,'ddmmyyyy') AS DT_DOC,
                                       NVL(SUBSTR(REPLACE(REPLACE(REPLACE(REPLACE(N.NRINSJURNF,'.'),'-'),'/'),' '),1,14),'') AS CNPJ_CPF,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(N.VRPRODUTOS,2), '999999999990.00')), '.', ',') AS VL_MERC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(N.VRNOTAFISC,2), '999999999990.00')), '.', ',') AS VL_DOC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(SUM(T.VRITEMENCA),2), '999999999990.00')), '.', ',') AS VL_DESC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '50', 'I','1'),2), '999999999990.00')), '.', ',') AS VL_PIS,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '60', 'I','1'),2), '999999999990.00')), '.', ',') AS VL_COFINS,
                                       MAX((SELECT MAX(CONTCTBL_SPED(N.IDENTRSAIDOP,I.CDPRODUTO,N.CDTIPOOPER,N.CDFILIEMIT))
                                                     FROM ITEMPRODUTO I
                                                    WHERE I.CDFILIAL   = N.CDFILIAL
                                                      AND I.NRLANCTONF = N.NRLANCTONF)) AS COD_CTA,
                                       I.NRLANCTONF, I.CDFILIAL, N.CDCLIENTE, '' AS  CDCAIXA
                                  FROM IMPOSTONF I, NOTAFISCAL N, ENCARGO E, ITEMENCARGO T, IMPOSTO IM, SERIENF SS
                                 WHERE I.CDIMPOSTO = IM.CDIMPOSTO
                                   AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                   AND N.NRSEQUMAPAPUSN = V_NRSEQUMAPAPU
                                   AND N.CDINSCESTA = P_CDINSCESTA
                                   AND N.CDFILIAL = T.CDFILIAL
                                   AND N.NRLANCTONF = T.NRLANCTONF
                                   AND E.CDENCARGO = T.CDENCARGO
                                   AND E.IDENCARGO = 'D'
                                   AND N.CDMODDOCFISC = '02'
                                   AND NVL(I.IDIMPOSTONF, '1') <> '3'
                                   AND I.CDFILIAL = N.CDFILIAL
                                   AND I.NRLANCTONF = N.NRLANCTONF
                                   AND N.IDENTRSAIDOP = 'S'
                                   AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                   AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                   AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                   AND SS.CDSERIE(+)     = N.CDSERIE
                                   AND NVL(P_GERAFORSALE,'N') = 'N'
                                   AND (NVL(N.IDSISTEMA,'DFS') <> 'REC'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP'
                                   AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS')
                                 GROUP BY NVL(SS.CDSERIENFE,N.CDSERIE), LTRIM(NRNOTAFISC, '0'),TO_CHAR(N.DTEMISSAO,'ddmmyyyy'),
                                          NVL(SUBSTR(REPLACE(REPLACE(REPLACE(REPLACE(N.NRINSJURNF,'.'),'-'),'/'),' '),1,14),''),
                                          N.CDCLIENTE, N.VRPRODUTOS, N.VRNOTAFISC,
                                          VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '50', 'I','1'),
                                          VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, '60', 'I','1'),
                                          I.NRLANCTONF, I.CDFILIAL, ''
                                 UNION
                                /*GERA C350 PARA O FORSALE - C300 FOS*/
                                SELECT 'D' AS SERIE,
                                       SUBSTR(LPAD(NRNOTAFISC,10,'0'),5,6) AS NUM_DOC,
                                       TO_CHAR(DTEMISSAO,'DDMMYYYY') AS DT_DOC,
                                       NVL(REPLACE(REPLACE(REPLACE(REPLACE(NRINSCRCONS,'.'),'-'),'/'),' '),'') AS CNPJ_CPF,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VRNOTAFISC+VRDESITVEND,2), '999999999990.00')), '.', ',') AS VL_MERC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VRNOTAFISC, 2), '999999999990.00')), '.', ',') AS VL_DOC,
                                       REPLACE(LTRIM(TO_CHAR(ROUND(VRDESITVEND,2), '999999999990.00')), '.', ',') AS VL_DESC,
                                       '0,00' AS VL_PIS,
                                       '0,00' AS VL_COFINS,
                                       CONTCTBL_SPED('S','',CDTIPOOPER,CDFILIAL) AS COD_CTA,
                                       NRLANCTONF, CDFILIAL, '' CDCLIENTE ,CDCAIXA
                                  FROM (SELECT VE.DTENTRVENDA AS DTEMISSAO, VE.NRSERIEVND AS CDSERIE ,VE.NRSUBSERIEVND ,VE.NRORDEMVND AS NRNOTAFISC,
                                               SUM(TRUNC(IT.QTPRODVEND * (IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0)),2) - NVL(IT.VRDESITVEND,0) + NVL(IT.VRACRITVEND,0)) AS VRNOTAFISC,
                                               SUM(VRDESITVEND) AS VRDESITVEND, PV.CDTPOPERCNTREC AS CDTIPOOPER,
                                               VE.CDFILIAL, VE.NRSEQVENDA AS NRLANCTONF, VE.CDCAIXA, VE.NRINSCRCONS
                                          FROM VENDA VE, ITEMVENDA IT, PARAVEND PV
                                         WHERE VE.CDEMPRESA   =  P_CDEMPRESA
                                           AND VE.CDFILIAL    = IT.CDFILIAL
                                           AND VE.NRSEQVENDA  = IT.NRSEQVENDA
                                           AND VE.CDCAIXA     = IT.CDCAIXA
                                           AND VE.DTENTRVENDA BETWEEN P_DTINICIAL AND P_DTFINAL
                                           AND VE.IDSITUVENDA = 'O'
                                           AND VE.NRORDEMVND  IS NOT NULL
                                           AND NVL(P_GERAFORSALE,'N') = 'S'
                                           AND VE.CDFILIAL    = PV.CDFILIAL(+)
                                         GROUP BY VE.DTENTRVENDA, VE.NRSERIEVND,VE.NRSUBSERIEVND, VE.NRORDEMVND, VE.NRSEQVENDA,
                                               VE.CDFILIAL, VE.CDCAIXA, VE.NRINSCRCONS, PV.CDTPOPERCNTREC))) LOOP
         INSERT INTO ARQMAGNETICO
           (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
           ('24'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC350.ARQ_C350, P_NRSEQARQMAG);
         V_CONTREGC := NVL(V_CONTREGC,0) + 1;

         /* PLANO DE CONTAS REFERENCIAL */
         SELECT MAX(CDCHAVEREG)
           INTO V_CONTCTBL
           FROM TMP_REGDADOSSPED
          WHERE CDCHAVEREG = C_REGC350.COD_CTA
            AND CDREGISTRO = '0500';

         IF (V_CONTCTBL IS NULL) AND (C_REGC350.COD_CTA IS NOT NULL) THEN
            V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
            INSERT INTO TMP_REGDADOSSPED
               (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
            VALUES
               ('0500', V_SEQUPROD, C_REGC350.COD_CTA);
         END IF;
         V_CONTCTBL := NULL;

         V_NRSEQITEM := 0;
         FOR C_REGC370 IN(SELECT (P.CDARVPROD  || '|' ||
                                  IT.QTITEMPROD             || '|' ||
                                  P.SGUNIDADE               || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND((SUM(I.VRCONTITIMP)),2), '999999999990.00')), '.', ',')    || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND((SUM(IT.VRENCARGODESC)),2), '999999999990.00')), '.', ',')    || '|' ) AS ARQ_C370,
                                  P.CDPRODUTO, P.SGUNIDADE AS UNID, IT.CDPRODNCMTRANS AS CDCLASFISC
                            FROM ITEMPROIMPOS I, ITEMPRODUTO IT, PRODUTO P, IMPOSTO IM
                           WHERE IT.CDFILIAL      = C_REGC350.CDFILIAL
                             AND IT.NRLANCTONF    = C_REGC350.NRLANCTONF
                             AND I.CDIMPOSTO      = IM.CDIMPOSTO
                             AND I.CDFILIAL       = IT.CDFILIAL
                             AND I.NRLANCTONF     = IT.NRLANCTONF
                             AND I.NRSEQITPROD    = IT.NRSEQITPROD
                             AND IT.CDPRODUTO     = P.CDPRODUTO
                             AND IM.CDIMPOSTONFE  = P_CDIMPOSTO
                             AND NVL(P_GERAFORSALE,'N') = 'N'
                           GROUP BY SUBSTR(I.NRSEQITPROD,2,3), P.CDARVPROD, IT.QTITEMPROD, P.SGUNIDADE, P.CDPRODUTO, IT.CDPRODNCMTRANS
                           UNION
                          SELECT CDARVPROD    ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(QTPRODVEND, 3), '99999999990.000')), '.', ',') ||'|'||
                                 SGUNIDADE    ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VR_TOT_IT,  2), '999999999990.00')), '.', ',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VRDESITVEND,2), '999999999990.00')), '.', ',') ||'|' AS ARQ_C370,
                                 CDPRODUTO, SGUNIDADE AS UNID, CDCLASFISC
                           FROM (SELECT NRSEQUITVEND,
                                        P.CDARVPROD,
                                        QTPRODVEND,
                                        P.SGUNIDADE,
                                        (IV.VRUNITVEND+NVL(IV.VRUNITVENDCL,0)+NVL(IV.VRACRITVEND,0))  AS VR_TOT_IT,
                                        VRDESITVEND, P.CDPRODUTO, IV.CDCLASFISC
                                   FROM ITEMVENDA IV, PRODUTO P
                                  WHERE IV.CDFILIAL   = C_REGC350.CDFILIAL
                                    AND IV.CDCAIXA    = C_REGC350.CDCAIXA
                                    AND IV.NRSEQVENDA =  C_REGC350.NRLANCTONF
                                    AND NVL(P_GERAFORSALE,'N') = 'S'
                                    AND IV.CDPRODUTO  = P.CDPRODUTO)NF) LOOP

               V_NRSEQITEM := NVL(V_NRSEQITEM,0)+1;
               INSERT INTO ARQMAGNETICO
                 (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                 ('24'||LPAD(RTRIM(V_CONTREGC), 8, '0'), '|C370|'||LPAD(V_NRSEQITEM,3,'0')||'|'||C_REGC370.ARQ_C370, P_NRSEQARQMAG);
               V_CONTREGC := NVL(V_CONTREGC,0) + 1;

               /* CODIGO DO PRODUTO */
               SELECT MAX(CDCHAVEREG)
                 INTO V_PRODUTO
                 FROM TMP_REGDADOSSPED
                WHERE CDCHAVEREG = C_REGC370.CDPRODUTO
                  AND CDREGISTRO = '0200';

               IF (V_PRODUTO IS NULL) AND (C_REGC370.CDPRODUTO IS NOT NULL) THEN
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED
                    (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
                  VALUES
                    ('0200', V_SEQUPROD, C_REGC370.CDPRODUTO, C_REGC370.CDCLASFISC);
               END IF;
               V_PRODUTO := NULL;

               /* UNIDADE DE MEDIDA */
               SELECT MAX(CDCHAVEREG)
                 INTO V_UNID
                 FROM TMP_REGDADOSSPED
                WHERE CDCHAVEREG = C_REGC370.UNID
                  AND CDREGISTRO = '0190';

               IF (V_UNID IS NULL) AND (C_REGC370.UNID IS NOT NULL) THEN
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED
                    (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
                  VALUES
                    ('0190', V_SEQUPROD, C_REGC370.UNID);
               END IF;
               V_UNID := NULL;
         END LOOP;

         FOR C_REGC390 IN(SELECT ('|C390'         || '|' ||
                                  NF.CDSITUTRIBNF|| '|' ||
                                  NF.CDFISCOPERNF    || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRALIQNF,2), '999999999990.00')), '.', ',')    || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRCONTABILNF,2), '999999999990.00')), '.', ',')    || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRBASECALCNF + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(NF.VRBASECARGA,0))),2), '999999999990.00')), '.', ',')    || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRIMPOSTONF  + DECODE(V_IDTPCARGATRIB,'O',0,NVL(NF.VRIMPCARGA,0)),2), '999999999990.00')), '.', ',')    || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRREDBCALC,2), '999999999990.00')), '.', ',')    || '|' ||
                                  ''  || '|'  ) AS ARQ_C390, CDFISCOPERNF
                          FROM(SELECT NVL(CDSITUTRIBNF,'000') AS CDSITUTRIBNF,
                                      CDFISCOPERNF,
                                      VRALIQNF,
                                      SUM(VRCONTABILNF) AS VRCONTABILNF,
                                      SUM(VRBASECALCNF) AS VRBASECALCNF,
                                      SUM((SELECT SUM(VRBASECALCNF)
                                             FROM IMPOSTONF IP
                                            WHERE IP.CDFILIAL     = I.CDFILIAL
                                              AND IP.NRLANCTONF   = I.NRLANCTONF
                                              AND IP.CDFISCOPERNF = I.CDFISCOPERNF
                                              AND IP.CDIMPOSTO    = IM.CDIMPCARGATRIB)) AS VRBASECARGA,
                                      SUM(VRIMPOSTONF) AS VRIMPOSTONF,
                                      SUM(VRIMPCARGATRIBI) AS VRIMPCARGA,
                                      SUM(DECODE(IDIMPOSTONF, '2', VRCONTABILNF, '0')) AS VRREDBCALC
                                 FROM IMPOSTONF I, IMPOSTO IM 
                                WHERE I.CDFILIAL      = C_REGC350.CDFILIAL
                                  AND I.NRLANCTONF    = C_REGC350.NRLANCTONF 
                                  AND I.CDIMPOSTO     = IM.CDIMPOSTO
                                  AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                  AND IDIMPOSTONF <> '3'
                                  AND NVL(P_GERAFORSALE,'N') = 'N'
                                GROUP BY NVL(CDSITUTRIBNF,'000'), CDFISCOPERNF, VRALIQNF) NF
                          UNION
                          /*GERA REGISTRO C390 PARA O FOS - C390 FOS*/
                          SELECT '|C390'      ||'|'||
                                 CDSITUTRIBIT ||'|'||
                                 CDFISCOPERIT ||'|'||
                                 VRALIQITEM   ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VR_OPER,2), '999999999990.00')), '.', ',')    ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VR_BC_ICMS,2), '999999999990.00')), '.', ',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VR_ICMS,2), '999999999990.00')), '.', ',')    ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(VR_RED,2), '999999999990.00')), '.', ',')     ||'|'||
                                 COD_OB       ||'|' AS ARQ_C390, CDFISCOPERIT AS CDFISCOPERNF
                            FROM (SELECT (NVL(LPAD(IVI.CDCSTPRODI,3,'0'), CASE WHEN IP.IDTPIMPOSFIS = 'T' THEN '000'
                                                                               WHEN IP.IDTPIMPOSFIS = 'I' THEN '040'
                                                                               WHEN IP.IDTPIMPOSFIS = 'F' THEN '060'
                                                                               WHEN IP.IDTPIMPOSFIS = 'N' THEN '041' END)) AS CDSITUTRIBIT,
                                         NVL(IVI.CDCSTPRODPC,'5102')  AS CDFISCOPERIT,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(IVI.VRPEALPRODIT,2), '999999999990.00')), '.', ',') AS VRALIQITEM,
                                         (CASE WHEN IP.CDIMPOSTONFE = P_CDIMPOSTO
                                               THEN SUM(TRUNC(IV.QTPRODVEND * (IV.VRUNITVEND+NVL(IV.VRUNITVENDCL,0)),2) - NVL(IV.VRDESITVEND,0) + NVL(IV.VRACRITVEND,0))
                                               ELSE 0 END) AS VR_OPER,
                                         (CASE WHEN IP.IDTPIMPOSFIS = 'T' AND IP.CDIMPOSTONFE = P_CDIMPOSTO
                                               THEN SUM(TRUNC(IV.QTPRODVEND * (IV.VRUNITVEND+NVL(IV.VRUNITVENDCL,0)),2) - NVL(IV.VRDESITVEND,0) + NVL(IV.VRACRITVEND,0))
                                               ELSE 0 END) AS VR_BC_ICMS,
                                         (CASE WHEN IP.IDTPIMPOSFIS = 'T' AND IP.CDIMPOSTONFE = P_CDIMPOSTO
                                               THEN SUM(IVI.VRIMPOPRODIT)
                                               ELSE 0 END) AS VR_ICMS,
                                         0 AS VR_RED,'' AS COD_OB, IP.CDIMPOSTONFE
                                    FROM ITEMVENDA IV, ITVENDAIMPOS IVI, IMPOSTO IP
                                   WHERE IV.CDFILIAL     = IVI.CDFILIAL
                                     AND IV.CDCAIXA      = IVI.CDCAIXA
                                     AND IV.NRSEQUITVEND = IVI.NRSEQUITVEND
                                     AND IV.NRSEQVENDA   = IVI.NRSEQVENDA
                                     AND IV.CDFILIAL     = C_REGC350.CDFILIAL
                                     AND IV.CDCAIXA      =  C_REGC350.CDCAIXA
                                     AND IV.NRSEQVENDA   = C_REGC350.NRLANCTONF
                                     AND NVL(P_GERAFORSALE,'N') = 'S'
                                     AND IP.CDIMPOSTO    = IVI.CDIMPOSTO
                                   GROUP BY IVI.CDCSTPRODI, IVI.CDCSTPRODPC, IP.IDTPIMPOSFIS, IVI.VRPEALPRODIT, IP.CDIMPOSTONFE)NF
                           WHERE NF.CDIMPOSTONFE = P_CDIMPOSTO) LOOP
            INSERT INTO ARQMAGNETICO
              (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
              ('24'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC390.ARQ_C390, P_NRSEQARQMAG);
            V_CONTREGC := NVL(V_CONTREGC,0) + 1;
         END LOOP;
      END LOOP;
   END IF;
 
   /* registro c400 */
   FOR C_REGC400 IN (SELECT '|C400'            || '|' ||
                            '2D'               || '|' ||
                            'M'                || '|' ||  --DSMODMARCAECF
                            NRSERIEREDZ1       || '|' ||
                            CDCAIXA            || '|'   AS C400,
                            CDCAIXA, NRSERIEREDZ 
                       FROM (SELECT SUBSTR(NRSERIEREDZ,1,21) AS NRSERIEREDZ1,
                                    SUBSTR(REPLACE('','|','-'),1,20) AS DSMODMARCAECF, --DSMODMARCAECF
                                    CDCAIXA, RZ.NRSERIEREDZ
                               FROM REDUCAOZ RZ ,FILIAL FI
                              WHERE RZ.DTREDUCAOZ BETWEEN P_DTINICIAL AND P_DTFINAL 
                                AND RZ.CDFILIAL    = FI.CDFILIAL 
                                AND FI.CDEMPRESA   = P_CDEMPRESA 
                                AND FI.CDINSCESTA  = P_CDINSCESTA 
                                AND NRSERIEREDZ IS NOT NULL
                                AND RZ.IDSTATUS    = 'A'
                                AND ((V_CDSITUCRT = '3') OR (V_CDSITUCRT <> '3' AND V_SGESTADO <> 'CE'))
                              GROUP BY SUBSTR(NRSERIEREDZ,1,20), SUBSTR(REPLACE('','|','-'),1,20) , --DSMODMARCAECF
                                       CDCAIXA, RZ.NRSERIEREDZ) )LOOP 
      INSERT INTO ARQMAGNETICO 
        (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
      VALUES 
        ('25'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC400.C400, P_NRSEQARQMAG); 
      V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
      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')                                    || '|' || 
                                CASE WHEN RZ.DTREDUCAOZ < '01/01/2014' THEN LPAD(LTRIM(NVL(RZ.NRULTCFREDZ,'0'),'0'), 6, '0') ELSE LPAD(LTRIM(NVL(RZ.NRULTCFREDZ,'0'),'0'), 9, '0') END || '|' || --atualizacao do layout para 2014
                                REPLACE(LTRIM(TO_CHAR(TRUNC(RZ.VRGTREDZ,2), '999999999990.00')), '.', ',')        || '|' || 
                                REPLACE(LTRIM(TO_CHAR(TRUNC(DECODE(RZ.VRVENLIQREDZ,0,RZ.VRVENBRUREDZ,RZ.VRVENLIQREDZ),2), '999999999990.00')), '.', ',')    || '|' ) AS C405, 
                                DTREDUCAOZ, RZ.NRECFREDZ, RZ.CDFILIAL 
                          FROM REDUCAOZ RZ, FILIAL FI 
                         WHERE RZ.CDFILIAL    = FI.CDFILIAL 
                           AND RZ.DTREDUCAOZ BETWEEN P_DTINICIAL AND P_DTFINAL 
                           AND FI.CDEMPRESA   = P_CDEMPRESA 
                           AND FI.CDINSCESTA  = P_CDINSCESTA 
                           AND RZ.CDCAIXA     = C_REGC400.CDCAIXA 
                           AND RZ.NRSERIEREDZ = C_REGC400.NRSERIEREDZ
                           AND RZ.IDSTATUS    = 'A' 
                           AND VRVENBRUREDZ   > 0 
                         ORDER BY TO_CHAR(RZ.DTREDUCAOZ,'ddmmyyyy')) LOOP
         INSERT INTO ARQMAGNETICO 
           (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
         VALUES 
           ('25'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC405.C405, P_NRSEQARQMAG); 
         V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
         FOR C_420 IN (SELECT ('|C420'          || '|' || 
                                 VRALIQIMPRZ    || '|' || 
                                 VRBCALCIMPRZ   || '|' ) AS PARTE1, 
                                 VRALIQIMPRZ, 
                                 ALIQ_NR_TOT, 
                                 DTREDUCAOZ, CDFILIAL 
                            FROM (SELECT IDTPIMPOSFIS||LPAD(REPLACE(REPLACE(LTRIM(TO_CHAR(ROUND(VRALIQIMPRZ,2), '99.00')), '.', ','),',',''), 4, '0') AS VRALIQIMPRZ, 
                                         REPLACE(LTRIM(TO_CHAR(TRUNC(SUM(R.VRBCALCIMPRZ),2), '999999999990.00')), '.', ',') AS VRBCALCIMPRZ, 
                                         R.DTREDUCAOZ, VRALIQIMPRZ AS ALIQ_NR_TOT, FI.CDFILIAL, VRVENBRUREDZ, VRTOTCANREDZ 
                                    FROM IMPOSTOREDZ R, IMPOSTO I, FILIAL FI, REDUCAOZ Z 
                                   WHERE R.CDCAIXA      = C_REGC400.CDCAIXA
                                     AND R.DTREDUCAOZ   = C_REGC405.DTREDUCAOZ
                                     AND R.CDIMPOSTO    = I.CDIMPOSTO
                                     AND I.IDTPIMPOSFIS = 'T'
                                     AND FI.CDEMPRESA   = P_CDEMPRESA
                                     AND FI.CDINSCESTA  = P_CDINSCESTA
                                     AND FI.CDFILIAL    = R.CDFILIAL
                                     AND R.CDCAIXA      = Z.CDCAIXA
                                     AND R.NRECFREDZ    = Z.NRECFREDZ
                                     AND R.DTREDUCAOZ   = Z.DTREDUCAOZ
                                     AND R.CDFILIAL     = Z.CDFILIAL
                                     AND Z.NRECFREDZ    = C_REGC405.NRECFREDZ
                                     AND Z.NRSERIEREDZ  = C_REGC400.NRSERIEREDZ
                                    GROUP BY R.DTREDUCAOZ, IDTPIMPOSFIS||LPAD(REPLACE(REPLACE(LTRIM(TO_CHAR(ROUND(VRALIQIMPRZ,2), '99.00')), '.', ','),',',''), 4, '0'), 
                                             VRALIQIMPRZ, FI.CDFILIAL, VRVENBRUREDZ, VRTOTCANREDZ 
                                   UNION ALL 
                                  SELECT 'F1' AS VRALIQIMPRZ, 
                                         REPLACE(LTRIM(TO_CHAR(TRUNC(SUM(VRSTRIBREDZ),2), '999999999990.00')), '.', ',') AS VRBCALCIMPRZ, /* VALOR DE SUBSTITUICAO TRIBUTARIA */
                                         RE.DTREDUCAOZ, 0 AS ALIQ_NR_TOT, FI.CDFILIAL, VRVENBRUREDZ, VRTOTCANREDZ 
                                    FROM REDUCAOZ RE, FILIAL FI 
                                   WHERE RE.CDCAIXA     = C_REGC400.CDCAIXA 
                                     AND RE.DTREDUCAOZ  = C_REGC405.DTREDUCAOZ 
                                     AND RE.VRSTRIBREDZ > 0
                                     AND FI.CDEMPRESA   = P_CDEMPRESA
                                     AND FI.CDINSCESTA  = P_CDINSCESTA
                                     AND FI.CDFILIAL    = RE.CDFILIAL
                                     AND RE.NRECFREDZ   = C_REGC405.NRECFREDZ
                                     AND RE.NRSERIEREDZ = C_REGC400.NRSERIEREDZ
                                   GROUP BY RE.DTREDUCAOZ, FI.CDFILIAL, VRVENBRUREDZ, VRTOTCANREDZ 
                                   UNION ALL 
                                  SELECT DECODE(VRVENBRUREDZ,VRTOTCANREDZ ,'CAN-O','N1') AS VRALIQIMPRZ, 
                                         REPLACE(LTRIM(TO_CHAR(TRUNC(SUM(VRNINCIDREDZ),2), '999999999990.00')), '.', ',') AS VRBCALCIMPRZ, /* VALOR DE NAO TRIBUTADAS */
                                         RE.DTREDUCAOZ, 0 AS ALIQ_NR_TOT, FI.CDFILIAL, VRVENBRUREDZ, VRTOTCANREDZ 
                                    FROM REDUCAOZ RE, FILIAL FI
                                   WHERE RE.CDCAIXA      = C_REGC400.CDCAIXA
                                     AND RE.DTREDUCAOZ   = C_REGC405.DTREDUCAOZ
                                     AND RE.VRNINCIDREDZ > 0
                                     AND FI.CDEMPRESA    = P_CDEMPRESA
                                     AND FI.CDINSCESTA   = P_CDINSCESTA
                                     AND FI.CDFILIAL     = RE.CDFILIAL
                                     AND RE.NRECFREDZ    = C_REGC405.NRECFREDZ
                                     AND RE.NRSERIEREDZ  = C_REGC400.NRSERIEREDZ
                                   GROUP BY RE.DTREDUCAOZ, FI.CDFILIAL, VRVENBRUREDZ, VRTOTCANREDZ 
                                   UNION ALL 
                                  SELECT 'I1' AS VRALIQIMPRZ, 
                                         REPLACE(LTRIM(TO_CHAR(TRUNC(SUM(VRISENCREDZ),2), '999999999990.00')), '.', ',') AS VRBCALCIMPRZ, /* VALOR DE ISENTO */
                                         RE.DTREDUCAOZ, 0 AS ALIQ_NR_TOT, FI.CDFILIAL, VRVENBRUREDZ, VRTOTCANREDZ 
                                    FROM REDUCAOZ RE, FILIAL FI 
                                   WHERE RE.CDCAIXA     = C_REGC400.CDCAIXA
                                     AND RE.DTREDUCAOZ  = C_REGC405.DTREDUCAOZ
                                     AND RE.VRISENCREDZ > 0
                                     AND FI.CDEMPRESA   = P_CDEMPRESA
                                     AND FI.CDINSCESTA  = P_CDINSCESTA
                                     AND FI.CDFILIAL    = RE.CDFILIAL
                                     AND RE.NRECFREDZ   = C_REGC405.NRECFREDZ
                                     AND RE.NRSERIEREDZ = C_REGC400.NRSERIEREDZ
                                   GROUP BY RE.DTREDUCAOZ, FI.CDFILIAL, VRVENBRUREDZ, VRTOTCANREDZ)) LOOP 
               FOR C_NR_TOT IN (SELECT VRALIQIMPRZ, LPAD(TO_CHAR(ROWNUM), 2, '0') AS SEQUENCIAL 
                                  FROM (SELECT VRALIQIMPRZ 
                                          FROM IMPOSTOREDZ 
                                         WHERE DTREDUCAOZ BETWEEN P_DTINICIAL AND P_DTFINAL 
                                         GROUP BY VRALIQIMPRZ) )LOOP 
                  IF (C_NR_TOT.VRALIQIMPRZ = C_420.ALIQ_NR_TOT) AND (C_420.ALIQ_NR_TOT > 0) THEN 
                     V_NR_TOT := C_NR_TOT.SEQUENCIAL; 
                     V_DESCR_NR_TOT := 'ALIQUOTA ' || V_NR_TOT; 
                  END IF; 
               END LOOP; 
               V_LINHA := C_420.PARTE1      || 
                          V_NR_TOT          || '|' || 
                          V_DESCR_NR_TOT    || '|'; 
                V_NR_TOT       := NULL; 
                V_DESCR_NR_TOT := NULL; 
               INSERT INTO ARQMAGNETICO 
                 (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
               VALUES
                 ('25'||LPAD(RTRIM(V_CONTREGC), 8, '0'), V_LINHA, P_NRSEQARQMAG);
               V_CONTREGC := NVL(V_CONTREGC,0) + 1;
            IF P_PERFIL = 'B' THEN
               FOR C_425 IN (SELECT DISTINCT('|C425'|| '|' ||
                                    CDARVPROD       || '|' ||
                                    QTPRODVEND      || '|' ||
                                    SGUNIDADE       || '|' ||
                                    VRITEM          || '|' || 
                                    VRPIS           || '|' ||
                                    VRCOFINS        || '|'  ) AS C425, 
                                    CDPRODUTO, 
                                    SGUNIDADE AS UNID, CDCLASFISC
                               FROM (SELECT P.CDARVPROD, 
                                            REPLACE(LTRIM(TO_CHAR(SUM(QTPRODVEND), '999999999990.000')), '.', ',')  AS QTPRODVEND, 
                                            SGUNIDADE,
                                            REPLACE(LTRIM(TO_CHAR(ROUND(SUM(VRTOTAL),2), '999999999990.00')), '.', ',')  AS VRITEM, 
                                            '0,00' AS VRPIS, 
                                            '0,00' AS VRCOFINS,
                                            P.CDPRODUTO, I.CDCLASFISC
                                       FROM PRODUTO P, 
                                            (SELECT DISTINCT R.DTREDUCAOZ
                                              FROM REDUCAOZ R, IMPOSTOREDZ IR, IMPOSTO I 
                                             WHERE R.DTREDUCAOZ  = C_420.DTREDUCAOZ 
                                               AND R.CDCAIXA = C_REGC400.CDCAIXA
                                               AND R.CDFILIAL = IR.CDFILIAL 
                                               AND R.CDCAIXA = IR.CDCAIXA 
                                               AND R.NRECFREDZ = IR.NRECFREDZ
                                               AND R.DTREDUCAOZ = IR.DTREDUCAOZ 
                                               AND R.CDFILIAL = C_420.CDFILIAL 
                                               AND I.CDIMPOSTO = IR.CDIMPOSTO) R,
                                            (SELECT V.CDFILIAL, V.CDCAIXA, V.NRSEQVENDA, IT.CDPRODUTO, V.DTENTRVENDA, 
                                                    NVL(IT.VRUNITVEND,0) AS VRUNITVEND, 
                                                    NVL(IT.QTPRODVEND,0) AS QTPRODVEND,
                                                    (TRUNC(QTPRODVEND * (IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0)),2) - VRDESITVEND + VRACRITVEND) AS VRTOTAL,
                                                    IT.CDCLASFISC
                                               FROM ITVENDAIMPOS I, IMPOSTO P, ITEMVENDA IT, VENDA V
                                              WHERE I.CDIMPOSTO = P.CDIMPOSTO 
                                                AND I.CDFILIAL = IT.CDFILIAL 
                                                AND I.CDCAIXA = IT.CDCAIXA
                                                AND I.NRSEQVENDA = IT.NRSEQVENDA 
                                                AND I.NRSEQUITVEND = IT.NRSEQUITVEND
                                                AND I.CDFILIAL = V.CDFILIAL
                                                AND I.CDCAIXA = V.CDCAIXA
                                                AND V.CDCAIXA = C_REGC400.CDCAIXA
                                                AND I.NRSEQVENDA = V.NRSEQVENDA
                                                AND DTENTRVENDA = C_420.DTREDUCAOZ
                                                AND IDSITUVENDA = 'O'
                                                AND V.NRCUPOMFIS IS NOT NULL
                                                AND C_420.VRALIQIMPRZ = IDTPIMPOSFIS||LPAD(REPLACE(REPLACE(LTRIM(TO_CHAR(ROUND(VRPEALPRODIT,2), '99.00')), '.', ','),',',''), 4,'0')
                                                AND V.CDFILIAL = C_420.CDFILIAL
                                                AND IDTPIMPOSFIS = 'T'
                                              UNION ALL
                                              SELECT V.CDFILIAL, V.CDCAIXA, V.NRSEQVENDA, IT.CDPRODUTO, V.DTENTRVENDA,
                                                    NVL(IT.VRUNITVEND,0) AS VRUNITVEND,
                                                    NVL(IT.QTPRODVEND,0) AS QTPRODVEND,
                                                    (TRUNC(QTPRODVEND * (IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0)),2) - VRDESITVEND + VRACRITVEND) AS VRTOTAL,
                                                    IT.CDCLASFISC
                                               FROM ITVENDAIMPOS I, IMPOSTO P, ITEMVENDA IT, VENDA V
                                              WHERE I.CDIMPOSTO = P.CDIMPOSTO
                                                AND I.CDFILIAL = IT.CDFILIAL
                                                AND I.CDCAIXA = IT.CDCAIXA
                                                AND I.NRSEQVENDA = IT.NRSEQVENDA
                                                AND I.NRSEQUITVEND = IT.NRSEQUITVEND
                                                AND I.CDFILIAL = V.CDFILIAL
                                                AND I.CDCAIXA = V.CDCAIXA
                                                AND V.CDCAIXA = C_REGC400.CDCAIXA
                                                AND I.NRSEQVENDA = V.NRSEQVENDA
                                                AND DTENTRVENDA = C_420.DTREDUCAOZ
                                                AND V.NRCUPOMFIS IS NOT NULL
                                                AND IDSITUVENDA = 'O'
                                                AND C_420.VRALIQIMPRZ = IDTPIMPOSFIS||'1'
                                                AND V.CDFILIAL = C_420.CDFILIAL
                                                AND IDTPIMPOSFIS <> 'T'   ) I
                                      WHERE R.DTREDUCAOZ(+) = I.DTENTRVENDA
                                        AND P.CDPRODUTO     = I.CDPRODUTO
                                     GROUP BY P.CDARVPROD, SGUNIDADE, P.CDPRODUTO, I.CDCLASFISC)) LOOP
                  INSERT INTO ARQMAGNETICO 
                    (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
                  VALUES 
                    ('25'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_425.C425, P_NRSEQARQMAG); 
                  V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
                  /* UNIDADE DE MEDIDA */
                  SELECT MAX(CDCHAVEREG) 
                    INTO V_UNID 
                    FROM TMP_REGDADOSSPED 
                   WHERE CDCHAVEREG = C_425.UNID 
                     AND CDREGISTRO = '0190'; 
                  IF (V_UNID IS NULL) AND (C_425.UNID IS NOT NULL) THEN 
                     V_SEQUPROD := NVL(V_SEQUPROD,0) + 1; 
                     INSERT INTO TMP_REGDADOSSPED 
                       (CDREGISTRO, CDCONTREGI, CDCHAVEREG) 
                     VALUES 
                       ('0190', V_SEQUPROD, C_425.UNID); 
                  END IF; 
                  V_UNID := NULL; 
                  /* CODIGO DO PRODUTO */
                  SELECT MAX(CDCHAVEREG) 
                    INTO V_PRODUTO 
                    FROM TMP_REGDADOSSPED 
                   WHERE CDCHAVEREG = C_425.CDPRODUTO 
                     AND CDREGISTRO = '0200';
                  IF (V_PRODUTO IS NULL) AND (C_425.CDPRODUTO IS NOT NULL) THEN 
                     V_SEQUPROD := NVL(V_SEQUPROD,0) + 1; 
                     INSERT INTO TMP_REGDADOSSPED 
                       (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
                     VALUES 
                       ('0200', V_SEQUPROD, C_425.CDPRODUTO, C_425.CDCLASFISC);
                  END IF; 
                  V_PRODUTO := NULL; 
               END LOOP; 
            END IF; 
         END LOOP; 
 
         FOR C_C460 IN (SELECT (REG      || '|' || 
                               COD_MOD   || '|' || 
                               COD_SIT   || '|' || 
                               NUM_DOC   || '|' || 
                               DT_DOC    || '|' || 
                               VL_DOC    || '|' || 
                               VL_PIS    || '|' || 
                               VL_COFINS || '|' || 
                               CPF_CNPJ  || '|' || 
                               NOM_ADQ   || '|' )AS REG_C460, 
                               CDCAIXA, CDFILIAL, DTREDUCAOZ ,NRSERIEREDZ , NRCUPOMFIS 
                          FROM (SELECT '|C460' AS REG, 
                                       '2D' AS COD_MOD, 
                                       '00' AS COD_SIT, 
                                       CASE WHEN V.DTENTRVENDA < '01/01/2014' THEN LPAD(LTRIM(NVL(V.NRCUPOMFIS,'0'),'0'), 6, '0') ELSE LPAD(LTRIM(NVL(V.NRCUPOMFIS,'0'),'0'), 9, '0') END AS NUM_DOC, --atualizacao do layout para 2014
                                       TO_CHAR(V.DTENTRVENDA, 'DDMMYYYY') AS DT_DOC, 
                                       REPLACE(LTRIM(TO_CHAR(SUM(TRUNC(IV.QTPRODVEND * (IV.VRUNITVEND+NVL(IV.VRUNITVENDCL,0)),2) - NVL(IV.VRDESITVEND,0) + NVL(IV.VRACRITVEND,0)),'999999999990.00')),'.',',') AS VL_DOC, 
                                       0 AS VL_PIS, 
                                       0 AS VL_COFINS, 
                                       NVL(REPLACE(REPLACE(REPLACE(REPLACE(V.NRINSCRCONS,'.'),'-'),'/'),' '),'') AS CPF_CNPJ, 
                                       '' AS NOM_ADQ, V.NRCUPOMFIS, IV.CDCAIXA, V.CDFILIAL, V.DTENTRVENDA AS DTREDUCAOZ, V.NRSERIEIMPVND AS NRSERIEREDZ 
                                  FROM ITEMVENDA IV, ITVENDAIMPOS IVI, VENDA V, IMPOSTO IP 
                                 WHERE IV.CDFILIAL = IVI.CDFILIAL 
                                   AND IV.CDCAIXA  = IVI.CDCAIXA 
                                   AND IV.NRSEQUITVEND = IVI.NRSEQUITVEND 
                                   AND IV.NRSEQVENDA  = IVI.NRSEQVENDA 
                                   AND IV.CDFILIAL    = V.CDFILIAL 
                                   AND IV.CDCAIXA     = V.CDCAIXA 
                                   AND IV.NRSEQVENDA  = V.NRSEQVENDA 
                                   AND IV.CDFILIAL    = C_REGC405.CDFILIAL 
                                   AND IV.CDCAIXA     = C_REGC400.CDCAIXA 
                                   AND V.DTENTRVENDA  = C_REGC405.DTREDUCAOZ 
                                   AND V.IDSITUVENDA  = 'O' 
			                          AND P_PERFIL = 'A' 
                                   AND V.NRCUPOMFIS IS NOT NULL
                                   --AND NVL(P_GERAFORSALE,'N') = 'S'
                                   AND IP.CDIMPOSTO = IVI.CDIMPOSTO
                                 GROUP BY V.NRCUPOMFIS, DTENTRVENDA, V.NRSERIEIMPVND, IV.CDCAIXA, V.CDFILIAL, V.NRINSCRCONS))LOOP
               INSERT INTO ARQMAGNETICO
                 (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                 ('25'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_C460.REG_C460, P_NRSEQARQMAG);
               V_CONTREGC := NVL(V_CONTREGC,0) + 1;
            FOR C_470 IN (SELECT REG        || '|' ||
                                 COD_ITEM   || '|' ||
                                 QTD        || '|' ||
                                 QTD_CANC   || '|' ||
                                 UNID       || '|' || 
                                 VL_ITEM    || '|' || 
                                 CST_ICMS   || '|' || 
                                 CFOP       || '|' ||
                                 ALIQ_ICMS  || '|' || 
                                 VL_PIS     || '|' || 
                                 VL_COFINS  || '|' AS REG_C470,
                                 CDPRODUTO, UNID, CDCLASFISC
                            FROM (SELECT '|C470' AS REG, 
                                         CDARVPROD AS COD_ITEM, 
                                         REPLACE(LTRIM(TO_CHAR(QTPRODVEND, '999999999990.000')), '.', ',') AS QTD,
                                         '0' AS QTD_CANC,
                                         SGUNIDADE AS UNID,
                                         REPLACE(LTRIM(TO_CHAR(TRUNC(VRTOTAL,2), '999999999990.00')), '.', ',') AS VL_ITEM, 
                                         NVL(LPAD(CDCSTPRODI,3,'0'),DECODE(IDTPIMPOSFIS,'F','060','I','040','N','041','T',CASE WHEN VRPERCREDUCAO > 0 THEN '020' ELSE '000' END)) AS CST_ICMS,
                                         NVL(CDCFOPPROD,DECODE(IDTPIMPOSFIS,'F','5405','5102')) AS CFOP,
                                         REPLACE(LTRIM(TO_CHAR(TRUNC(VRPEALPRODIT,2), '999999999990.00')), '.', ',') AS ALIQ_ICMS, 
                                         '0' AS VL_PIS, 
                                         '0' AS VL_COFINS, 
                                         P.CDPRODUTO, I.CDCLASFISC AS CDCLASFISC
                                    FROM PRODUTO P, 
                                        (SELECT DISTINCT R.DTREDUCAOZ 
                                           FROM REDUCAOZ R, IMPOSTOREDZ IR, IMPOSTO I 
                                          WHERE R.DTREDUCAOZ  = C_C460.DTREDUCAOZ
                                            AND R.CDCAIXA     = C_C460.CDCAIXA
                                            AND R.CDFILIAL    = IR.CDFILIAL
                                            AND R.CDCAIXA     = IR.CDCAIXA
                                            AND R.NRECFREDZ   = IR.NRECFREDZ
                                            AND R.DTREDUCAOZ  = IR.DTREDUCAOZ
                                            AND R.CDFILIAL    = C_C460.CDFILIAL
                                            AND R.NRSERIEREDZ = C_C460.NRSERIEREDZ
                                            AND R.NRECFREDZ   = C_REGC405.NRECFREDZ
                                            AND P_PERFIL      = 'A'
                                            AND R.NRECFREDZ   = C_REGC405.NRECFREDZ
                                            AND I.CDIMPOSTO   = IR.CDIMPOSTO) R,
                                         (SELECT V.CDFILIAL, V.CDCAIXA, V.NRSEQVENDA, IT.CDPRODUTO, V.DTENTRVENDA,
                                                 NVL(IT.VRUNITVEND,0) AS VRUNITVEND,
                                                 NVL(IT.QTPRODVEND,0) AS QTPRODVEND, 
                                                 TRUNC(IT.QTPRODVEND * (IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0)),2) - IT.VRDESITVEND + IT.VRACRITVEND AS VRTOTAL,
                                                 I.VRPEALPRODIT, P.IDTPIMPOSFIS, NVL(A.VRPERCREDUCAO,0) AS VRPERCREDUCAO, IT.CDCLASFISC, I.CDCFOPPROD, I.CDCSTPRODI
                                            FROM ITVENDAIMPOS I, IMPOSTO P, ITEMVENDA IT, VENDA V, ALIQIMPFIS A
                                           WHERE I.CDIMPOSTO    = P.CDIMPOSTO
                                             AND I.CDFILIAL     = IT.CDFILIAL
                                             AND I.CDCAIXA      = IT.CDCAIXA
                                             AND I.NRSEQVENDA   = IT.NRSEQVENDA
                                             AND I.NRSEQUITVEND = IT.NRSEQUITVEND
                                             AND I.CDFILIAL     = V.CDFILIAL
                                             AND I.CDCAIXA      = V.CDCAIXA
                                             AND V.CDCAIXA      = C_C460.CDCAIXA
                                             AND V.NRCUPOMFIS   = C_C460.NRCUPOMFIS
                                             AND I.NRSEQVENDA   = V.NRSEQVENDA
                                             AND V.DTENTRVENDA  = C_C460.DTREDUCAOZ
                                             AND V.NRCUPOMFIS   IS NOT NULL
                                             AND V.IDSITUVENDA  = 'O'
                                             AND IT.CDFILIAL    = A.CDFILIAL(+)
                                             AND IT.CDPRODUTO   = A.CDPRODUTO(+)
                                             --AND V.NRORDEMVND IS NULL
                                             AND NVL(NRSERIEIMPVND,NRSERIEVND) = C_C460.NRSERIEREDZ/*REDUÇÃO PELA IMPRESSORA*/
                                             --AND C_420.VRALIQIMPRZ = IDTPIMPOSFIS||LPAD(REPLACE(REPLACE(LTRIM(TO_CHAR(ROUND(VRPEALPRODIT,2), '99.00')), '.', ','),',',''), 4, '0')
                                             AND V.CDFILIAL = C_C460.CDFILIAL
                                             AND P_PERFIL = 'A'
                                             /*AND IDTPIMPOSFIS = 'T'*/)I
                                           /*
                                           UNION ALL
                                           SELECT V.CDFILIAL, V.CDCAIXA, V.NRSEQVENDA, IT.CDPRODUTO, V.DTENTRVENDA,
                                                 NVL(IT.VRUNITVEND,0) AS VRUNITVEND,
                                                 NVL(IT.QTPRODVEND,0) AS QTPRODVEND,
                                                 (TRUNC(QTPRODVEND * (VRUNITVEND+NVL(IV.VRUNITVENDCL,0)),2) - VRDESITVEND + VRACRITVEND) AS VRTOTAL,
                                                 VRPEALPRODIT, IT.CDCLASFISC
                                            FROM ITVENDAIMPOS I, IMPOSTO P, ITEMVENDA IT, VENDA V
                                           WHERE I.CDIMPOSTO = P.CDIMPOSTO
                                             AND I.CDFILIAL = IT.CDFILIAL
                                             AND I.CDCAIXA = IT.CDCAIXA
                                             AND I.NRSEQVENDA = IT.NRSEQVENDA
                                             AND I.NRSEQUITVEND = IT.NRSEQUITVEND
                                             AND I.CDFILIAL = V.CDFILIAL
                                             AND I.CDCAIXA = V.CDCAIXA
                                             AND V.CDCAIXA = C_C460.CDCAIXA
                                             AND I.NRSEQVENDA = V.NRSEQVENDA
                                             AND DTENTRVENDA = C_C460.DTREDUCAOZ
                                             AND IDSITUVENDA = 'O'
                                             --AND C_420.VRALIQIMPRZ = IDTPIMPOSFIS||'1'
                                             AND V.CDFILIAL = C_C460.CDFILIAL
                                             AND P_PERFIL = 'A'
                                             AND IDTPIMPOSFIS <> 'T'
                                             */
                                   WHERE R.DTREDUCAOZ(+) = I.DTENTRVENDA
                                     AND P.CDPRODUTO     = I.CDPRODUTO
                                   --GROUP BY CDARVPROD, SGUNIDADE, REPLACE(LTRIM(TO_CHAR(TRUNC(VRPEALPRODIT,2), '999999999990.00')), '.', ','),
                                            --P.CDPRODUTO, IDTPIMPOSFIS, CDCLASFISC
                                   ))LOOP
 
               INSERT INTO ARQMAGNETICO 
                 (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
               VALUES 
                 ('25'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_470.REG_C470, P_NRSEQARQMAG); 
               V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
 
               SELECT MAX(CDCHAVEREG) 
                 INTO V_UNID 
                 FROM TMP_REGDADOSSPED 
                WHERE CDCHAVEREG = C_470.UNID 
                  AND CDREGISTRO = '0190'; 
 
               IF (V_UNID IS NULL) AND (C_470.UNID IS NOT NULL) THEN 
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1; 
                  INSERT INTO TMP_REGDADOSSPED 
                    (CDREGISTRO, CDCONTREGI, CDCHAVEREG) 
                  VALUES 
                    ('0190', V_SEQUPROD, C_470.UNID); 
               END IF; 
 
               V_UNID := NULL; 
               SELECT MAX(CDCHAVEREG) 
                 INTO V_PRODUTO 
                 FROM TMP_REGDADOSSPED 
                WHERE CDCHAVEREG = C_470.CDPRODUTO 
                  AND CDREGISTRO = '0200'; 
 
               IF (V_PRODUTO IS NULL) AND (C_470.CDPRODUTO IS NOT NULL) THEN 
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1; 
                  INSERT INTO TMP_REGDADOSSPED 
                    (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
                  VALUES 
                    ('0200', V_SEQUPROD, C_470.CDPRODUTO, C_470.CDCLASFISC); 
               END IF; 
               V_PRODUTO := NULL; 
 
            END LOOP; 
         END LOOP; 
    /*VERIFICA O TOTAL DA VENDA BRUTA E O TOTAL DE CANCELAMENTOS*/
      SELECT VRVENBRUREDZ, VRTOTCANREDZ 
        INTO V_VENDABRUTA, V_VENDACANC 
        FROM REDUCAOZ 
       WHERE DTREDUCAOZ  = C_REGC405.DTREDUCAOZ 
         AND CDCAIXA     = C_REGC400.CDCAIXA 
         AND NRECFREDZ   = C_REGC405.NRECFREDZ 
         AND CDFILIAL    = C_REGC405.CDFILIAL 
         AND NRSERIEREDZ = C_REGC400.NRSERIEREDZ; 
 
       IF V_VENDABRUTA <> V_VENDACANC  THEN /*VERIFICA SE TODAS AS VENDAS FORAM CANCELADAS PARA GERAR O REGISTRO C490*/
 
         FOR C_490 IN (SELECT '|C490'     || '|' ||
                                 CST_ICMS    || '|' ||
                                 CFOP        || '|' ||
                                 REPLACE(LTRIM(TO_CHAR(ROUND(ALIQ_ICMS,2), '999999999990.00')), '.', ',')      || '|' ||
                                 REPLACE(LTRIM(TO_CHAR(TRUNC(VL_OPR,2), '999999999990.00')), '.', ',')|| '|' ||
                                 REPLACE(LTRIM(TO_CHAR(TRUNC(VL_BC_ICMS,2), '999999999990.00')), '.', ',')|| '|' ||
                                 REPLACE(LTRIM(TO_CHAR(TRUNC(VL_ICMS,2), '999999999990.00')), '.', ',')|| '|' ||
                                 COD_OBS     || '|' AS C490
                         FROM (SELECT '000' AS CST_ICMS,
                                      '5102' AS CFOP,
                                      VRALIQIMPRZ AS ALIQ_ICMS,
                                      SUM(VRBCALCIMPRZ) AS VL_OPR,
                                      SUM(VRBCALCIMPRZ) AS VL_BC_ICMS,
                                      SUM(VRIMPOSTORZ) AS VL_ICMS,
                                      '' COD_OBS
                                 FROM IMPOSTOREDZ R, FILIAL FI, REDUCAOZ Z, IMPOSTO IM
                                WHERE R.DTREDUCAOZ    = C_REGC405.DTREDUCAOZ
                                  AND R.CDCAIXA       = C_REGC400.CDCAIXA
                                  AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                  AND R.CDIMPOSTO     = IM.CDIMPOSTO
                                  AND FI.CDEMPRESA    = P_CDEMPRESA
                                  AND FI.CDINSCESTA   = P_CDINSCESTA
                                  AND FI.CDFILIAL     = R.CDFILIAL
                                  AND R.CDFILIAL      = Z.CDFILIAL
                                  AND R.CDCAIXA       = Z.CDCAIXA
                                  AND R.NRECFREDZ     = Z.NRECFREDZ
                                  AND R.DTREDUCAOZ    = Z.DTREDUCAOZ
                                  AND Z.NRECFREDZ     = C_REGC405.NRECFREDZ
                                  AND Z.NRSERIEREDZ   = C_REGC400.NRSERIEREDZ
                                  AND Z.NRLANCTONF    IS NULL
                                GROUP BY R.VRALIQIMPRZ
                                UNION ALL
                               SELECT '0'||SUBSTR(NVL(LPAD(IP.CDSITUTRIBNF,3,'0'),DECODE(IP.VRPERREDBCNF,0,'000','020')),2,2) AS CST_ICMS,
                                      NVL(IP.CDFISCOPERNF,'5102') AS CFOP,
                                      R.VRALIQIMPRZ AS ALIQ_ICMS,
                                      SUM(IP.VRCONTABILNF) + NVL(SUM(DECODE(IP.VRPERREDBCNF,0,0,(SELECT SUM(VRCONTABILNF)
                                                                                                   FROM IMPOSTONF II
                                                                                                  WHERE II.CDFILIAL    = IP.CDFILIAL
                                                                                                    AND II.NRLANCTONF  = IP.NRLANCTONF
                                                                                                    AND II.IDIMPOSTONF = '2'))),0) AS VL_OPR,
                                      SUM(IP.VRBASECALCNF) AS VL_BC_ICMS,
                                      SUM(IP.VRIMPOSTONF)  AS VL_ICMS,
                                      '' COD_OBS
                                 FROM IMPOSTOREDZ R, IMPOSTONF IP, FILIAL FI, REDUCAOZ Z, IMPOSTO IM, IMPOSTO I
                                WHERE R.DTREDUCAOZ    = C_REGC405.DTREDUCAOZ
                                  AND R.CDCAIXA       = C_REGC400.CDCAIXA
                                  AND Z.CDFILIALNF    = IP.CDFILIAL
                                  AND Z.NRLANCTONF    = IP.NRLANCTONF
                                  AND R.VRALIQIMPRZ   = IP.VRALIQNF
                                  AND IP.CDIMPOSTO    = I.CDIMPOSTO
                                  AND I.CDIMPOSTONFE  IN ('00','03')
                                  AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                  AND R.CDIMPOSTO     = IM.CDIMPOSTO
                                  AND FI.CDEMPRESA    = P_CDEMPRESA
                                  AND FI.CDINSCESTA   = P_CDINSCESTA
                                  AND FI.CDFILIAL     = R.CDFILIAL
                                  AND R.CDFILIAL      = Z.CDFILIAL
                                  AND R.CDCAIXA       = Z.CDCAIXA
                                  AND R.NRECFREDZ     = Z.NRECFREDZ
                                  AND R.DTREDUCAOZ    = Z.DTREDUCAOZ
                                  AND Z.NRECFREDZ     = C_REGC405.NRECFREDZ
                                  AND Z.NRSERIEREDZ   = C_REGC400.NRSERIEREDZ
                                  AND Z.NRLANCTONF    IS NOT NULL
                                GROUP BY R.VRALIQIMPRZ,  '0'||SUBSTR(NVL(LPAD(IP.CDSITUTRIBNF,3,'0'),DECODE(IP.VRPERREDBCNF,0,'000','020')),2,2), IP.CDFISCOPERNF
                                UNION ALL
                               SELECT '060'  AS CST_ICMS,
                                      '5405' AS CFOP,
                                      0      AS ALIQ_ICMS,
                                      SUM(VRSTRIBREDZ) AS VL_OPR, /* VALOR DE SUBSTITUICAO TRIBUTARIA */
                                      0 VL_BC_ICMS,
                                      0 VL_ICMS,
                                      '' COD_OBS
                                 FROM REDUCAOZ RE, FILIAL FI
                                WHERE RE.CDCAIXA     = C_REGC400.CDCAIXA
                                  AND RE.DTREDUCAOZ  = C_REGC405.DTREDUCAOZ
                                  AND VRSTRIBREDZ    > 0
                                  AND FI.CDEMPRESA   = P_CDEMPRESA
                                  AND FI.CDINSCESTA  = P_CDINSCESTA
                                  AND FI.CDFILIAL    = RE.CDFILIAL
                                  AND RE.NRECFREDZ   = C_REGC405.NRECFREDZ
                                  AND RE.NRSERIEREDZ = C_REGC400.NRSERIEREDZ
                                  AND RE.NRLANCTONF  IS NULL
                                GROUP BY '060', '5405'
                                UNION ALL
                               SELECT '040'  AS CST_ICMS,
                                      '5102' AS CFOP,
                                      0      AS ALIQ_ICMS,
                                      SUM(VRISENCREDZ) AS VL_OPR, /* VALOR DE ISENÇÃO */
                                      0 VL_BC_ICMS,
                                      0 VL_ICMS,
                                      '' COD_OBS
                                 FROM REDUCAOZ RE, FILIAL FI
                                WHERE RE.CDCAIXA     = C_REGC400.CDCAIXA
                                  AND RE.DTREDUCAOZ  = C_REGC405.DTREDUCAOZ
                                  AND VRISENCREDZ    > 0
                                  AND FI.CDEMPRESA   = P_CDEMPRESA
                                  AND FI.CDINSCESTA  = P_CDINSCESTA
                                  AND FI.CDFILIAL    = RE.CDFILIAL
                                  AND RE.NRECFREDZ   = C_REGC405.NRECFREDZ
                                  AND RE.NRSERIEREDZ = C_REGC400.NRSERIEREDZ
                                  AND RE.NRLANCTONF  IS NULL
                                GROUP BY '040', '5102'
                                UNION ALL
                               SELECT '041'  AS CST_ICMS,
                                      '5102' AS CFOP,
                                      0      AS ALIQ_ICMS,
                                      SUM(VRNINCIDREDZ) AS VL_OPR, /* VALOR DE NÃO INCIDENCIA */
                                      0 VL_BC_ICMS,
                                      0 VL_ICMS,
                                      '' COD_OBS
                                 FROM REDUCAOZ RE, FILIAL FI
                                WHERE RE.CDCAIXA     = C_REGC400.CDCAIXA
                                  AND RE.DTREDUCAOZ  = C_REGC405.DTREDUCAOZ
                                  AND VRNINCIDREDZ   > 0
                                  AND FI.CDEMPRESA   = P_CDEMPRESA
                                  AND FI.CDINSCESTA  = P_CDINSCESTA
                                  AND FI.CDFILIAL    = RE.CDFILIAL
                                  AND RE.NRECFREDZ   = C_REGC405.NRECFREDZ
                                  AND RE.NRSERIEREDZ = C_REGC400.NRSERIEREDZ
                                  AND RE.NRLANCTONF  IS NULL
                                GROUP BY '041', '5102'
								        UNION ALL
								       SELECT '0'||SUBSTR(NVL(LPAD(IP.CDSITUTRIBNF,3,'0'),DECODE(IP.VRPERREDBCNF,0,'000','020')),2,2) AS CST_ICMS,
                                      NVL(IP.CDFISCOPERNF,'5102') AS CFOP,
                                      0 AS ALIQ_ICMS,
                                      SUM(IP.VRCONTABILNF) AS VL_OPR,
                                      0 AS VL_BC_ICMS,
                                      0 AS VL_ICMS,
                                      '' COD_OBS
                                 FROM IMPOSTONF IP, FILIAL FI, REDUCAOZ Z, IMPOSTO IM
                                WHERE Z.DTREDUCAOZ    = C_REGC405.DTREDUCAOZ
                                  AND Z.CDCAIXA       = C_REGC400.CDCAIXA
                                  AND Z.CDFILIALNF    = IP.CDFILIAL
                                  AND Z.NRLANCTONF    = IP.NRLANCTONF
                                  AND IP.CDIMPOSTO    = IM.CDIMPOSTO
                                  AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                  AND FI.CDEMPRESA    = P_CDEMPRESA
                                  AND FI.CDINSCESTA   = P_CDINSCESTA
                                  AND FI.CDFILIAL     = Z.CDFILIAL
                                  AND Z.NRECFREDZ     = C_REGC405.NRECFREDZ
                                  AND Z.NRSERIEREDZ   = C_REGC400.NRSERIEREDZ
                                  AND IP.CDFISCALNF   <> '1'
                                  AND IP.IDIMPOSTONF  <> '2'
                                  AND Z.NRLANCTONF    IS NOT NULL
                                  AND NVL(IP.VRIMPCARGATRIBI,0) = 0
                                GROUP BY '0'||SUBSTR(NVL(LPAD(IP.CDSITUTRIBNF,3,'0'),DECODE(IP.VRPERREDBCNF,0,'000','020')),2,2), IP.CDFISCOPERNF)) LOOP
            INSERT INTO ARQMAGNETICO
              (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
              ('25'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_490.C490, P_NRSEQARQMAG);
            V_CONTREGC := NVL(V_CONTREGC,0) + 1;
         END LOOP;
       END IF;
      END LOOP;
   END LOOP;
   V_DADOS_2 := '';
   V_COD_PAR := '';

   IF V_CDSITUCRT = '3' THEN
      FOR C_500 IN (SELECT REG                 || '|' ||
                            IND_OPER            || '|' ||
                            IND_EMIT            || '|' ||
                            REPLACE(REPLACE(REPLACE(REPLACE(COD_PAR,'.'),'-'),'/'),' ') || '|' ||
                            COD_MOD             || '|' AS PART_1,
                            SER                 || '|' ||
                            SUB                 || '|' ||
                            COD_CONS            || '|' ||
                            NUM_DOC             || '|' ||
                            DT_DOC              || '|' ||
                            DT_E_S              || '|' ||
                            REPLACE(LTRIM(TO_CHAR(ROUND(VL_DOC,2), '999999999990.00')), '.', ',')    || '|' ||
                            VL_DESC             || '|' ||
                            REPLACE(LTRIM(TO_CHAR(ROUND(VL_FORN,2), '999999999990.00')), '.', ',')   || '|' ||
                            REPLACE(LTRIM(TO_CHAR(ROUND(VL_SERV_NT,2), '999999999990.00')), '.', ',')|| '|' ||
                            VL_TERC             || '|' ||
                            VL_DA               || '|' ||
                            REPLACE(LTRIM(TO_CHAR(ROUND(VL_BC_ICMS + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VRBASECARGA,0))),2), '999999999990.00')), '.', ',')|| '|' ||
                            REPLACE(LTRIM(TO_CHAR(ROUND(VL_ICMS    + DECODE(V_IDTPCARGATRIB,'O',0,NVL(DECODE(IDENTRSAIDOP,'S',VRIMPCARGA,DECODE(V_SGESTADO,'SP',0,VRIMPCARGA)),0)),2), '999999999990.00')), '.', ',')   || '|' ||
                            VL_BC_ICMS_ST       || '|' ||
                            VL_ICMS_ST          || '|' ||
                            COD_INF             || '|' ||
                            VL_PIS              || '|' ||
                            VL_COFINS           || '|' ||
                            TP_LIGACAO          || '|' ||
                            COD_GRUPO_TENSAO    || '|' AS PART_2,
                            IDSTATUS, DTEMISSAO, CDFILIAL, NRLANCTONF, COD_PAR,
                            IDENTRSAIDOP, IDORIGDESTNF, CDTIPOOPER, FILIAL
                       FROM (SELECT '|C500' AS REG,
                                    DECODE(N.IDENTRSAIDOP, 'E', '0','1')  AS IND_OPER,
                                    '1' AS IND_EMIT,
                                    N.IDORIGDESTNF||N.CDFORNECED AS COD_PAR,
                                    N.CDMODDOCFISC AS COD_MOD,
                                    NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS SER,
                                    '' AS SUB,
                                    '01' AS COD_CONS,
                                    LTRIM(N.NRNOTAFISC, '0') AS NUM_DOC,
                                    TO_CHAR(N.DTEMISSAO,'ddmmyyyy') AS DT_DOC,
                                    TO_CHAR(N.DTENTRSAID,'ddmmyyyy') AS DT_E_S,
                                    SUM(I.VRCONTABILNF) AS VL_DOC,
                                    '0,00' AS VL_DESC,
                                    SUM(I.VRCONTABILNF) AS VL_FORN,
                                    SUM(DECODE(CDFISCALNF, '2', VRCONTABILNF, 0)) AS VL_SERV_NT,
                                    '0,00' AS VL_TERC,
                                    '0,00' AS VL_DA,
                                    SUM(DECODE(CDFISCALNF, '1', VRBASECALCNF, 0)) AS VL_BC_ICMS,
                                    SUM((SELECT SUM(VRBASECALCNF)
                                           FROM IMPOSTONF IP
                                          WHERE IP.CDFILIAL   = I.CDFILIAL
                                            AND IP.NRLANCTONF = I.NRLANCTONF
                                            AND IP.CDIMPOSTO  = IM.CDIMPCARGATRIB)) AS VRBASECARGA,
                                    SUM(DECODE(CDFISCALNF, '1', VRIMPOSTONF, 0)) AS VL_ICMS,
                                    SUM(VRIMPCARGATRIBI) AS VRIMPCARGA,
                                    '0,00' AS VL_BC_ICMS_ST,
                                    '0,00' AS VL_ICMS_ST,
                                    '' AS COD_INF,
                                    '0,00' AS VL_PIS,
                                    '0,00' AS VL_COFINS,
                                    '1' AS TP_LIGACAO,
                                    '01' AS COD_GRUPO_TENSAO,
                                    N.IDSTATUS, N.DTENTRSAID AS DTEMISSAO, N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP,
                                    N.IDORIGDESTNF, N.CDTIPOOPER, N.CDFILIRECE AS FILIAL
                               FROM NOTAFISCAL N, IMPOSTONF I, FORNECEDOR F, IMPOSTO IM, SERIEENTR SE
                              WHERE I.NRSEQUMAPAPU    = V_NRSEQUMAPAPU
                                AND IM.CDIMPOSTONFE   = P_CDIMPOSTO
                                AND I.CDIMPOSTO       = IM.CDIMPOSTO
                                AND (NVL(N.IDSISTEMA,'DFS') <> 'REC'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS')
                                AND SE.CDSERIEENTR(+) = N.CDSERIEENTR
                                AND N.IDENTRSAIDOP    = 'E' 
                                AND NVL(I.IDIMPOSTONF, '1') <> '3' 
                                AND N.CDFILIAL        = I.CDFILIAL 
                                AND N.NRLANCTONF      = I.NRLANCTONF
                                AND ((N.IDSTATUS = 'A') OR (N.IDSTATUS = 'E')) 
                                AND N.CDMODDOCFISC IN ('06', '29','28') 
                                AND N.CDFORNECED   = F.CDFORNECED 
                                AND N.IDORIGDESTNF = 'F' 
                              GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), N.IDORIGDESTNF||N.CDFORNECED, N.CDMODDOCFISC,
                                    NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR), LTRIM(N.NRNOTAFISC, '0'), TO_CHAR(N.DTEMISSAO,'ddmmyyyy'),
                                    TO_CHAR(N.DTENTRSAID,'ddmmyyyy'), N.IDSTATUS, N.DTENTRSAID, N.CDFILIAL, N.NRLANCTONF,
                                    N.IDENTRSAIDOP, N.IDORIGDESTNF, N.CDTIPOOPER, N.CDFILIRECE
                             UNION ALL 
                             SELECT '|C500' AS REG, 
                                    DECODE(N.IDENTRSAIDOP, 'E', '0','1') AS IND_OPER, 
                                    '1' AS IND_EMIT,
                                    N.IDORIGDESTNF||N.CDCLIENTE AS COD_PAR,
                                    N.CDMODDOCFISC AS COD_MOD, 
                                    NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS SER, 
                                    '' AS SUB, 
                                    '01' AS COD_CONS, 
                                    LTRIM(N.NRNOTAFISC, '0') AS NUM_DOC,
                                    TO_CHAR(N.DTEMISSAO,'ddmmyyyy') AS DT_DOC,
                                    TO_CHAR(N.DTENTRSAID,'ddmmyyyy') AS DT_E_S,
                                    SUM(I.VRCONTABILNF) AS VL_DOC, 
                                    '0,00' AS VL_DESC, 
                                    SUM(I.VRCONTABILNF) AS VL_FORN, 
                                    SUM(DECODE(CDFISCALNF, '2', VRCONTABILNF, 0)) AS VL_SERV_NT,
                                    '0,00' AS VL_TERC, 
                                    '0,00' AS VL_DA, 
                                    SUM(DECODE(CDFISCALNF, '1', VRBASECALCNF, 0)) AS VL_BC_ICMS, 
                                    SUM((SELECT SUM(VRBASECALCNF) 
                                           FROM IMPOSTONF IP 
                                          WHERE IP.CDFILIAL   = I.CDFILIAL
                                            AND IP.NRLANCTONF = I.NRLANCTONF 
                                            AND IP.CDIMPOSTO  = IM.CDIMPCARGATRIB)) AS VRBASECARGA,
                                    SUM(DECODE(CDFISCALNF, '1', VRIMPOSTONF, 0)) AS VL_ICMS,
                                    SUM(VRIMPCARGATRIBI) AS VRIMPCARGA, 
                                    '0,00' AS VL_BC_ICMS_ST, 
                                    '0,00' AS VL_ICMS_ST,
                                    '' AS COD_INF, 
                                    '0,00' AS VL_PIS, 
                                    '0,00' AS VL_COFINS, 
                                    '1' AS TP_LIGACAO, 
                                    '01' AS COD_GRUPO_TENSAO, 
                                    N.IDSTATUS, N.DTENTRSAID AS DTEMISSAO, N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP,
                                    N.IDORIGDESTNF, N.CDTIPOOPER, N.CDFILIRECE AS FILIAL
                               FROM NOTAFISCAL N, IMPOSTONF I, CLIENTE C, IMPOSTO IM, SERIEENTR SE 
                              WHERE I.NRSEQUMAPAPU    = V_NRSEQUMAPAPU 
                                AND IM.CDIMPOSTONFE   = P_CDIMPOSTO 
                                AND I.CDIMPOSTO       = IM.CDIMPOSTO 
                                AND (NVL(N.IDSISTEMA,'DFS') <> 'REC'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS') 
                                AND SE.CDSERIEENTR(+) = N.CDSERIEENTR
                                AND N.IDENTRSAIDOP    = 'E' 
                                AND NVL(I.IDIMPOSTONF, '1') <> '3' 
                                AND N.CDFILIAL        = I.CDFILIAL 
                                AND N.NRLANCTONF      = I.NRLANCTONF 
                                AND ((N.IDSTATUS = 'A') OR (N.IDSTATUS = 'E')) 
                                AND N.CDMODDOCFISC IN ('06', '29','28')
                                AND N.CDCLIENTE = C.CDCLIENTE
                                AND N.IDORIGDESTNF = 'C' 
                              GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), N.IDORIGDESTNF||N.CDCLIENTE, N.CDMODDOCFISC,
                                    NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR), LTRIM(N.NRNOTAFISC, '0'), TO_CHAR(N.DTEMISSAO,'ddmmyyyy'),
                                    TO_CHAR(N.DTENTRSAID,'ddmmyyyy'), N.IDSTATUS, N.DTENTRSAID, N.CDFILIAL, N.NRLANCTONF,
                                    N.IDENTRSAIDOP, N.IDORIGDESTNF, N.CDTIPOOPER, N.CDFILIRECE
                             UNION ALL 
                             SELECT '|C500' AS REG, 
                                    DECODE(N.IDENTRSAIDOP, 'E', '0','1') AS IND_OPER, 
                                    '1' AS IND_EMIT, 
                                    N.IDORIGDESTNF||N.CDFILIEMIT AS COD_PAR,
                                    N.CDMODDOCFISC AS COD_MOD,
                                    NVL(SE.CDSERIE,N.CDSERIE) AS SER,
                                    '' AS SUB, 
                                    '01' AS COD_CONS, 
                                    LTRIM(N.NRNOTAFISC, '0') AS NUM_DOC, 
                                    TO_CHAR(N.DTEMISSAO,'ddmmyyyy') AS DT_DOC,
                                    TO_CHAR(N.DTENTRSAID,'ddmmyyyy') AS DT_E_S,
                                    SUM(I.VRCONTABILNF) AS VL_DOC, 
                                    '0,00' AS VL_DESC, 
                                    SUM(I.VRCONTABILNF) AS VL_FORN, 
                                    SUM(DECODE(CDFISCALNF, '2', VRCONTABILNF, 0)) AS VL_SERV_NT, 
                                    '0,00' AS VL_TERC, 
                                    '0,00' AS VL_DA,
                                    SUM(DECODE(CDFISCALNF, '1', VRBASECALCNF, 0)) AS VL_BC_ICMS, 
                                    SUM((SELECT SUM(VRBASECALCNF) 
                                           FROM IMPOSTONF IP 
                                          WHERE IP.CDFILIAL   = I.CDFILIAL 
                                            AND IP.NRLANCTONF = I.NRLANCTONF 
                                            AND IP.CDIMPOSTO  = IM.CDIMPCARGATRIB)) AS VRBASECARGA,
                                    SUM(DECODE(CDFISCALNF, '1', VRIMPOSTONF, 0)) AS VL_ICMS, 
                                    SUM(VRIMPCARGATRIBI) AS VRIMPCARGA, 
                                    '0,00' AS VL_BC_ICMS_ST, 
                                    '0,00' AS VL_ICMS_ST, 
                                    '' AS COD_INF, 
                                    '0,00' AS VL_PIS,
                                    '0,00' AS VL_COFINS, 
                                    '1' AS TP_LIGACAO, 
                                    '01' AS COD_GRUPO_TENSAO, 
                                    N.IDSTATUS, N.DTEMISSAO, N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP,
                                    N.IDORIGDESTNF, N.CDTIPOOPER, N.CDFILIEMIT AS FILIAL
                               FROM NOTAFISCAL N, IMPOSTONF I, FILIAL F, IMPOSTO IM, SERIENF SE
                              WHERE I.NRSEQUMAPAPU    = V_NRSEQUMAPAPU 
                                AND IM.CDIMPOSTO      = P_CDIMPOSTO 
                                AND IM.CDIMPOSTO      = IM.CDIMPOSTO
                                AND (NVL(N.IDSISTEMA,'DFS') <> 'REC' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP'
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS')
                                AND SE.CDEMPRESA(+)   = N.CDEMPRESA
                                AND SE.CDINSCESTA(+)  = N.CDINSCESTA
                                AND SE.CDINSCMUNI(+)  = N.CDINSCMUNI
                                AND SE.CDSERIE(+)     = N.CDSERIE
                                AND N.IDENTRSAIDOP    = 'S'
                                AND NVL(I.IDIMPOSTONF, '1') <> '3' 
                                AND N.CDFILIAL        = I.CDFILIAL 
                                AND N.NRLANCTONF      = I.NRLANCTONF 
                                AND ((N.IDSTATUS = 'A') OR (N.IDSTATUS = 'E'))
                                AND N.CDMODDOCFISC IN ('06', '29','28') 
                                AND N.CDFILIEMIT = F.CDFILIAL 
                                AND IDORIGDESTNF = 'L' 
                              GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), N.IDORIGDESTNF||N.CDFILIEMIT, N.CDMODDOCFISC,
                                    NVL(SE.CDSERIE,N.CDSERIE), LTRIM(N.NRNOTAFISC, '0'), TO_CHAR(N.DTEMISSAO,'ddmmyyyy'),
                                    TO_CHAR(N.DTENTRSAID,'ddmmyyyy'), N.IDSTATUS, N.DTEMISSAO, N.CDFILIAL, N.NRLANCTONF,
                                    N.IDENTRSAIDOP, N.IDORIGDESTNF, N.CDTIPOOPER, N.CDFILIEMIT)) LOOP
          /* CODIDO DO PARTICIPANTE */
          SELECT MAX(CDCHAVEREG)
            INTO V_COD_PAR
            FROM TMP_REGDADOSSPED
           WHERE CDCHAVEREG = C_500.COD_PAR
             AND CDREGISTRO = '0150';
 
          IF (V_COD_PAR IS NULL) AND (C_500.COD_PAR IS NOT NULL) THEN
             V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
             INSERT INTO TMP_REGDADOSSPED
               (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
             VALUES 
               ('0150', V_SEQUPROD, C_500.COD_PAR);
          END IF;

          V_COD_PAR := '';
          IF C_500.IDSTATUS = 'C' THEN
             /* documentos cancelados */
             V_DADOS_2 := '02|';
          ELSE
             IF NOT C_500.DTEMISSAO BETWEEN P_DTINICIAL AND P_DTFINAL THEN 
                /* documentos fora do periodo */
                V_DADOS_2 := '01|';
             ELSE
                V_DADOS_2 := '00|';
             END IF;
          END IF; 
          INSERT INTO ARQMAGNETICO 
            (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
          VALUES 
            ('25'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_500.PART_1||V_DADOS_2||C_500.PART_2, P_NRSEQARQMAG); 
          V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
          V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0'); 
          FOR C_510 IN (SELECT COD_ITEM         || '|' || 
                               COD_CLASS        || '|' || 
                               QTD              || '|' || 
                               UNID             || '|' || 
                               REPLACE(LTRIM(TO_CHAR(ROUND(VL_ITEM,2), '999999999990.00')), '.', ',')    || '|' || 
                               VL_DESC          || '|' || 
                               CST_ICMS         || '|' || 
                               CFOP             || '|' || 
                               REPLACE(LTRIM(TO_CHAR(ROUND(VL_BC_ICMS + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VRBASECARGA,0))),2), '999999999990.00')), '.', ',') || '|' || 
                               REPLACE(LTRIM(TO_CHAR(ROUND(ALIQ_ICMS,2), '999999999990.00')), '.', ',')  || '|' || 
                               REPLACE(LTRIM(TO_CHAR(ROUND(VL_ICMS    + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(C_500.IDENTRSAIDOP,'E',DECODE(V_SGESTADO,'SP',0,NVL(VRIMPCARGA,0)),NVL(VRIMPCARGA,0))),2), '999999999990.00')), '.', ',')    || '|' ||
                               VL_BC_ICMS_ST    || '|' ||
                               ALIQ_ST          || '|' ||
                               VL_ICMS_ST       || '|' ||
                               IND_REC          || '|' ||
                               COD_PART         || '|' ||
                               VL_PIS           || '|' ||
                               VL_COFINS        || '|' ||
                               COD_CTA          || '|' AS REGC510,
                               CDPRODUTO, UNID, CDCLASFISC, COD_CTA
                         FROM (SELECT CDARVPROD AS COD_ITEM,
                                      '0601' AS COD_CLASS,
                                      QTITEMPROD AS QTD,
                                      SGUNIDADE AS UNID,
                                      VRUNITITEM AS VL_ITEM,
                                      '0,00' AS VL_DESC,
                                      CDSITUTRIBIT AS CST_ICMS,
                                      CDFISCOPERIT AS CFOP,
                                      DECODE(CDFISCALIT, '1', VRBASECALCIT, 0) AS VL_BC_ICMS,
                                      (SELECT SUM(IT.VRBASECALCIT)
                                         FROM ITEMPROIMPOS IP
                                        WHERE IP.CDFILIAL   = IT.CDFILIAL
                                          AND IP.NRLANCTONF = IT.NRLANCTONF
                                          AND IP.CDIMPOSTO  = IM.CDIMPCARGATRIB) AS VRBASECARGA,
                                      DECODE(CDFISCALIT, '1', VRALIQITEM, 0) AS ALIQ_ICMS,
                                      DECODE(CDFISCALIT, '1', VRIMPOSTOIT, 0) AS VL_ICMS,
                                      (SELECT SUM(IT.VRIMPOSTOIT)
                                         FROM ITEMPROIMPOS IP
                                        WHERE IP.CDFILIAL   = IT.CDFILIAL
                                          AND IP.NRLANCTONF = IT.NRLANCTONF
                                          AND IP.CDIMPOSTO  = IM.CDIMPCARGATRIB) AS VRIMPCARGA,
                                      '0,00' AS VL_BC_ICMS_ST,
                                      '0,00' AS ALIQ_ST,
                                      '0,00' AS VL_ICMS_ST,
                                      '1' AS IND_REC,
                                      '' AS COD_PART,
                                      '0,00' AS VL_PIS,
                                      '0,00' AS VL_COFINS,
                                      CONTCTBL_SPED(C_500.IDENTRSAIDOP, I.CDPRODUTO, C_500.CDTIPOOPER, C_500.FILIAL) AS COD_CTA,
                                      P.CDPRODUTO,
                                      I.CDPRODNCMTRANS AS CDCLASFISC
                                 FROM ITEMPRODUTO I, ITEMPROIMPOS IT, PRODUTO P, IMPOSTO IM
                                WHERE I.CDFILIAL = C_500.CDFILIAL 
                                  AND I.NRLANCTONF = C_500.NRLANCTONF 
                                  AND I.CDFILIAL = IT.CDFILIAL 
                                  AND I.NRLANCTONF = IT.NRLANCTONF 
                                  AND I.NRSEQITPROD = IT.NRSEQITPROD 
                                  AND SUBSTR(IT.CDFISCOPERIT,1,1) IN ('5','6','7') 
                                  AND P.CDPRODUTO = I.CDPRODUTO 
                                  AND IM.CDIMPOSTO = IT.CDIMPOSTO) ) LOOP

            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('25'||LPAD(RTRIM(V_CONTREGC), 8, '0'), '|C510|'||V_SEQUENCIAL||'|'||C_510.REGC510, P_NRSEQARQMAG);
            V_CONTREGC := NVL(V_CONTREGC,0) + 1;
            V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER(RTRIM(V_SEQUENCIAL))+1)), 3,'0');

            /* CODIGO DO PRODUTO */
            SELECT MAX(CDCHAVEREG)
              INTO V_PRODUTO
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_510.CDPRODUTO
               AND CDREGISTRO = '0200';
            IF V_PRODUTO IS NULL AND (C_510.CDPRODUTO IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
               VALUES
                  ('0200', V_SEQUPROD, C_510.CDPRODUTO, C_510.CDCLASFISC);
            END IF;
            V_PRODUTO := '';

            /* UNIDADE DE MEDIDA */
            SELECT MAX(CDCHAVEREG)
              INTO V_UNID
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_510.UNID
               AND CDREGISTRO = '0190';
            IF (V_UNID IS NULL) AND (C_510.UNID IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
               VALUES
                  ('0190', V_SEQUPROD, C_510.UNID);
            END IF;
            V_UNID := '';

            /* PLANO DE CONTAS REFERENCIAL */
            SELECT MAX(CDCHAVEREG)
              INTO V_CONTCTBL
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_510.COD_CTA
               AND CDREGISTRO = '0500';

            IF (V_CONTCTBL IS NULL) AND (C_510.COD_CTA IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
               VALUES
                  ('0500', V_SEQUPROD, C_510.COD_CTA);
            END IF;
            V_CONTCTBL := '';
          END LOOP;

          FOR C_590 IN(SELECT ('|C590'      || '|' || 
                               T.CST_ICMS   || '|' || 
                               T.CFOP       || '|' || 
                               REPLACE(LTRIM(TO_CHAR(ROUND(T.ALIQ_ICMS,2), '999999999990.00')), '.', ',')      || '|' || 
                               REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_OPR,2), '999999999990.00')), '.', ',')      || '|' || 
                               REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_BC_ICMS + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VRBASECARGA,0))),2), '999999999990.00')), '.', ',')      || '|' || 
                               REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_ICMS    + DECODE(V_IDTPCARGATRIB,'O',0,NVL(DECODE(C_500.IDENTRSAIDOP,'E',DECODE(V_SGESTADO,'SP',0,VRIMPCARGA),VRIMPCARGA),0)),2), '999999999990.00')), '.', ',')      || '|' || 
                               REPLACE(LTRIM(TO_CHAR(ROUND(0,2), '999999999990.00')), '.', ',')      || '|' || 
                               REPLACE(LTRIM(TO_CHAR(ROUND(0,2), '999999999990.00')), '.', ',')      || '|' || 
                               REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_RED_BC,2), '999999999990.00')), '.', ',')      || '|' || 
                               '' || '|') ARQ_C590 
                       FROM (SELECT CDSITUTRIBIT AS CST_ICMS, 
                                    CDFISCOPERIT AS CFOP, 
                                    DECODE(CDFISCALIT, '1', VRALIQITEM, 0) AS ALIQ_ICMS, 
                                    SUM(VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL)),0) VL_OPR, 
                                    SUM(DECODE(CDFISCALIT, '1', VRBASECALCIT, 0)) AS VL_BC_ICMS, 
                                    SUM((SELECT SUM(IP.VRBASECALCIT) 
                                           FROM ITEMPROIMPOS IP 
                                          WHERE IP.CDFILIAL     = I.CDFILIAL
                                            AND IP.NRLANCTONF   = I.NRLANCTONF
                                            AND IP.CDSITUTRIBIT = I.CDSITUTRIBIT 
                                            AND IP.CDFISCOPERIT = I.CDFISCOPERIT 
                                            AND IP.CDIMPOSTO    = IM.CDIMPCARGATRIB)) AS VRBASECARGA,
                                    SUM(DECODE(CDFISCALIT, '1', VRIMPOSTOIT, 0)) AS VL_ICMS, 
                                    SUM((SELECT SUM(IP.VRIMPOSTOIT) 
                                           FROM ITEMPROIMPOS IP 
                                          WHERE IP.CDFILIAL     = I.CDFILIAL
                                            AND IP.NRLANCTONF   = I.NRLANCTONF
                                            AND IP.CDSITUTRIBIT = I.CDSITUTRIBIT 
                                            AND IP.CDFISCOPERIT = I.CDFISCOPERIT 
                                            AND IP.CDIMPOSTO    = IM.CDIMPCARGATRIB)) AS VRIMPCARGA, 
                                    0 AS VL_BC_ICMS_ST, 
                                    0 AS VL_ICMS_ST, 
                                    NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL) ),0) AS VL_RED_BC, 
                                    0 AS VL_IPI, 
                                    '' AS COD_OBS 
                               FROM ITEMPROIMPOS I, IMPOSTO IM 
                              WHERE I.CDFILIAL      = C_500.CDFILIAL 
                                AND I.NRLANCTONF    = C_500.NRLANCTONF 
                                AND I.NRITPROIMPOS    = '1' 
                                AND IM.CDIMPOSTO    = I.CDIMPOSTO 
                                AND IM.CDIMPOSTONFE = P_CDIMPOSTO 
                              GROUP BY CDSITUTRIBIT, I.CDFISCOPERIT, DECODE(I.CDFISCALIT, '1', I.VRALIQITEM, 0) ) T ) LOOP 
             INSERT INTO ARQMAGNETICO 
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
             VALUES 
               ('25'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_590.ARQ_C590, P_NRSEQARQMAG); 
             V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
          END LOOP; 
       END LOOP; 
   END IF; 
 
   IF V_CDSITUCRT <> '3' THEN   /*SIMPLES NACIONAL*/
       FOR C_500 IN (SELECT REG                 || '|' ||
                            IND_OPER            || '|' || 
                            IND_EMIT            || '|' ||
                            REPLACE(REPLACE(REPLACE(REPLACE(COD_PAR,'.'),'-'),'/'),' ') || '|' || 
                            COD_MOD             || '|' AS PART_1,
                            SER                 || '|' ||
                            SUB                 || '|' || 
                            COD_CONS            || '|' || 
                            NUM_DOC             || '|' || 
                            DT_DOC              || '|' || 
                            DT_E_S              || '|' || 
                            REPLACE(LTRIM(TO_CHAR(ROUND(VL_DOC,2), '999999999990.00')), '.', ',')    || '|' || 
                            VL_DESC             || '|' || 
                            REPLACE(LTRIM(TO_CHAR(ROUND(VL_FORN,2), '999999999990.00')), '.', ',')   || '|' || 
                            REPLACE(LTRIM(TO_CHAR(ROUND(VL_SERV_NT,2), '999999999990.00')), '.', ',')|| '|' || 
                            VL_TERC             || '|' || 
                            VL_DA               || '|' || 
                            REPLACE(LTRIM(TO_CHAR(ROUND(VL_BC_ICMS + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VRBASECARGA,0))),2), '999999999990.00')), '.', ',')|| '|' || 
                            REPLACE(LTRIM(TO_CHAR(ROUND(VL_ICMS    + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(IDENTRSAIDOP,'S',NVL(VRIMPCARGA,0),DECODE(V_SGESTADO,'SP',0,NVL(VRIMPCARGA,0)))),2), '999999999990.00')), '.', ',')   || '|' || 
                            VL_BC_ICMS_ST       || '|' || 
                            VL_ICMS_ST          || '|' || 
                            COD_INF             || '|' || 
                            VL_PIS              || '|' || 
                            VL_COFINS           || '|' || 
                            TP_LIGACAO          || '|' || 
                            COD_GRUPO_TENSAO    || '|' AS PART_2, 
                            IDSTATUS, DTEMISSAO, CDFILIAL, NRLANCTONF, COD_PAR, IDENTRSAIDOP,
                            IDORIGDESTNF, CDTIPOOPER, FILIAL
                       FROM (SELECT '|C500' AS REG,
                                    DECODE(N.IDENTRSAIDOP, 'E', '0','1')  AS IND_OPER,
                                    '1' AS IND_EMIT,
                                    N.IDORIGDESTNF||N.CDFORNECED AS COD_PAR,
                                    N.CDMODDOCFISC AS COD_MOD,
                                    NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS SER,
                                    '' AS SUB,
                                    '01' AS COD_CONS,
                                    LTRIM(N.NRNOTAFISC, '0') AS NUM_DOC,
                                    TO_CHAR(N.DTEMISSAO,'ddmmyyyy') AS DT_DOC,
                                    TO_CHAR(N.DTENTRSAID,'ddmmyyyy') AS DT_E_S,
                                    SUM(I.VRCONTABILNF) AS VL_DOC,
                                    '0,00' AS VL_DESC,
                                    SUM(I.VRCONTABILNF) AS VL_FORN,
                                    SUM(DECODE(CDFISCALNF, '2', VRCONTABILNF, 0)) AS VL_SERV_NT,
                                    '0,00' AS VL_TERC,
                                    '0,00' AS VL_DA,
                                    SUM(DECODE(CDFISCALNF, '1', VRBASECALCNF, 0)) AS VL_BC_ICMS,
                                    SUM((SELECT SUM(VRBASECALCNF)
                                           FROM IMPOSTONF IP
                                          WHERE IP.CDFILIAL   = I.CDFILIAL
                                            AND IP.NRLANCTONF = I.NRLANCTONF
                                            AND IP.CDIMPOSTO  = IM.CDIMPCARGATRIB)) AS VRBASECARGA,
                                    SUM(DECODE(CDFISCALNF, '1', VRIMPOSTONF, 0)) AS VL_ICMS,
                                    SUM(VRIMPCARGATRIBI) AS VRIMPCARGA,
                                    '0,00' AS VL_BC_ICMS_ST,
                                    '0,00' AS VL_ICMS_ST,
                                    '' AS COD_INF,
                                    '0,00' AS VL_PIS,
                                    '0,00' AS VL_COFINS,
                                    '1' AS TP_LIGACAO,
                                    '01' AS COD_GRUPO_TENSAO,
                                    N.IDSTATUS, N.DTEMISSAO, N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP,
                                    N.IDORIGDESTNF, N.CDTIPOOPER, N.CDFILIRECE AS FILIAL
                               FROM NOTAFISCAL N, IMPOSTONF I, FORNECEDOR F, IMPOSTO IM, SERIEENTR SE
                              WHERE N.NRSEQUMAPAPUSN  = V_NRSEQUMAPAPU
                                AND N.CDINSCESTA      = P_CDINSCESTA
                                AND IM.CDIMPOSTONFE   = P_CDIMPOSTO 
                                AND I.CDIMPOSTO       = IM.CDIMPOSTO 
                                AND (NVL(N.IDSISTEMA,'DFS') <> 'REC' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS') 
                                AND SE.CDSERIEENTR(+)    = N.CDSERIEENTR 
                                AND N.IDENTRSAIDOP    = 'E' 
                                AND NVL(I.IDIMPOSTONF, '1') <> '3'
                                AND N.CDFILIAL        = I.CDFILIAL 
                                AND N.NRLANCTONF      = I.NRLANCTONF 
                                AND ((N.IDSTATUS = 'A') OR (N.IDSTATUS = 'E')) 
                                AND N.CDMODDOCFISC IN ('06', '29','28') 
                                AND N.CDFORNECED   = F.CDFORNECED 
                                AND N.IDORIGDESTNF = 'F' 
                              GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), N.IDORIGDESTNF||N.CDFORNECED, N.CDMODDOCFISC,
                                    NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR), LTRIM(N.NRNOTAFISC, '0'), TO_CHAR(N.DTEMISSAO,'ddmmyyyy'),
                                    TO_CHAR(N.DTENTRSAID,'ddmmyyyy'), N.IDSTATUS, N.DTEMISSAO, N.CDFILIAL, N.NRLANCTONF,
                                    N.IDENTRSAIDOP, N.IDORIGDESTNF, N.CDTIPOOPER, N.CDFILIRECE
                              UNION ALL
                              SELECT '|C500' AS REG, 
                                    DECODE(N.IDENTRSAIDOP, 'E', '0','1') AS IND_OPER, 
                                    '1' AS IND_EMIT, 
                                    N.IDORIGDESTNF||N.CDCLIENTE AS COD_PAR,
                                    N.CDMODDOCFISC AS COD_MOD, 
                                    NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS SER, 
                                    '' AS SUB, 
                                    '01' AS COD_CONS, 
                                    LTRIM(N.NRNOTAFISC, '0') AS NUM_DOC, 
                                    TO_CHAR(N.DTEMISSAO,'ddmmyyyy') AS DT_DOC,
                                    TO_CHAR(N.DTENTRSAID,'ddmmyyyy') AS DT_E_S,
                                    SUM(I.VRCONTABILNF) AS VL_DOC, 
                                    '0,00' AS VL_DESC, 
                                    SUM(I.VRCONTABILNF) AS VL_FORN, 
                                    SUM(DECODE(CDFISCALNF, '2', VRCONTABILNF, 0)) AS VL_SERV_NT, 
                                    '0,00' AS VL_TERC, 
                                    '0,00' AS VL_DA, 
                                    SUM(DECODE(CDFISCALNF, '1', VRBASECALCNF, 0)) AS VL_BC_ICMS, 
                                    SUM((SELECT SUM(VRBASECALCNF) 
                                           FROM IMPOSTONF IP 
                                          WHERE IP.CDFILIAL   = I.CDFILIAL 
                                            AND IP.NRLANCTONF = I.NRLANCTONF 
                                            AND IP.CDIMPOSTO  = IM.CDIMPCARGATRIB)) AS VRBASECARGA,
                                    SUM(DECODE(CDFISCALNF, '1', VRIMPOSTONF, 0)) AS VL_ICMS, 
                                    SUM(VRIMPCARGATRIBI) AS VRIMPCARGA, 
                                    '0,00' AS VL_BC_ICMS_ST, 
                                    '0,00' AS VL_ICMS_ST,
                                    '' AS COD_INF, 
                                    '0,00' AS VL_PIS, 
                                    '0,00' AS VL_COFINS, 
                                    '1' AS TP_LIGACAO, 
                                    '01' AS COD_GRUPO_TENSAO, 
                                    N.IDSTATUS, N.DTEMISSAO, N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP,
                                    N.IDORIGDESTNF, N.CDTIPOOPER, N.CDFILIRECE AS FILIAL
                               FROM NOTAFISCAL N, IMPOSTONF I, CLIENTE C, IMPOSTO IM, SERIEENTR SE 
                              WHERE N.NRSEQUMAPAPUSN  = V_NRSEQUMAPAPU 
                                AND N.CDINSCESTA      = P_CDINSCESTA 
                                AND IM.CDIMPOSTONFE   = P_CDIMPOSTO 
                                AND I.CDIMPOSTO       = IM.CDIMPOSTO 
                                AND (NVL(N.IDSISTEMA,'DFS') <> 'REC' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS') 
                                AND SE.CDSERIEENTR(+)    = N.CDSERIEENTR 
                                AND N.IDENTRSAIDOP    = 'E'
                                AND NVL(I.IDIMPOSTONF, '1') <> '3' 
                                AND N.CDFILIAL        = I.CDFILIAL 
                                AND N.NRLANCTONF      = I.NRLANCTONF 
                                AND ((N.IDSTATUS = 'A') OR (N.IDSTATUS = 'E')) 
                                AND N.CDMODDOCFISC IN ('06', '29','28') 
                                AND N.CDCLIENTE = C.CDCLIENTE 
                                AND N.IDORIGDESTNF = 'C' 
                              GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), N.IDORIGDESTNF||N.CDCLIENTE, N.CDMODDOCFISC,
                                    NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR), LTRIM(N.NRNOTAFISC, '0'), TO_CHAR(N.DTEMISSAO,'ddmmyyyy'),
                                    TO_CHAR(N.DTENTRSAID,'ddmmyyyy'), N.IDSTATUS, N.DTEMISSAO, N.CDFILIAL, N.NRLANCTONF,
                                    N.IDENTRSAIDOP, N.IDORIGDESTNF, N.CDTIPOOPER, N.CDFILIRECE
                              UNION ALL 
                             SELECT '|C500' AS REG, 
                                    DECODE(N.IDENTRSAIDOP, 'E', '0','1') AS IND_OPER, 
                                    '1' AS IND_EMIT, 
                                    N.IDORIGDESTNF||N.CDFILIEMIT AS COD_PAR,
                                    N.CDMODDOCFISC AS COD_MOD, 
                                    NVL(SE.CDSERIE,N.CDSERIE) AS SER,
                                    '' AS SUB, 
                                    '01' AS COD_CONS, 
                                    LTRIM(N.NRNOTAFISC, '0') AS NUM_DOC, 
                                    TO_CHAR(N.DTEMISSAO,'ddmmyyyy') AS DT_DOC,
                                    TO_CHAR(N.DTENTRSAID,'ddmmyyyy') AS DT_E_S,
                                    SUM(I.VRCONTABILNF) AS VL_DOC, 
                                    '0,00' AS VL_DESC, 
                                    SUM(I.VRCONTABILNF) AS VL_FORN, 
                                    SUM(DECODE(CDFISCALNF, '2', VRCONTABILNF, 0)) AS VL_SERV_NT, 
                                    '0,00' AS VL_TERC, 
                                    '0,00' AS VL_DA, 
                                    SUM(DECODE(CDFISCALNF, '1', VRBASECALCNF, 0)) AS VL_BC_ICMS, 
                                    SUM((SELECT SUM(VRBASECALCNF) 
                                           FROM IMPOSTONF IP 
                                          WHERE IP.CDFILIAL   = I.CDFILIAL
                                            AND IP.NRLANCTONF = I.NRLANCTONF 
                                            AND IP.CDIMPOSTO  = IM.CDIMPCARGATRIB)) AS VRBASECARGA,
                                    SUM(DECODE(CDFISCALNF, '1', VRIMPOSTONF, 0)) AS VL_ICMS, 
                                    SUM(VRIMPCARGATRIBI) AS VRIMPCARGA, 
                                    '0,00' AS VL_BC_ICMS_ST, 
                                    '0,00' AS VL_ICMS_ST, 
                                    '' AS COD_INF, 
                                    '0,00' AS VL_PIS, 
                                    '0,00' AS VL_COFINS, 
                                    '1' AS TP_LIGACAO, 
                                    '01' AS COD_GRUPO_TENSAO, 
                                    N.IDSTATUS, N.DTEMISSAO, N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP,
                                    N.IDORIGDESTNF, N.CDTIPOOPER, N.CDFILIEMIT AS FILIAL
                               FROM NOTAFISCAL N, IMPOSTONF I, FILIAL F, IMPOSTO IM, SERIENF SE
                              WHERE N.NRSEQUMAPAPUSN  = V_NRSEQUMAPAPU 
                                AND N.CDINSCESTA      = P_CDINSCESTA 
                                AND IM.CDIMPOSTO      = P_CDIMPOSTO 
                                AND IM.CDIMPOSTO      = IM.CDIMPOSTO 
                                AND (NVL(N.IDSISTEMA,'DFS') <> 'REC' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP' 
                                AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS')
                                AND SE.CDEMPRESA(+)   = N.CDEMPRESA
                                AND SE.CDINSCESTA(+)  = N.CDINSCESTA
                                AND SE.CDINSCMUNI(+)  = N.CDINSCMUNI
                                AND SE.CDSERIE(+)     = N.CDSERIE
                                AND N.IDENTRSAIDOP    = 'S'
                                AND NVL(I.IDIMPOSTONF, '1') <> '3'
                                AND N.CDFILIAL        = I.CDFILIAL 
                                AND N.NRLANCTONF      = I.NRLANCTONF 
                                AND ((N.IDSTATUS = 'A') OR (N.IDSTATUS = 'E')) 
                                AND N.CDMODDOCFISC IN ('06', '29','28') 
                                AND N.CDFILIEMIT = F.CDFILIAL
                                AND IDORIGDESTNF = 'L' 
                              GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), N.IDORIGDESTNF||N.CDFILIEMIT, N.CDMODDOCFISC, NVL(SE.CDSERIE,N.CDSERIE),
                                    LTRIM(N.NRNOTAFISC, '0'), TO_CHAR(N.DTEMISSAO,'ddmmyyyy'), TO_CHAR(N.DTENTRSAID,'ddmmyyyy'),
                                    N.IDSTATUS, N.DTEMISSAO, N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP,
                                    N.IDORIGDESTNF, N.CDTIPOOPER, N.CDFILIEMIT)) LOOP

         /* CODIGO DO PARTICIPANTE */
         SELECT MAX(CDCHAVEREG)
           INTO V_COD_PAR
           FROM TMP_REGDADOSSPED
          WHERE CDCHAVEREG = C_500.COD_PAR
            AND CDREGISTRO = '0150';

         IF (V_COD_PAR IS NULL) AND (C_500.COD_PAR IS NOT NULL) THEN
            V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
            INSERT INTO TMP_REGDADOSSPED
              (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
            VALUES
              ('0150', V_SEQUPROD, C_500.COD_PAR);
         END IF;

         V_COD_PAR := '';
         IF C_500.IDSTATUS = 'C' THEN
            /* documentos cancelados */
            V_DADOS_2 := '02|';
         ELSE
            IF NOT C_500.DTEMISSAO BETWEEN P_DTINICIAL AND P_DTFINAL THEN
               /* documentos fora do periodo */
               V_DADOS_2 := '01|';
            ELSE
               V_DADOS_2 := '00|';
            END IF;
         END IF;

         INSERT INTO ARQMAGNETICO
            (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
            ('25'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_500.PART_1||V_DADOS_2||C_500.PART_2, P_NRSEQARQMAG);
         V_CONTREGC := NVL(V_CONTREGC,0) + 1;
         V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');
 
         FOR C_510 IN (SELECT COD_ITEM         || '|' ||
                              COD_CLASS        || '|' ||
                              QTD              || '|' ||
                              UNID             || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(VL_ITEM,2), '999999999990.00')), '.', ',')    || '|' ||
                              VL_DESC          || '|' ||
                              CST_ICMS         || '|' ||
                              CFOP             || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(VL_BC_ICMS + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VRBASECARGA,0))),2), '999999999990.00')), '.', ',') || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(ALIQ_ICMS,2), '999999999990.00')), '.', ',')  || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(VL_ICMS    + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(C_500.IDENTRSAIDOP,'S',NVL(VRIMPCARGA,0),DECODE(V_SGESTADO,'SP',0,NVL(VRIMPCARGA,0)))),2), '999999999990.00')), '.', ',')    || '|' ||
                              VL_BC_ICMS_ST    || '|' ||
                              ALIQ_ST          || '|' ||
                              VL_ICMS_ST       || '|' ||
                              IND_REC          || '|' ||
                              COD_PART         || '|' ||
                              VL_PIS           || '|' ||
                              VL_COFINS        || '|' ||
                              COD_CTA          || '|' AS REGC510,
                              CDPRODUTO, UNID, CDCLASFISC, COD_CTA
                         FROM (SELECT CDARVPROD AS COD_ITEM,
                                      '0601' AS COD_CLASS,
                                      QTITEMPROD AS QTD,
                                      SGUNIDADE AS UNID,
                                      VRUNITITEM AS VL_ITEM,
                                      '0,00' AS VL_DESC,
                                      CDSITUTRIBIT AS CST_ICMS,
                                      CDFISCOPERIT AS CFOP,
                                      DECODE(CDFISCALIT, '1', VRBASECALCIT, 0) AS VL_BC_ICMS,
                                      (SELECT SUM(IT.VRBASECALCIT)
                                         FROM ITEMPROIMPOS IP
                                        WHERE IP.CDFILIAL   = IT.CDFILIAL
                                          AND IP.NRLANCTONF = IT.NRLANCTONF
                                          AND IP.CDIMPOSTO  = IM.CDIMPCARGATRIB) AS VRBASECARGA,
                                      DECODE(CDFISCALIT, '1', VRALIQITEM, 0) AS ALIQ_ICMS,
                                      DECODE(CDFISCALIT, '1', VRIMPOSTOIT, 0) AS VL_ICMS,
                                      (SELECT SUM(IT.VRIMPOSTOIT)
                                         FROM ITEMPROIMPOS IP
                                        WHERE IP.CDFILIAL   = IT.CDFILIAL
                                          AND IP.NRLANCTONF = IT.NRLANCTONF
                                          AND IP.CDIMPOSTO  = IM.CDIMPCARGATRIB) AS VRIMPCARGA,
                                      '0,00' AS VL_BC_ICMS_ST,
                                      '0,00' AS ALIQ_ST,
                                      '0,00' AS VL_ICMS_ST,
                                      '1' AS IND_REC,
                                      '' AS COD_PART,
                                      '0,00' AS VL_PIS,
                                      '0,00' AS VL_COFINS,
                                      CONTCTBL_SPED(C_500.IDENTRSAIDOP, I.CDPRODUTO, C_500.CDTIPOOPER, C_500.FILIAL) AS COD_CTA,
                                      P.CDPRODUTO,
                                      I.CDPRODNCMTRANS AS CDCLASFISC
                                 FROM ITEMPRODUTO I, ITEMPROIMPOS IT, PRODUTO P, IMPOSTO IM
                                WHERE I.CDFILIAL = C_500.CDFILIAL
                                  AND I.NRLANCTONF = C_500.NRLANCTONF
                                  AND I.CDFILIAL = IT.CDFILIAL
                                  AND I.NRLANCTONF = IT.NRLANCTONF
                                  AND I.NRSEQITPROD = IT.NRSEQITPROD
                                  AND SUBSTR(IT.CDFISCOPERIT,1,1) IN ('5','6','7')
                                  AND P.CDPRODUTO = I.CDPRODUTO
                                  AND IM.CDIMPOSTO = IT.CDIMPOSTO)) LOOP

            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('25'||LPAD(RTRIM(V_CONTREGC), 8, '0'), '|C510|'||V_SEQUENCIAL||'|'||C_510.REGC510, P_NRSEQARQMAG);
            V_CONTREGC := NVL(V_CONTREGC,0) + 1;
            V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER(RTRIM(V_SEQUENCIAL))+1)), 3,'0');

            /* CODIGO DO PRODUTO */
            SELECT MAX(CDCHAVEREG)
              INTO V_PRODUTO
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_510.CDPRODUTO
               AND CDREGISTRO = '0200';

            IF V_PRODUTO IS NULL AND (C_510.CDPRODUTO IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
               VALUES
                 ('0200', V_SEQUPROD, C_510.CDPRODUTO, C_510.CDCLASFISC);
            END IF;
            V_PRODUTO := '';

            /* UNIDADE DE MEDIDA */
            SELECT MAX(CDCHAVEREG)
              INTO V_UNID
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_510.UNID
               AND CDREGISTRO = '0190';
            IF (V_UNID IS NULL) AND (C_510.UNID IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
               VALUES
                 ('0190', V_SEQUPROD, C_510.UNID);
            END IF;
            V_UNID := '';

            SELECT MAX(CDCHAVEREG)
              INTO V_CONTCTBL
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_510.COD_CTA
               AND CDREGISTRO = '0500';

            IF (V_CONTCTBL IS NULL) AND (C_510.COD_CTA IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
               VALUES
                  ('0500', V_SEQUPROD, C_510.COD_CTA);
            END IF;
            V_CONTCTBL := '';
         END LOOP;
         FOR C_590 IN (SELECT ('|C590'     || '|' ||
                              T.CST_ICMS   || '|' ||
                              T.CFOP       || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(T.ALIQ_ICMS,2), '999999999990.00')), '.', ',')      || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_OPR,2), '999999999990.00')), '.', ',')      || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_BC_ICMS + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VRBASECARGA,0))),2), '999999999990.00')), '.', ',')      || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_ICMS    + DECODE(V_IDTPCARGATRIB,'O',0,DECODE(C_500.IDENTRSAIDOP,'E',DECODE(V_SGESTADO,'SP',0,NVL(VRIMPCARGA,0)),NVL(VRIMPCARGA,0))),2), '999999999990.00')), '.', ',')      || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(0,2), '999999999990.00')), '.', ',')      || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(0,2), '999999999990.00')), '.', ',')      || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(T.VL_RED_BC,2), '999999999990.00')), '.', ',')      || '|' ||
                              '' || '|') ARQ_C590
                         FROM (SELECT CDSITUTRIBIT AS CST_ICMS,
                                      CDFISCOPERIT AS CFOP,
                                      DECODE(CDFISCALIT, '1', VRALIQITEM, 0) AS ALIQ_ICMS,
                                      SUM(VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL)),0) VL_OPR,
                                      SUM(DECODE(CDFISCALIT, '1', VRBASECALCIT, 0)) AS VL_BC_ICMS,
                                      SUM((SELECT SUM(IP.VRBASECALCIT)
                                             FROM ITEMPROIMPOS IP
                                            WHERE IP.CDFILIAL     = I.CDFILIAL
                                              AND IP.NRLANCTONF   = I.NRLANCTONF
                                              AND IP.CDSITUTRIBIT = I.CDSITUTRIBIT
                                              AND IP.CDFISCOPERIT = I.CDFISCOPERIT
                                              AND IP.CDIMPOSTO    = IM.CDIMPCARGATRIB)) AS VRBASECARGA,
                                      SUM(DECODE(CDFISCALIT, '1', VRIMPOSTOIT, 0)) AS VL_ICMS,
                                      SUM((SELECT SUM(IP.VRIMPOSTOIT)
                                             FROM ITEMPROIMPOS IP
                                            WHERE IP.CDFILIAL     = I.CDFILIAL
                                              AND IP.NRLANCTONF   = I.NRLANCTONF
                                              AND IP.CDSITUTRIBIT = I.CDSITUTRIBIT
                                              AND IP.CDFISCOPERIT = I.CDFISCOPERIT
                                              AND IP.CDIMPOSTO    = IM.CDIMPCARGATRIB)) AS VRIMPCARGA,
                                      0 AS VL_BC_ICMS_ST,
                                      0 AS VL_ICMS_ST,
                                      NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL) ),0) AS VL_RED_BC,
                                      0 AS VL_IPI,
                                      '' AS COD_OBS
                                 FROM ITEMPROIMPOS I, IMPOSTO IM
                                WHERE I.CDFILIAL      = C_500.CDFILIAL
                                  AND I.NRLANCTONF    = C_500.NRLANCTONF
                                  AND I.NRITPROIMPOS    = '1'
                                  AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                  AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                GROUP BY CDSITUTRIBIT, I.CDFISCOPERIT, DECODE(I.CDFISCALIT, '1', I.VRALIQITEM, 0) ) T ) LOOP

            INSERT INTO ARQMAGNETICO
              (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
              ('25'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_590.ARQ_C590, P_NRSEQARQMAG);
            V_CONTREGC := NVL(V_CONTREGC,0) + 1;
            
         END LOOP;
      END LOOP;
   END IF;
 
   /* REGISTRO REFERENTE AO CF-E SAT */
   FOR C_800 IN (SELECT (REG         || '|' ||
                         COD_MOD     || '|' ||
                         COD_SIT     || '|' || 
                         NUM_CFE     || '|' ||
                         DT_DOC      || '|' || 
                         VL_CFE      || '|' ||
                         VL_PIS      || '|' || 
                         VL_COFINS   || '|' ||
                         CNPJ_CPF    || '|' ||
                         NR_SAT      || '|' || 
                         CHV_CFE     || '|' ||
                         VL_DESC     || '|' ||
                         VL_MERC     || '|' ||
                         VL_OUT_DA   || '|' ||
                         VL_ICMS     || '|' || 
                         VL_PIS_ST   || '|' ||
                         VL_COFINS_ST|| '|') AS ARQ_C800, DTEMISSAO, CDFILIAL, CDCAIXA, NRSEQVENDA
                   FROM (SELECT '|C800' AS REG, '59' AS COD_MOD, DECODE(VE.IDSTATUSNFCE,'C','02','A','00') AS COD_SIT,
                                LPAD(NVL(VE.NRNOTAFISCALCE,0),6,'0') AS NUM_CFE, 
                                DECODE(VE.IDSTATUSNFCE,'C','',TO_CHAR(VE.DTEMISSAONFCE,'DDMMYYYY')) AS DT_DOC, 
                                DECODE(VE.IDSTATUSNFCE,'C','',REPLACE(LTRIM(TO_CHAR(SUM(TRUNC(IT.QTPRODVEND*(IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)),'999999999990.00')),'.',',')) AS VL_CFE, 
                                '' AS VL_PIS, '' AS VL_COFINS,/*Contribuinte que apresenta EFD Contribuições não precisa informar valores de PIS e COFINS*/
                                DECODE(VE.IDSTATUSNFCE,'C','',REPLACE(REPLACE(REPLACE(REPLACE(VE.NRINSCRCONS,'.'),'-'),'/'),' ')) AS CNPJ_CPF, 
                                VE.CDSERIESAT AS NR_SAT, SUBSTR(VE.NRACESSONFCE,4,44) AS CHV_CFE, 
                                DECODE(VE.IDSTATUSNFCE,'C','',REPLACE(LTRIM(TO_CHAR(SUM(TRUNC(NVL(IT.VRDESITVEND,0),2)),'999999999990.00')),'.',',')) AS VL_DESC, 
                                DECODE(VE.IDSTATUSNFCE,'C','',REPLACE(LTRIM(TO_CHAR(SUM(TRUNC(IT.QTPRODVEND*(IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0)),2)),'999999999990.00')),'.',',')) AS VL_MERC,
                                DECODE(VE.IDSTATUSNFCE,'C','',REPLACE(LTRIM(TO_CHAR(SUM(TRUNC(NVL(IT.VRACRITVEND,0),2)),'999999999990.00')),'.',',')) AS VL_OUT_DA, 
                                DECODE(VE.IDSTATUSNFCE,'C','',REPLACE(LTRIM(TO_CHAR(SUM(ROUND(II.VRIMPOPRODIT, 2)),'999999999990.00')),'.',',')) AS VL_ICMS, 
                                DECODE(VE.IDSTATUSNFCE,'C','',0) AS VL_PIS_ST, DECODE(VE.IDSTATUSNFCE,'C','',0) AS VL_COFINS_ST, TRUNC(VE.DTEMISSAONFCE) AS DTEMISSAO, VE.CDFILIAL, VE.CDCAIXA, VE.NRSEQVENDA 
                           FROM VENDA VE, FILIAL FI, ITEMVENDA IT, ITVENDAIMPOS II 
                          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.CDINSCESTA      = P_CDINSCESTA 
                            AND VE.IDSITUVENDA     IN ('O','C') 
                            AND ((VE.IDAPROVACAONFCE = 'A' AND VE.IDSTATUSNFCE = 'A') OR (VE.IDSTATUSNFCE = 'C')) 
                            AND VE.IDTPAMBNFCE     = '1' 
                            AND P_PERFIL           = 'A' 
                            AND VE.CDFILIAL        = IT.CDFILIAL 
                            AND VE.CDCAIXA         = IT.CDCAIXA 
                            AND VE.NRSEQVENDA      = IT.NRSEQVENDA 
                            AND IT.CDFILIAL        = II.CDFILIAL 
                            AND IT.CDCAIXA         = II.CDCAIXA 
                            AND IT.NRSEQVENDA      = II.NRSEQVENDA 
                            AND IT.NRSEQUITVEND    = II.NRSEQUITVEND
                            AND ((V_CDSITUCRT = '3') OR (V_CDSITUCRT <> '3' AND V_SGESTADO <> 'CE'))
                         GROUP BY VE.IDSTATUSNFCE, LPAD(NVL(VE.NRNOTAFISCALCE,0),6,'0'), 
                                  DECODE(VE.IDSTATUSNFCE,'C','',TO_CHAR(VE.DTEMISSAONFCE,'DDMMYYYY')), 
                                  DECODE(VE.IDSTATUSNFCE,'C','',REPLACE(REPLACE(REPLACE(REPLACE(VE.NRINSCRCONS,'.'),'-'),'/'),' ')), 
                                  VE.CDSERIESAT, SUBSTR(VE.NRACESSONFCE,4,44), 
                                  TRUNC(VE.DTEMISSAONFCE), VE.CDFILIAL, VE.CDCAIXA, VE.NRSEQVENDA 
                         ORDER BY NUM_CFE)) LOOP 
 
      INSERT INTO ARQMAGNETICO 
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
      VALUES 
         ('28'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_800.ARQ_C800, P_NRSEQARQMAG); 
      V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
 
      FOR C_850 IN (SELECT (REG          || '|' || 
                            CST_ICMS     || '|' || 
                            CFOP         || '|' || 
                            ALIQ_ICMS    || '|' || 
                            VL_OPR       || '|' || 
                            VL_BC_ICMS   || '|' ||
                            VL_ICMS      || '|' || 
                            COD_OBS      || '|' ) ARQ_C850 
                      FROM (SELECT '|C850' AS REG, LPAD(II.CDCSTPRODI,3,'0') AS CST_ICMS, II.CDCFOPPROD AS CFOP, 
                                   REPLACE(LTRIM(TO_CHAR(II.VRPEALPRODIT,'999990.00')),'.',',') AS ALIQ_ICMS,
                                   REPLACE(LTRIM(TO_CHAR(SUM(TRUNC(IT.QTPRODVEND*(IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)),'999999999990.00')),'.',',') AS VL_OPR, 
                                   REPLACE(LTRIM(TO_CHAR(SUM(DECODE(II.VRPEALPRODIT,0,0,TRUNC(IT.QTPRODVEND*(IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2))),   '999999999990.00')),'.',',') AS VL_BC_ICMS, 
                                   REPLACE(LTRIM(TO_CHAR(SUM(ROUND(II.VRIMPOPRODIT, 2)),'999999999990.00')),'.',',') AS VL_ICMS, 
                                   '' AS COD_OBS 
                              FROM VENDA VE, ITEMVENDA IT, ITVENDAIMPOS II 
                             WHERE VE.IDAPROVACAONFCE      = 'A' 
                               AND TRUNC(VE.DTEMISSAONFCE) = C_800.DTEMISSAO 
                               AND VE.CDCAIXA              = C_800.CDCAIXA 
                               AND VE.CDFILIAL             = C_800.CDFILIAL 
                               AND VE.NRSEQVENDA           = C_800.NRSEQVENDA 
                               AND VE.IDTPEMISVEND         = 'S' 
                               AND VE.IDSITUVENDA          = 'O' 
                               AND VE.IDSTATUSNFCE         = 'A' 
                               AND VE.IDTPAMBNFCE          = '1' 
                               AND VE.CDFILIAL             = IT.CDFILIAL 
                               AND VE.CDCAIXA              = IT.CDCAIXA 
                               AND VE.NRSEQVENDA           = IT.NRSEQVENDA 
                               AND IT.CDFILIAL             = II.CDFILIAL 
                               AND IT.CDCAIXA              = II.CDCAIXA 
                               AND IT.NRSEQVENDA           = II.NRSEQVENDA 
                               AND IT.NRSEQUITVEND         = II.NRSEQUITVEND 
                            GROUP BY LPAD(II.CDCSTPRODI,3,'0'), II.CDCFOPPROD, II.VRPEALPRODIT)) LOOP 
 
         INSERT INTO ARQMAGNETICO 
            (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
         VALUES 
            ('28'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_850.ARQ_C850, P_NRSEQARQMAG); 
         V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
      END LOOP; 
   END LOOP; 
 
   FOR C_860 IN (SELECT (REG     || '|' || 
                         COD_MOD || '|' || 
                         NR_SAT  || '|' || 
                         DT_DOC  || '|' || 
                         DOC_INI || '|' || 
                         DOC_FIM || '|' ) ARQ_C860, NR_SAT, DTEMISSAO 
                   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 
                           FROM VENDA VE, FILIAL FI 
                          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.CDINSCESTA      = P_CDINSCESTA 
                            AND P_PERFIL           = 'B' 
                            AND VE.IDSITUVENDA     IN ('O','C') 
                            AND ((VE.IDAPROVACAONFCE = 'A' AND VE.IDSTATUSNFCE = 'A') OR (VE.IDSTATUSNFCE = 'C')) 
                            AND VE.IDTPAMBNFCE     = '1'
                            AND ((V_CDSITUCRT = '3') OR (V_CDSITUCRT <> '3' AND V_SGESTADO <> 'CE'))
                          GROUP BY VE.CDSERIESAT, TRUNC(VE.DTEMISSAONFCE))) LOOP 
 
      INSERT INTO ARQMAGNETICO 
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
      VALUES 
         ('28'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_860.ARQ_C860, P_NRSEQARQMAG); 
      V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
 
      FOR C_890 IN (SELECT (REG          || '|' || 
                            CST_ICMS     || '|' || 
                            CFOP         || '|' || 
                            ALIQ_ICMS    || '|' || 
                            VL_OPR       || '|' ||
                            VL_BC_ICMS   || '|' ||
                            VL_ICMS      || '|' || 
                            COD_OBS      || '|' ) ARQ_C890 
                      FROM (SELECT '|C890' AS REG, LPAD(II.CDCSTPRODI,3,'0') AS CST_ICMS, II.CDCFOPPROD AS CFOP, 
                                   REPLACE(LTRIM(TO_CHAR(II.VRPEALPRODIT,'999990.00')),'.',',') AS ALIQ_ICMS,
                                   REPLACE(LTRIM(TO_CHAR(SUM(TRUNC(IT.QTPRODVEND*(IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)),'999999999990.00')),'.',',') AS VL_OPR, 
                                   REPLACE(LTRIM(TO_CHAR(SUM(DECODE(II.VRPEALPRODIT,0,0,TRUNC(IT.QTPRODVEND*(IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2))),   '999999999990.00')),'.',',') AS VL_BC_ICMS, 
                                   REPLACE(LTRIM(TO_CHAR(SUM(ROUND(II.VRIMPOPRODIT,2)),'999999999990.00')),'.',',') AS VL_ICMS,
                                   '' AS COD_OBS 
                              FROM VENDA VE, FILIAL FI, ITEMVENDA IT, ITVENDAIMPOS II 
                             WHERE VE.IDAPROVACAONFCE      = 'A' 
                               AND VE.CDFILIAL             = FI.CDFILIAL 
                               AND FI.CDEMPRESA            = P_CDEMPRESA 
                               AND FI.CDINSCESTA           = P_CDINSCESTA 
                               AND TRUNC(VE.DTEMISSAONFCE) = C_860.DTEMISSAO 
                               AND VE.CDSERIESAT           = C_860.NR_SAT 
                               AND VE.IDTPEMISVEND         = 'S' 
                               AND VE.IDSITUVENDA          = 'O' 
                               AND VE.IDSTATUSNFCE         = 'A' 
                               AND VE.IDTPAMBNFCE          = '1' 
                               AND VE.CDFILIAL             = IT.CDFILIAL 
                               AND VE.CDCAIXA              = IT.CDCAIXA 
                               AND VE.NRSEQVENDA           = IT.NRSEQVENDA 
                               AND IT.CDFILIAL             = II.CDFILIAL 
                               AND IT.CDCAIXA              = II.CDCAIXA 
                               AND IT.NRSEQVENDA           = II.NRSEQVENDA 
                               AND IT.NRSEQUITVEND         = II.NRSEQUITVEND 
                            GROUP BY II.CDCSTPRODI, II.CDCFOPPROD, II.VRPEALPRODIT)) LOOP 
 
         INSERT INTO ARQMAGNETICO 
            (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
         VALUES 
            ('28'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_890.ARQ_C890, P_NRSEQARQMAG); 
         V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
 
      END LOOP; 
   END LOOP; 
 
   IF V_CONTREGC <> 0 THEN 
      V_MOVIMENT := 0; 
   ELSE 
      V_MOVIMENT := 1; 
   END IF; 
   /* ABERTURA DO REGISTRO C */
   V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
   INSERT INTO ARQMAGNETICO 
     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
   VALUES 
     ('18'||LPAD('0', 8, '0'), '|C001'|| '|' ||V_MOVIMENT|| '|', P_NRSEQARQMAG); 
   /* ENCERRAMENTO DO BLOCO C */
   V_CONTREGC := NVL(V_CONTREGC,0) + 1; 
   INSERT INTO ARQMAGNETICO 
     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG) 
   VALUES 
     ('40'||LPAD(RTRIM(V_CONTREGC), 8, '0'), '|C990'|| '|' ||V_CONTREGC|| '|', P_NRSEQARQMAG); 
   RETURN(LPAD(TO_CHAR(NVL(V_CONTREGC,0)),10, '0')||LPAD(TO_CHAR(NVL(V_TOTFORPER_S,0)),10,'0')||LPAD(TO_CHAR(NVL(V_VRFORAPER_E,0)),10,'0')||LPAD(TO_CHAR(NVL(V_SEQUPROD,0)), 10, '0')||LPAD(TO_CHAR(NVL(V_VRDEBESP,0)), 10, '0'));
END;
/

CREATE OR REPLACE FUNCTION SPED_BLOCOE (
   P_CDIMPOSTO    IN IMPOSTO.CDIMPOSTO%TYPE,
   P_CDEMPRESA    IN EMPRESA.CDEMPRESA%TYPE,
   P_CDINSCESTA   IN EMPRESA.CDINSCESTA%TYPE,
   P_DTINICIAL    IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DTFINAL      IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_LIVROMAG     IN NOTAFISCAL.IDSTATUS%TYPE,
   P_NRSEQARQMAG  IN ARQMAGNETICO.NRSEQARQMAG%TYPE,
   P_TOTFORPER_S  IN IMPOSTONF.VRIMPOSTONF%TYPE,
   P_TOTFORPER_E  IN IMPOSTONF.VRIMPOSTONF%TYPE,
   P_VL_DEB_EXTE  IN IMPOSTONF.VRIMPOSTONF%TYPE,
   P_GERAFORSALE  IN VARCHAR2 DEFAULT 'N',
   P_IDDIFALIQ    IN VARCHAR2) RETURN NUMBER
AS
   V_CONTREGE              NUMBER;
   V_MOVIMENT              NUMBER;
   V_IMP_1605              NUMBER;
   V_IMP_5605              NUMBER;
   V_AJ_DEBITOS            NUMBER;
   V_VRTOT_AJ_DEB          NUMBER;
   V_VR_ESTORNO_CRED       NUMBER;
   V_AJ_CREDITOS           NUMBER;
   V_VL_TOT_AJ_CREDITOS    NUMBER;
   V_VL_ESTORNOS_DEB       NUMBER;
   V_VL_TOT_DED            NUMBER;
   V_VR_DEB_ESP            NUMBER;
   V_C197ENTRADA           NUMBER;
   V_C197SAIDA             NUMBER;
   V_CDIMPOSTRIB           VARCHAR2(02);
   V_SGESTADO              VARCHAR2(02);
   V_VREXTRAPUR            NUMBER;
   V_VROUTRDEB             NUMBER;
   V_REG_E210              VARCHAR2(300);
   V_CDSITUCRT             VARCHAR2(01);
   V_AJ_DEBITOS_DIFAL      NUMBER;
   V_AJ_DEBITOS_FCP        NUMBER;
   V_AJ_CREDITOS_DIFAL     NUMBER;
   V_AJ_CREDITOS_FCP       NUMBER;
   V_VL_TOT_DED_DIFAL      NUMBER;
   V_VL_TOT_DED_FCP        NUMBER;
   V_VR_DEB_ESP_DIFAL      NUMBER;
   V_VR_DEB_ESP_FCP        NUMBER;
   V_AJ_DEBITO_DOC_ST      NUMBER;
   V_EXISTE_IPI            VARCHAR2(01);
BEGIN
   BEGIN
      SELECT SGESTADO
        INTO V_SGESTADO
        FROM INSCRESTAD
       WHERE CDEMPRESA  = P_CDEMPRESA
         AND CDINSCESTA = P_CDINSCESTA;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_SGESTADO := NULL;
   END;

   /*VERIFICA SE A EMPRESA É DO SIMPLES NACIONAL, '3' NAO É DO SIMPLES, APENAS 1 E 2*/
   SELECT NVL(MAX(CDSITUCRT), '3') CDSITUCRT
     INTO V_CDSITUCRT
     FROM PARAMEMPRESA
    WHERE CDEMPRESA = P_CDEMPRESA;

   IF (V_CDSITUCRT = '3') THEN
      FOR C_REGE100 IN (SELECT DISTINCT ('|E100'                    || '|' ||
                                TO_CHAR(DTINIPERIODO,'DDMMYYYY')    || '|' ||
                                TO_CHAR(DTFIMPERIODO,'DDMMYYYY')    || '|'  ) AS ARQ_E100,
                                TO_CHAR(DTINIPERIODO,'DDMMYYYY') as DTINICIAL,
                                TO_CHAR(DTFIMPERIODO,'DDMMYYYY') as DTFINAL,
                                NRSEQUMAPAPU
                        FROM MAPAAPURAC
                        WHERE CDEMPRESA     = P_CDEMPRESA                   AND
                              CDINSCESTA    = P_CDINSCESTA                  AND
                              DTINIPERIODO  = P_DTINICIAL                   AND
                              DTFIMPERIODO  = P_DTFINAL                     AND
                              CDIMPOSTO     = P_CDIMPOSTO  ) LOOP
         V_CONTREGE := NVL(V_CONTREGE,0) + 1;
         INSERT INTO ARQMAGNETICO
           (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
           ('53'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE100.ARQ_E100, P_NRSEQARQMAG);

         /*BUSCA O VALOR DO C197 GERADO COM BASE NOS ITENS, POIS OS MESMOS
           DEVEM SER ABATIDOS DO DÉBITO E CRÉDITO NORMAL*/
         SELECT NVL(SUM(DECODE(NF.IDENTRSAIDOP,'E',IT.VRIMPOSTOIT,0)),0) AS VRENTRADA,
                NVL(SUM(DECODE(NF.IDENTRSAIDOP,'S',IT.VRIMPOSTOIT,0)),0) AS VRSAIDA
           INTO V_C197ENTRADA, V_C197SAIDA
           FROM NOTAFISCAL NF, ITEMPROIMPOS IT, IMPOSTO IM, DETITMAPARECUP DT
          WHERE DT.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
            AND NF.CDFILIAL     = IT.CDFILIAL
            AND NF.NRLANCTONF   = IT.NRLANCTONF
            AND IT.CDFILIAL     = DT.CDFILIAL
            AND IT.NRLANCTONF   = DT.NRLANCTONF
            AND IT.NRSEQITPROD  = DT.NRSEQITPROD
            AND IT.CDIMPOSTO    = DT.CDIMPOSTO
            AND IT.NRITPROIMPOS = DT.NRITPROIMPOS
            AND IT.CDIMPOSTO    = IM.CDIMPOSTO
            AND IM.CDIMPOSTONFE = '00'
            AND IT.NRITPROIMPOS = '1';

         /* BUSCA O VALOR DO CFOP "1.605 - RECEBIMENTO, POR TRANSFERÊNCIA,
            DE SALDO DEVEDOR DO ICMS DE OUTRO ESTABELECIMENTO DA MESMA EMPRESA",
            QUE ACRESCE O VALOR DOS DÉBITOS*/
         SELECT NVL(SUM(VRIMPOSTONF),0)
           INTO V_IMP_1605
           FROM IMPOSTONF I, IMPOSTO IP
          WHERE I.NRSEQUMAPAPU  = C_REGE100.NRSEQUMAPAPU
            AND IP.CDIMPOSTONFE = P_CDIMPOSTO
            AND NVL(IDIMPOSTONF,'1') <> '3'
            AND CDFISCOPERNF    = '1605'
            AND IP.CDIMPOSTO    = I.CDIMPOSTO;

         /* BUSCA O VALOR DO CFOP "5.605 - TRANSFERÊNCIA DE SALDO DEVEDOR DE ICMS
            DE OUTRO ESTABELECIMENTO DA MESMA EMPRESA", QUE ACRESCE O VALOR DOS CRÉDITOS*/
         SELECT NVL(SUM(VRIMPOSTONF),0)
           INTO V_IMP_5605
           FROM IMPOSTONF I
          WHERE NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
            AND I.CDIMPOSTO  = P_CDIMPOSTO
            AND NVL(IDIMPOSTONF,'1') <> '3'
            AND CDFISCOPERNF = '5605';

         /* BUSCA OS VALORES DE AJUSTE A DÉBITO - DOC. FISCAL PRESENTES NA APURAÇÃO,
            DE ACORDO COM O CÓDIGO DE AJUSTE - CAMPO 3 E110 */
         SELECT NVL(SUM(VRITEMMAPR),0)
           INTO V_AJ_DEBITOS
           FROM (SELECT NVL(SUM(ROUND(DECODE(SUBSTR(IM.CDAJUSTEITMAPA,3,1),'9',0,IT.VRIMPOSTOIT),2)),0) AS VRITEMMAPR
                   FROM ITMAPARECUP IM, ITEMPROIMPOS IT, IMPOSTO II, DETITMAPARECUP DT
                  WHERE IM.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
                    AND IM.IDCOMPOEC197 = 'I'
                    AND IM.CDFILIAL     = IT.CDFILIAL
                    AND IM.NRLANCTONF   = IT.NRLANCTONF
                    AND IT.CDIMPOSTO    = II.CDIMPOSTO
                    AND II.CDIMPOSTONFE = P_CDIMPOSTO
                    AND SUBSTR(IM.CDAJUSTEITMAPA,4,1) IN ('0','2','9')
                    AND IM.NRSEQUMAPAPU = DT.NRSEQUMAPAPU
                    AND IM.IDTIPOITMAPR = DT.IDTIPOITMAPR
                    AND IM.NRSEQITMAPR  = DT.NRSEQITMAPR
                    AND IT.CDFILIAL     = DT.CDFILIAL
                    AND IT.NRLANCTONF   = DT.NRLANCTONF
                    AND IT.NRSEQITPROD  = DT.NRSEQITPROD
                    AND IT.NRITPROIMPOS = DT.NRITPROIMPOS
                    AND ((IT.NRITPROIMPOS = '1' AND IT.CDFISCALIT = '1') OR (IT.NRITPROIMPOS = '3'))
                    AND SUBSTR(IM.CDAJUSTEITMAPA,3,1) IN ('3','4','5')
                    AND SUBSTR(IM.CDAJUSTEITMAPA,4,1) IN ('0','3','4','5','6','7','8')
                  UNION ALL
                 SELECT ROUND(DECODE(SUBSTR(IM.CDAJUSTEITMAPA,3,1),'9',0,IM.VRITEMMAPR),2) AS VRITEMMAPR
                   FROM ITMAPARECUP IM
                  WHERE IM.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
                    AND IM.IDCOMPOEC197 = 'D'
                    AND SUBSTR(IM.CDAJUSTEITMAPA,3,1) IN ('3','4','5')
                    AND SUBSTR(IM.CDAJUSTEITMAPA,4,1) IN ('0','3','4','5','6','7','8'));

         /* VALOR TOTAL DE AJUSTE A DÉBITO - CAMPO 4 E110 */
         SELECT NVL(SUM(VRITEMMAPR),0)
           INTO V_VRTOT_AJ_DEB
           FROM ITMAPARECUP IT
          WHERE IT.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
            AND IT.IDCOMPOEC197 = 'N'
            AND SUBSTR(IT.CDAJUSTEITMAPA,3,1) = '0'
            AND SUBSTR(IT.CDAJUSTEITMAPA,4,1) = '0'
            AND (((NVL(P_IDDIFALIQ,'N') = 'S') AND (IDTIPOITMAPR = 'DA')) OR (IDTIPOITMAPR <> 'DA'));

         /* VALOR DO ESTORNO DE CRÉDITO - CAMPO 5 E110 */
         SELECT NVL(SUM(VRITEMMAPR),0)
           INTO V_VR_ESTORNO_CRED
           FROM ITMAPARECUP IT
          WHERE IT.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
            AND IT.IDCOMPOEC197 = 'N'
            AND SUBSTR(IT.CDAJUSTEITMAPA,3,1) = '0'
            AND SUBSTR(IT.CDAJUSTEITMAPA,4,1) = '1'
            AND (((NVL(P_IDDIFALIQ,'N') = 'S') AND (IDTIPOITMAPR = 'DA')) OR (IDTIPOITMAPR <> 'DA'));

         /* BUSCA OS VALORES DE AJUSTE A CRÉDITO - DOC. FISCAL PRESENTES NA APURAÇÃO,
            DE ACORDO COM O CÓDIGO DE AJUSTE - CAMPO 7 E110*/
         SELECT NVL(SUM(VRITEMMAPR),0)
           INTO V_AJ_CREDITOS
           FROM (SELECT NVL(SUM(ROUND(DECODE(SUBSTR(IM.CDAJUSTEITMAPA,3,1),'9',0,DECODE(IT.CDFISCALIT,'1',IT.VRIMPOSTOIT,0)),2)),0) AS VRITEMMAPR
                   FROM ITMAPARECUP IM, ITEMPROIMPOS IT, IMPOSTO II, DETITMAPARECUP DT
                  WHERE IM.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
                    AND IM.IDCOMPOEC197 = 'I'
                    AND IM.CDFILIAL     = IT.CDFILIAL
                    AND IM.NRLANCTONF   = IT.NRLANCTONF
                    AND IT.CDIMPOSTO    = II.CDIMPOSTO
                    AND II.CDIMPOSTONFE = P_CDIMPOSTO
                    AND SUBSTR(IM.CDAJUSTEITMAPA,4,1) IN ('0','2','9')
                    AND IM.NRSEQUMAPAPU = DT.NRSEQUMAPAPU
                    AND IM.IDTIPOITMAPR = DT.IDTIPOITMAPR
                    AND IM.NRSEQITMAPR  = DT.NRSEQITMAPR
                    AND IT.CDFILIAL     = DT.CDFILIAL
                    AND IT.NRLANCTONF   = DT.NRLANCTONF
                    AND IT.NRSEQITPROD  = DT.NRSEQITPROD
                    AND IT.NRITPROIMPOS = DT.NRITPROIMPOS
                    AND SUBSTR(IM.CDAJUSTEITMAPA,3,1) IN ('0','1','2')
                    AND SUBSTR(IM.CDAJUSTEITMAPA,4,1) IN ('0','3','4','5','6','7','8')
                  UNION ALL
                 SELECT ROUND(DECODE(SUBSTR(IM.CDAJUSTEITMAPA,3,1),'9',0,IM.VRITEMMAPR),2) AS VRITEMMAPR
                   FROM ITMAPARECUP IM
                  WHERE IM.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
                    AND IM.IDCOMPOEC197 = 'D'
                    AND SUBSTR(IM.CDAJUSTEITMAPA,3,1) IN ('0','1','2')
                    AND SUBSTR(IM.CDAJUSTEITMAPA,4,1) IN ('0','3','4','5','6','7','8'));

         /* VALOR TOTAL DE AJUSTE A CREDITO - CAMPO 8 E110 */
         SELECT NVL(SUM(VRITEMMAPR),0)
           INTO V_VL_TOT_AJ_CREDITOS
           FROM ITMAPARECUP IT
          WHERE IT.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
            AND IT.IDCOMPOEC197 = 'N'
            AND SUBSTR(IT.CDAJUSTEITMAPA,3,1) = '0'
            AND SUBSTR(IT.CDAJUSTEITMAPA,4,1) = '2'
            AND (((NVL(P_IDDIFALIQ,'N') = 'S') AND (IDTIPOITMAPR = 'DA')) OR (IDTIPOITMAPR <> 'DA'));

         /* VALOR TOTAL DE AJUSTE A ESTORNO DE DEBITOS- CAMPO 9 E110 */
         SELECT NVL(SUM(VRITEMMAPR),0)
           INTO V_VL_ESTORNOS_DEB
           FROM ITMAPARECUP IT
          WHERE IT.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
            AND IT.IDCOMPOEC197 = 'N'
            AND SUBSTR(IT.CDAJUSTEITMAPA,3,1) = '0'
            AND SUBSTR(IT.CDAJUSTEITMAPA,4,1) = '3'
            AND (((NVL(P_IDDIFALIQ,'N') = 'S') AND (IDTIPOITMAPR = 'DA')) OR (IDTIPOITMAPR <> 'DA'));

         /*VALOR TOTAL DAS DEDUÇÕES - CAMPO 12 E110 */
         SELECT NVL(SUM(VRITEMMAPR),0)
           INTO V_VL_TOT_DED
           FROM (SELECT ROUND(DECODE(SUBSTR(IM.CDAJUSTEITMAPA,3,1),'9',0,IM.VRITEMMAPR),2) AS VRITEMMAPR
                   FROM ITMAPARECUP IM
                  WHERE IM.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
                    AND IM.IDCOMPOEC197 = 'D'
                    AND SUBSTR(IM.CDAJUSTEITMAPA,3,1) = '6'
                    AND SUBSTR(IM.CDAJUSTEITMAPA,4,1) = '0'
                  UNION ALL
                 SELECT SUM(ROUND(DECODE(SUBSTR(IM.CDAJUSTEITMAPA,3,1),'9',0,DECODE(IT.CDFISCALIT,'1',IT.VRIMPOSTOIT,0)),2)) AS VRITEMMAPR
                   FROM ITMAPARECUP IM, ITEMPROIMPOS IT, IMPOSTO II, DETITMAPARECUP DT
                  WHERE IM.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
                    AND IM.IDCOMPOEC197 = 'I'
                    AND IM.CDFILIAL     = IT.CDFILIAL
                    AND IM.NRLANCTONF   = IT.NRLANCTONF
                    AND IT.CDIMPOSTO    = II.CDIMPOSTO
                    AND II.CDIMPOSTONFE = P_CDIMPOSTO
                    AND SUBSTR(IM.CDAJUSTEITMAPA,4,1) IN ('0','2','9')
                    AND IM.NRSEQUMAPAPU = DT.NRSEQUMAPAPU
                    AND IM.IDTIPOITMAPR = DT.IDTIPOITMAPR
                    AND IM.NRSEQITMAPR  = DT.NRSEQITMAPR
                    AND IT.CDFILIAL     = DT.CDFILIAL
                    AND IT.NRLANCTONF   = DT.NRLANCTONF
                    AND IT.NRSEQITPROD  = DT.NRSEQITPROD
                    AND IT.NRITPROIMPOS = DT.NRITPROIMPOS
                    AND SUBSTR(IM.CDAJUSTEITMAPA,3,1) = '6'
                    AND SUBSTR(IM.CDAJUSTEITMAPA,4,1) = '0'
                  UNION ALL
                  SELECT SUM(VRITEMMAPR) AS VRITEMMAPR
                    FROM ITMAPARECUP IT
                   WHERE IT.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
                     AND IT.IDCOMPOEC197 = 'N'
                     AND SUBSTR(IT.CDAJUSTEITMAPA,3,1) = '0'
                     AND SUBSTR(IT.CDAJUSTEITMAPA,4,1) = '4'
                     AND (((NVL(P_IDDIFALIQ,'N') = 'S') AND (IDTIPOITMAPR = 'DA')) OR (IDTIPOITMAPR <> 'DA')));

         /*BUSCA OS VALOR DOS DÉBITOS ESPECIAIS - CAMPO 15 E110*/
         SELECT NVL(SUM(VRITEMMAPR),0)
           INTO V_VR_DEB_ESP
            FROM (SELECT ROUND(DECODE(SUBSTR(IM.CDAJUSTEITMAPA,3,1),'9',0,IM.VRITEMMAPR),2) AS VRITEMMAPR
                   FROM ITMAPARECUP IM
                  WHERE IM.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
                    AND IM.IDCOMPOEC197 = 'D'
                    AND SUBSTR(IM.CDAJUSTEITMAPA,3,1) = '7'
                    AND SUBSTR(IM.CDAJUSTEITMAPA,4,1) = '0'
                  UNION ALL
                 SELECT SUM(ROUND(DECODE(SUBSTR(IM.CDAJUSTEITMAPA,3,1),'9',0,IT.VRIMPOSTOIT),2)) AS VRITEMMAPR
                   FROM ITMAPARECUP IM, ITEMPROIMPOS IT, IMPOSTO II, DETITMAPARECUP DT
                  WHERE IM.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
                    AND IM.IDCOMPOEC197 = 'I'
                    AND IM.CDFILIAL     = IT.CDFILIAL
                    AND IM.NRLANCTONF   = IT.NRLANCTONF
                    AND IT.CDIMPOSTO    = II.CDIMPOSTO
                    AND II.CDIMPOSTONFE = P_CDIMPOSTO
                    AND SUBSTR(IM.CDAJUSTEITMAPA,4,1) IN ('0','2','9')
                    AND IM.NRSEQUMAPAPU = DT.NRSEQUMAPAPU
                    AND IM.IDTIPOITMAPR = DT.IDTIPOITMAPR
                    AND IM.NRSEQITMAPR  = DT.NRSEQITMAPR
                    AND IT.CDFILIAL     = DT.CDFILIAL
                    AND IT.NRLANCTONF   = DT.NRLANCTONF
                    AND IT.NRSEQITPROD  = DT.NRSEQITPROD
                    AND IT.NRITPROIMPOS = DT.NRITPROIMPOS
                    AND ((IT.NRITPROIMPOS = '1' AND IT.CDFISCALIT = '1') OR (IT.NRITPROIMPOS = '3'))
                    AND SUBSTR(IM.CDAJUSTEITMAPA,3,1) = '7'
                    AND SUBSTR(IM.CDAJUSTEITMAPA,4,1) = '0'
                  UNION ALL
                  SELECT SUM(VRITEMMAPR) AS VRITEMMAPR
                    FROM ITMAPARECUP IT
                   WHERE IT.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
                     AND IT.IDCOMPOEC197 = 'N'
                     AND SUBSTR(IT.CDAJUSTEITMAPA,3,1) = '0'
                     AND SUBSTR(IT.CDAJUSTEITMAPA,4,1) = '5'
                     AND (((NVL(P_IDDIFALIQ,'N') = 'S') AND (IDTIPOITMAPR = 'DA')) OR (IDTIPOITMAPR <> 'DA')));

         FOR C_REGE110 IN (SELECT ('|E110'   || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRNORMDEBI,  2),0),'999999999990.00')), '.', ',')   || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRAJUSTEDEB, 2),0),'999999999990.00')), '.', ',')   || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VROUTRDEBI,  2),0),'999999999990.00')), '.', ',')   || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRESTOCRED,  2),0),'999999999990.00')), '.', ',')   || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRNORMCRED,  2),0),'999999999990.00')), '.', ',')   || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRAJUSTECRED,2),0),'999999999990.00')), '.', ',')   || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VROUTRCRED,  2),0),'999999999990.00')), '.', ',')   || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRESTODEBI,  2),0),'999999999990.00')), '.', ',')   || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRSLDCRANTE, 2),0),'999999999990.00')), '.', ',')   || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(DECODE(VRSALDOAPUR,ABS(VRSALDOAPUR),VRSALDOAPUR,0),2),0), '999999999990.00')), '.', ',')   || '|' || -- SALDO APURADO
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRDEDUCAO,   2),0),'999999999990.00')), '.', ',')   || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(DECODE(VRSALDOAPUR-VRDEDUCAO,ABS(VRSALDOAPUR-VRDEDUCAO),VRSALDOAPUR-VRDEDUCAO,0),     2),0),'999999999990.00')), '.', ',')   || '|' || --ICMS A RECOLHER
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(DECODE(VRSALDOAPUR-VRDEDUCAO,ABS(VRSALDOAPUR-VRDEDUCAO),0,ABS(VRSALDOAPUR-VRDEDUCAO)),2),0),'999999999990.00')), '.', ',')   || '|' || --SALDO CREDOR A TRANSPORTAR
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRDEBESP,   2),0),'999999999990.00')), '.', ',')   || '|') AS ARQ_E110
                              FROM (SELECT VRNORMDEBI, VRAJUSTEDEB, VROUTRDEBI, VRESTOCRED, VRNORMCRED, VRAJUSTECRED, VROUTRCRED, VRESTODEBI,
                                           VRSLDCRANTE, VRDEDUCAO, VRDEBESP, (VRNORMDEBI + V_AJ_DEBITOS + V_VRTOT_AJ_DEB + V_VR_ESTORNO_CRED) -
                                           (VRNORMCRED + V_AJ_CREDITOS + V_VL_TOT_AJ_CREDITOS + V_VL_ESTORNOS_DEB + VRSLDCRANTE) AS VRSALDOAPUR
                                      FROM (SELECT DISTINCT CASE WHEN NVL(VRNORMDEBI,0) + V_IMP_1605 - NVL(P_TOTFORPER_S,0) - V_IMP_5605 - V_C197SAIDA > 0
                                                                 THEN NVL(VRNORMDEBI,0) + V_IMP_1605 - NVL(P_TOTFORPER_S,0) - V_IMP_5605 - V_C197SAIDA
                                                                 ELSE 0 END AS VRNORMDEBI,
                                                   V_AJ_DEBITOS         AS VRAJUSTEDEB,
                                                   V_VRTOT_AJ_DEB       AS VROUTRDEBI,
                                                   V_VR_ESTORNO_CRED    AS VRESTOCRED,
                                                   CASE WHEN NVL(VRNORMCRED,0) + V_IMP_5605 - V_IMP_1605 - V_C197ENTRADA > 0
                                                        THEN NVL(VRNORMCRED,0) + V_IMP_5605 - V_IMP_1605 - V_C197ENTRADA
                                                        ELSE 0 END AS VRNORMCRED,
                                                   V_AJ_CREDITOS        AS VRAJUSTECRED,
                                                   V_VL_TOT_AJ_CREDITOS AS VROUTRCRED,
                                                   V_VL_ESTORNOS_DEB    AS VRESTODEBI,
                                                   NVL(VRSLDCRANTE,0)   AS VRSLDCRANTE,
                                                   V_VL_TOT_DED         AS VRDEDUCAO,
                                                   NVL(P_TOTFORPER_S,0) + V_VR_DEB_ESP AS VRDEBESP,
                                                   M.NRSEQUMAPAPU
                                              FROM MAPAAPURAC M, MAPARECUP R
                                             WHERE M.NRSEQUMAPAPU = R.NRSEQUMAPAPU
                                               AND R.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
                                               AND M.CDIMPOSTO    = P_CDIMPOSTO)))LOOP

            INSERT INTO ARQMAGNETICO
              (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
              ('54'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE110.ARQ_E110, P_NRSEQARQMAG);
            V_CONTREGE := NVL(V_CONTREGE,0) + 1;

            FOR C_E111 IN (SELECT '|E111'                                                                          || '|' ||
                                  TRIM(REPLACE(REPLACE(CDAJUSTEITMAPA, CHR(10), ' ' ), CHR(9), ' '))               || '|' ||
                                  TRIM(REPLACE(REPLACE(DSITEMMAPR,     CHR(10), ' ' ), CHR(9), ' '))               || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRITEMMAPR,2),0), '999999999990.00')), '.', ',') || '|' AS E111,
                                  R.CDFILIAL, R.NRLANCTONF, R.VRITEMMAPR
                             FROM ITMAPARECUP R
                            WHERE R.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
                              AND R.IDCOMPOEC197 = 'N'
                              AND (((NVL(P_IDDIFALIQ,'N') = 'S') AND (IDTIPOITMAPR = 'DA')) OR (IDTIPOITMAPR <> 'DA'))) LOOP
               INSERT INTO ARQMAGNETICO
                 (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                 ('54'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_E111.E111, P_NRSEQARQMAG);
               V_CONTREGE := NVL(V_CONTREGE,0) + 1;

               FOR C_E113 IN (SELECT '|E113'                                                                                 || '|' ||
                                     CNPJ                                                                                    || '|' ||
                                     CDMODDOCFISC                                                                            || '|' ||
                                     SERIE                                                                                   || '|' ||
                                     ''                                                                                      || '|' ||
                                     LTRIM(NRNOTAFISC,0)                                                                     || '|' ||
                                     REPLACE(TO_CHAR(DTEMISSAO,'DDMMYYYY'),'/','')                                           || '|' ||
                                     ''                                                                                      || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(NVL(ROUND(C_E111.VRITEMMAPR,2),0), '999999999990.00')), '.', ',') || '|' ||
                                     CASE WHEN P_DTINICIAL >= TO_DATE('01/01/2017') THEN NRACESSONFE ||'|' ELSE '' END AS E113
                                FROM (SELECT NF.IDORIGDESTNF||FI.CDFILIAL AS CNPJ,
                                             CDMODDOCFISC,
                                             CASE WHEN IDENTRSAIDOP = 'E' THEN NF.CDSERIEENTR ELSE NF.CDSERIE END AS SERIE,
                                             NF.NRNOTAFISC, NF.DTEMISSAO, NF.NRLANCTONF, NF.CDFILIAL, NF.NRACESSONFE
                                        FROM NOTAFISCAL NF, FILIAL FI
                                       WHERE DECODE(IDENTRSAIDOP,'E',NF.CDFILIEMIT,NF.CDFILIRECE) = FI.CDFILIAL
                                         AND NF.CDEMPRESA  = FI.CDEMPRESA
                                         AND NVL(NF.IDORIGDESTNF,'L') = 'L'
                                         AND NF.NRLANCTONF = C_E111.NRLANCTONF
                                         AND NF.CDFILIAL   = C_E111.CDFILIAL
                                       UNION
                                      SELECT NF.IDORIGDESTNF||REPLACE(REPLACE(REPLACE(NF.CDCLIENTE,'.',''),'/',''),'-','') AS CNPJ,
                                             NF.CDMODDOCFISC,
                                             CASE WHEN IDENTRSAIDOP = 'E' THEN NF.CDSERIEENTR ELSE NF.CDSERIE END AS SERIE,
                                             NF.NRNOTAFISC, NF.DTEMISSAO, NF.NRLANCTONF, NF.CDFILIAL, NF.NRACESSONFE
                                        FROM CLIENTE CL, NOTAFISCAL NF
                                       WHERE CL.CDCLIENTE  = NF.CDCLIENTE
                                         AND NVL(NF.IDORIGDESTNF,'C') = 'C'
                                         AND NF.NRLANCTONF = C_E111.NRLANCTONF
                                         AND NF.CDFILIAL   = C_E111.CDFILIAL
                                       UNION
                                      SELECT NF.IDORIGDESTNF||REPLACE(REPLACE(REPLACE(NF.CDFORNECED,'.',''),'/',''),'-','') AS CNPJ,
                                             NF.CDMODDOCFISC,
                                             CASE WHEN IDENTRSAIDOP = 'E' THEN NF.CDSERIEENTR ELSE NF.CDSERIE END AS SERIE,
                                             NF.NRNOTAFISC, NF.DTEMISSAO, NF.NRLANCTONF, NF.CDFILIAL, NF.NRACESSONFE
                                        FROM FORNECEDOR FO, NOTAFISCAL NF
                                       WHERE FO.CDFORNECED = NF.CDFORNECED
                                         AND NVL(NF.IDORIGDESTNF,'F') = 'F'
                                         AND NF.NRLANCTONF = C_E111.NRLANCTONF
                                         AND NF.CDFILIAL   = C_E111.CDFILIAL)) LOOP
                  INSERT INTO ARQMAGNETICO
                    (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                    ('54'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_E113.E113, P_NRSEQARQMAG);
                  V_CONTREGE := NVL(V_CONTREGE,0) + 1;
               END LOOP;
            END LOOP;
         END LOOP;

         FOR C_REGE115 IN (SELECT '|E115'          ||'|'||
                                   CDINFADICMAPA   ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRINFADICMAPA,2),0), '999999999990.00')), '.', ',') ||'|'||
                                   DSINFADICMAPA                                                                       ||'|' AS E115
                              FROM INFADICMAPA
                             WHERE NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU) LOOP
            V_CONTREGE := NVL(V_CONTREGE,0) + 1;
            INSERT INTO ARQMAGNETICO
              (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
              ('54'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE115.E115, P_NRSEQARQMAG);
         END LOOP;

         FOR C_REGE116 IN (SELECT '|E116'                         || '|' ||
                                  '000'                           || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRRECEGUIA,2),0), '999999999990.00')), '.', ',')   || '|' || --VRTOTAIMPOS+NVL(P_VL_DEB_EXTE,0)
                                  TO_CHAR(DTVENCGUIA, 'DDMMYYYY') || '|' ||
                                  CDRECEGUIA                      || '|' ||
                                  ''                              || '|' ||
                                  ''                              || '|' ||
                                  ''                              || '|' ||
                                  ''                              || '|' ||
                                  TO_CHAR(DTINIPERIODO, 'MMYYYY') || '|'  AS ARQ_E116
                             FROM MAPAAPURAC M
                            WHERE M.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU
                              AND M.VRTOTAIMPOS > 0
                            UNION ALL
                           SELECT '|E116'                         || '|' ||
                                  LPAD(CDOBRIGAGUIA, 3, '0')      || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRRECEITAGUIA,2),0), '999999999990.00')), '.', ',') || '|' ||
                                  TO_CHAR(DTVENCGUIACOMPL, 'DDMMYYYY')  || '|' ||
                                  CDRECEITAGUIA     || '|' ||
                                  LPAD(LTRIM(NRPROCESSOGUIA, '0'), 15, '0')          || '|' ||
                                  DECODE(NRPROCESSOGUIA,'','',NVL(IDORIGEMGUIA,'0')) || '|' ||
                                  DSHISTGUIACOMPL   || '|' ||
                                  '' || '|'  ||
                                  TO_CHAR(DTINIPERIODO, 'MMYYYY') || '|' AS ARQ_E116
                             FROM GUIACOMPLMAPA G, MAPAAPURAC M
                            WHERE G.NRSEQUMAPAPU = M.NRSEQUMAPAPU
                              AND M.NRSEQUMAPAPU = C_REGE100.NRSEQUMAPAPU) LOOP
            V_CONTREGE := NVL(V_CONTREGE,0) + 1;
            INSERT INTO ARQMAGNETICO
              (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
              ('55'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE116.ARQ_E116, P_NRSEQARQMAG);
         END LOOP;
      END LOOP;

      /*REGISTRO E200 - ICMS ST*/
      FOR C_REGE200 IN (SELECT '|E200'                             || '|' ||
                               ME.SGESTADO                         || '|' ||
                               TO_CHAR(MP.DTINIPERIODO,'DDMMYYYY') || '|' ||
                               TO_CHAR(MP.DTFIMPERIODO,'DDMMYYYY') || '|'   AS ARQ_E200,
                               ME.NRSEQUMAPAPU, ME.SGESTADO,
                               SUM(ME.VRDEBITONORMAL + ME.VROUTROSDEBITOS) AS VRTOTDEB,
                               SUM(ME.VRCREDITONORMAL + ME.VRCREDANTERIOR + ME.VROUTROSCREDITOS) AS VRTOTCRE
                          FROM MAPAAPURAC MP, MAPAAPURESTADO ME
                         WHERE MP.CDEMPRESA    = P_CDEMPRESA    AND
                               MP.CDINSCESTA   = P_CDINSCESTA   AND
                               MP.DTINIPERIODO = P_DTINICIAL    AND
                               MP.DTFIMPERIODO = P_DTFINAL      AND
                               MP.CDIMPOSTO    = '80'           AND
                               ME.NRSEQUMAPAPU = MP.NRSEQUMAPAPU
                         GROUP BY ME.NRSEQUMAPAPU, ME.SGESTADO,
                                  TO_CHAR(MP.DTINIPERIODO,'DDMMYYYY'),
                                  TO_CHAR(MP.DTFIMPERIODO,'DDMMYYYY')
                         ORDER BY ME.SGESTADO) LOOP

         V_CONTREGE := NVL(V_CONTREGE,0) + 1;
         INSERT INTO ARQMAGNETICO
           (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
           ('56'||LPAD(RTRIM(V_CONTREGE), 7, '0')||'1', C_REGE200.ARQ_E200, P_NRSEQARQMAG);

         V_VROUTRDEB := 0;
         V_VREXTRAPUR:= 0;
         /*busca o valor de débito extra apuração e outros débitos*/
         FOR C_DEBEXT IN(SELECT CASE WHEN SUBSTR(CDAJUSTEAPURSG,3,1) = '1' AND SUBSTR(CDAJUSTEAPURSG,4,1) = '5'
                                     THEN VRAJUSTEAPURSG ELSE 0 END AS VREXTRAAPUR,
                                CASE WHEN SUBSTR(CDAJUSTEAPURSG,3,1) = '1' AND SUBSTR(CDAJUSTEAPURSG,4,1) = '5'
                                     THEN 0 ELSE VRAJUSTEAPURSG END AS VROUTRDEB
                           FROM AJUSTMAPAAPURSG A
                          WHERE A.NRSEQUMAPAPU = C_REGE200.NRSEQUMAPAPU
                            AND A.SGESTADO     = C_REGE200.SGESTADO)LOOP
            V_VROUTRDEB := NVL(V_VROUTRDEB,0 ) + NVL(C_DEBEXT.VROUTRDEB,0  );
            V_VREXTRAPUR:= NVL(V_VREXTRAPUR,0) + NVL(C_DEBEXT.VREXTRAAPUR,0);
         END LOOP;

         V_AJ_DEBITO_DOC_ST := 0;

         /* BUSCA OS VALORES DE AJUSTE A DÉBITO - DOC. FISCAL PRESENTES NA APURAÇÃO,
            DE ACORDO COM O CÓDIGO DE AJUSTE PARA O ICMS ST - SUBSTITUÍDO SOLIDÁRIO */
         SELECT NVL(SUM(VRITEMMAPR),0)
           INTO V_AJ_DEBITO_DOC_ST
           FROM (SELECT NVL(SUM(ROUND(DECODE(SUBSTR(IM.CDAJUSTEITMAPA,3,1),'9',0,DECODE(DT.IDSUBSTSOLIDST,'S',DT.VRIMPOSTOIT,IT.VRIMPOSTOIT)),2) + VALOR_FECP_ITEM_NFE(IT.CDFILIAL, IT.NRLANCTONF,IT.NRSEQITPROD,'80','I','1',IT.NRITPROIMPOS)),0) AS VRITEMMAPR
                   FROM ITMAPARECUP IM, ITEMPROIMPOS IT, IMPOSTO II, DETITMAPARECUP DT, NOTAFISCAL NF, INSCRESTAD IE
                  WHERE IM.NRSEQUMAPAPU = C_REGE200.NRSEQUMAPAPU
                    AND IM.IDCOMPOEC197 = 'I'
                    AND IM.CDFILIAL     = IT.CDFILIAL
                    AND IM.NRLANCTONF   = IT.NRLANCTONF
                    AND IT.CDIMPOSTO    = II.CDIMPOSTO
                    AND II.CDIMPOSTONFE = '80'
                    AND SUBSTR(IM.CDAJUSTEITMAPA,4,1) IN ('1','9')
                    AND IM.NRSEQUMAPAPU = DT.NRSEQUMAPAPU
                    AND IM.IDTIPOITMAPR = DT.IDTIPOITMAPR
                    AND IM.NRSEQITMAPR  = DT.NRSEQITMAPR
                    AND IT.CDFILIAL     = DT.CDFILIAL
                    AND IT.NRLANCTONF   = DT.NRLANCTONF
                    AND IT.NRSEQITPROD  = DT.NRSEQITPROD
                    AND IT.NRITPROIMPOS = DT.NRITPROIMPOS
                    AND SUBSTR(IM.CDAJUSTEITMAPA,3,1) IN ('3','4','5')
                    AND NF.CDFILIAL     = IT.CDFILIAL
                    AND NF.NRLANCTONF   = IT.NRLANCTONF
                    AND NF.CDINSCESTA   = IE.CDINSCESTA
                    AND IE.SGESTADO     = C_REGE200.SGESTADO);

         SELECT '|E210'                                                                                                                           ||'|'||
                DECODE((NVL(C_REGE200.VRTOTDEB,0)+NVL(V_AJ_DEBITO_DOC_ST,0)),0,DECODE(NVL(C_REGE200.VRTOTCRE,0),0,'0','1'),'1')                                               ||'|'|| --INDICADOR DE MOVIMENTO(CAMPO 2)
                REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(ME.VRCREDANTERIOR),2),0),'999999999990.00')),'.',',')                                         ||'|'|| -- SALDO CREDOR PERIDODO ANTERIOR ST(CAMPO 3)
                REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(ME.VRDEVMAPA),2),0),'999999999990.00')),'.',',')                                              ||'|'|| --SALDO CREDOR DE DEVOLUO(CAMPO 4)
                REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(ME.VRRESSAMAPA),2),0),'999999999990.00')),'.',',')                                            ||'|'|| -- VALOR DE RESSARCIMENTO(CAMPO 5)
                REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(ME.VROUTROSCREDITOS+ME.VRCREDITONORMAL),2),0),'999999999990.00')),'.',',')                    ||'|'|| --VALOR DE OUT. CRED. + EST. DEB(CAMPO 6)
                '0,00'                                                                                                                            ||'|'|| --AJUSTE A CREDITO ST DOC. FISCAL(CAMPO 7)
                REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(ME.VRDEBITONORMAL),2),0),'999999999990.00')),'.',',')                                         ||'|'|| --VALOR RETENO ST (CAMPO 8)
                REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(V_VROUTRDEB),2),0),'999999999990.00')),'.',',')                                               ||'|'|| -- VALOR DE OUT. DEB. + ESTORNO CRED. (CAMPO 9)
                REPLACE(LTRIM(TO_CHAR(NVL(V_AJ_DEBITO_DOC_ST,0),'999999999990.00')),'.',',')                                                      ||'|'|| --VALOR AJUSTE A DEB. DOC. FISC(CAMPO 10)
                REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(ME.VRIMPARECOLHER+NVL(V_AJ_DEBITO_DOC_ST,0)-V_VREXTRAPUR),2),0),'999999999990.00')),'.',',')                            ||'|'|| --VALOR SALDO DEB ANT. DEDUES(CAMPO 11)
                REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(DECODE(ME.SGESTADO,V_SGESTADO,MR.VRDEDUCAO,0)),2),0),'999999999990.00')),'.',',')             ||'|'|| -- VALOR DA DEDUCAO(CAMPO 12)
                REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(DECODE(ME.SGESTADO,V_SGESTADO,ME.VRIMPARECOLHER+NVL(V_AJ_DEBITO_DOC_ST,0)-MR.VRDEDUCAO-V_VREXTRAPUR,ME.VRIMPARECOLHER+NVL(V_AJ_DEBITO_DOC_ST,0)-V_VREXTRAPUR)),2),0),'999999999990.00')),'.',',')||'|'|| -- VALOR IMP. RECOLHER (CAMPO 13)
                REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(ME.VRSALDOCREDOR),2),0),'999999999990.00')),'.',',')                                          ||'|'|| --VALOR SALDO CREDOR(CAMPO 14)
                REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(V_VREXTRAPUR),2),0),'999999999990.00')),'.',',')                                              ||'|' --VALOR EXTRA APURAÇÃO(CAMPO 15)
           INTO V_REG_E210
           FROM MAPAAPURAC MP, MAPARECUP MR, MAPAAPURESTADO ME
          WHERE MP.NRSEQUMAPAPU = C_REGE200.NRSEQUMAPAPU AND
                MR.NRSEQUMAPAPU = C_REGE200.NRSEQUMAPAPU AND
                ME.NRSEQUMAPAPU = C_REGE200.NRSEQUMAPAPU AND
                ME.SGESTADO     = C_REGE200.SGESTADO;

         /*INSERTE O REGISTRO E210*/
         V_CONTREGE := NVL(V_CONTREGE,0) + 1;
         INSERT INTO ARQMAGNETICO
            (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
          VALUES
            ('56'||LPAD(RTRIM(V_CONTREGE), 7, '0')||'2',V_REG_E210, P_NRSEQARQMAG);

         FOR C_E220 IN (SELECT '|E220'
                               || '|' || A.CDAJUSTEAPURSG
                               || '|' || A.DSAJUSTEAPURSG
                               || '|' || REPLACE(LTRIM(TO_CHAR(NVL(ROUND(A.VRAJUSTEAPURSG,2),0), '999999999990.00')), '.', ',')
                               || '|' AS E220
                          FROM AJUSTMAPAAPURSG A
                         WHERE A.NRSEQUMAPAPU = C_REGE200.NRSEQUMAPAPU
                           AND A.SGESTADO     = C_REGE200.SGESTADO)LOOP
            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
             VALUES
               ('56'||LPAD(RTRIM(V_CONTREGE), 7, '0')||'3', C_E220.E220, P_NRSEQARQMAG);
            V_CONTREGE := NVL(V_CONTREGE,0) + 1;
         END LOOP;

         FOR C_REGE250 IN (SELECT ARQ_E250
                             FROM (SELECT '|E250'                            || '|' ||
                                          LPAD(NVL(DT.CDOBRIGACAO,'001'),3,'0')        || '|' ||
                                          REPLACE(LTRIM(TO_CHAR(NVL(ROUND(NVL(DT.VRRECEITA,0)+NVL(V_AJ_DEBITO_DOC_ST,0),2),0), '999999999990.00')),'.',',') || '|' ||
                                          TO_CHAR(NVL(DT.DTVENCDET,MP.DTVENCGUIA),'DDMMYYYY')  || '|' ||
                                          NVL(DT.CDRECEITA,MP.CDRECEGUIA)   || '|' ||
                                          DT.NRPROCESSO                     || '|' ||
                                          DT.IDORIGEMDET                    || '|' ||
                                          DT.DSHISTORICO                    || '|' ||
                                          ''                                || '|' ||
                                          TO_CHAR(MP.DTINIPERIODO, 'MMYYYY')|| '|' AS ARQ_E250,
                                          NVL(DT.VRRECEITA,0) + NVL(V_AJ_DEBITO_DOC_ST,0) AS VRGUIA
                                     FROM DETAUFMAPAEST DT, MAPAAPURAC MP
                                    WHERE DT.NRSEQUMAPAPU(+) = C_REGE200.NRSEQUMAPAPU
                                      AND DT.SGESTADO(+)     = C_REGE200.SGESTADO
                                      AND DT.NRSEQUMAPAPU(+) = MP.NRSEQUMAPAPU
                                      AND MP.NRSEQUMAPAPU    = C_REGE200.NRSEQUMAPAPU)
                            WHERE VRGUIA > 0) LOOP
         V_CONTREGE := NVL(V_CONTREGE,0) + 1;
            INSERT INTO ARQMAGNETICO
              (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
              ('56'||LPAD(RTRIM(V_CONTREGE), 7, '0')||'4', C_REGE250.ARQ_E250, P_NRSEQARQMAG);
         END LOOP;
      END LOOP;

      /*REGISTRO E300 - PERÍODO DE APURAÇÃO DO ICMS DIFERENCIAL DE ALÍQUOTA – UF ORIGEM/DESTINO EC 87/15*/
      FOR C_REGE300 IN (SELECT ('|E300'             || '|' ||
                               ME.SGESTADO         || '|' ||
                               TO_CHAR(MP.DTINIPERIODO,'DDMMYYYY') || '|' ||
                               TO_CHAR(MP.DTFIMPERIODO,'DDMMYYYY') || '|') AS ARQ_E300,
                               ME.NRSEQUMAPAPU, ME.NRSEQMAPAPURESTNC
                          FROM MAPAAPURESTADONC ME, MAPAAPURAC MP
                         WHERE MP.CDEMPRESA     = P_CDEMPRESA
                           AND MP.CDINSCESTA    = P_CDINSCESTA
                           AND MP.DTINIPERIODO  = P_DTINICIAL
                           AND MP.DTFIMPERIODO  = P_DTFINAL
                           AND MP.CDIMPOSTO     = P_CDIMPOSTO
                           AND MP.NRSEQUMAPAPU  = ME.NRSEQUMAPAPU) LOOP

         INSERT INTO ARQMAGNETICO
            (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
            ('57'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE300.ARQ_E300, P_NRSEQARQMAG);
         V_CONTREGE := NVL(V_CONTREGE,0) + 1;

         /* BUSCA OS VALORES DE AJUSTE A DÉBITO DE ACORDO COM O CÓDIGO DE AJUSTE */
         V_AJ_DEBITOS_DIFAL := 0;
         V_AJ_DEBITOS_FCP   := 0;
         BEGIN
            SELECT NVL(SUM(DECODE(IT.IDAJUSTENC,'D',IT.VRITEMMAPR,0)),0) AS AJ_DEBITOS_DIFAL,
                   NVL(SUM(DECODE(IT.IDAJUSTENC,'F',IT.VRITEMMAPR,0)),0) AS AJ_DEBITOS_FCP
              INTO V_AJ_DEBITOS_DIFAL, V_AJ_DEBITOS_FCP
              FROM ITMAPARECUPNC IT
             WHERE IT.NRSEQUMAPAPU      = C_REGE300.NRSEQUMAPAPU
               AND IT.NRSEQMAPAPURESTNC = C_REGE300.NRSEQMAPAPURESTNC
               AND IT.IDTIPOITMAPR      IN ('OD', 'EC')
               AND SUBSTR(IT.CDAJUSTEITMAPA,3,1) IN ('2')
               AND SUBSTR(IT.CDAJUSTEITMAPA,4,1) IN ('0','1');
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_AJ_DEBITOS_DIFAL := 0;
               V_AJ_DEBITOS_FCP   := 0;
         END;

         /* BUSCA OS VALORES DE AJUSTE A CRÉDITO DE ACORDO COM O CÓDIGO DE AJUSTE */
         V_AJ_CREDITOS_DIFAL := 0;
         V_AJ_CREDITOS_FCP   := 0;
         BEGIN
            SELECT NVL(SUM(DECODE(IT.IDAJUSTENC,'D',IT.VRITEMMAPR,0)),0) AS AJ_CREDITOS_DIFAL,
                   NVL(SUM(DECODE(IT.IDAJUSTENC,'F',IT.VRITEMMAPR,0)),0) AS AJ_CREDITOS_FCP
              INTO V_AJ_CREDITOS_DIFAL, V_AJ_CREDITOS_FCP
              FROM ITMAPARECUPNC IT
             WHERE IT.NRSEQUMAPAPU      = C_REGE300.NRSEQUMAPAPU
               AND IT.NRSEQMAPAPURESTNC = C_REGE300.NRSEQMAPAPURESTNC
               AND IT.IDTIPOITMAPR      IN ('OC', 'ED')
               AND SUBSTR(IT.CDAJUSTEITMAPA,3,1) IN ('2')
               AND SUBSTR(IT.CDAJUSTEITMAPA,4,1) IN ('2','3');
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_AJ_CREDITOS_DIFAL := 0;
               V_AJ_CREDITOS_FCP   := 0;
         END;

         /* BUSCA OS VALORES DE AJUSTE DE DEDUÇÃO DE ACORDO COM O CÓDIGO DE AJUSTE */
         V_VL_TOT_DED_DIFAL := 0;
         V_VL_TOT_DED_FCP   := 0;
         BEGIN
            SELECT NVL(SUM(DECODE(IT.IDAJUSTENC,'D',IT.VRITEMMAPR,0)),0) AS VL_TOT_DED_DIFAL,
                   NVL(SUM(DECODE(IT.IDAJUSTENC,'F',IT.VRITEMMAPR,0)),0) AS VL_TOT_DED_FCP
              INTO V_VL_TOT_DED_DIFAL, V_VL_TOT_DED_FCP
              FROM ITMAPARECUPNC IT
             WHERE IT.NRSEQUMAPAPU      = C_REGE300.NRSEQUMAPAPU
               AND IT.NRSEQMAPAPURESTNC = C_REGE300.NRSEQMAPAPURESTNC
               AND IT.IDTIPOITMAPR      IN ('DD')
               AND SUBSTR(IT.CDAJUSTEITMAPA,3,1) IN ('2')
               AND SUBSTR(IT.CDAJUSTEITMAPA,4,1) IN ('4');
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_VL_TOT_DED_DIFAL := 0;
               V_VL_TOT_DED_FCP   := 0;
         END;

         /* BUSCA OS VALORES DE DÉBITO ESPECIAL DE ACORDO COM O CÓDIGO DE AJUSTE */
         V_VR_DEB_ESP_DIFAL := 0;
         V_VR_DEB_ESP_FCP   := 0;
         BEGIN
            SELECT NVL(SUM(DECODE(IT.IDAJUSTENC,'D',IT.VRITEMMAPR,0)),0) AS VR_DEB_ESP_DIFAL,
                   NVL(SUM(DECODE(IT.IDAJUSTENC,'F',IT.VRITEMMAPR,0)),0) AS VR_DEB_ESP_FCP
              INTO V_VR_DEB_ESP_DIFAL, V_VR_DEB_ESP_FCP
              FROM ITMAPARECUPNC IT
             WHERE IT.NRSEQUMAPAPU      = C_REGE300.NRSEQUMAPAPU
               AND IT.NRSEQMAPAPURESTNC = C_REGE300.NRSEQMAPAPURESTNC
               AND IT.IDTIPOITMAPR      IN ('OD', 'EC')
               AND SUBSTR(IT.CDAJUSTEITMAPA,3,1) IN ('2')
               AND SUBSTR(IT.CDAJUSTEITMAPA,4,1) IN ('5');
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_VR_DEB_ESP_DIFAL := 0;
               V_VR_DEB_ESP_FCP   := 0;
         END;

         FOR C_REGE310 IN (SELECT '|E310'                                                                            || '|' ||
                                   CASE WHEN MR.VRSALDOCRED > 0 OR MR.VRSALDODEVE > 0 THEN '1' ELSE '0' END           || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRSLDCRANTE, 2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRDEBIDIFAL, 2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(AJ_DEBITOS,   2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRDEBIFCP,   2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRCREDDIFAL, 2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRCREDFCP,   2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(AJ_CREDITOS,  2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(CASE WHEN (MR.VRDEBIDIFAL + AJ_DEBITOS + MR.VRDEBIFCP) - (MR.VRCREDDIFAL + MR.VRCREDFCP + AJ_CREDITOS + MR.VRSLDCRANTE) > 0
                                                                        THEN (MR.VRDEBIDIFAL + AJ_DEBITOS + MR.VRDEBIFCP) - (MR.VRCREDDIFAL + MR.VRCREDFCP + AJ_CREDITOS + MR.VRSLDCRANTE)
                                                                        ELSE 0 END,2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRDEDUCAO,   2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(CASE WHEN (MR.VRDEBIDIFAL + AJ_DEBITOS + MR.VRDEBIFCP) - (MR.VRCREDDIFAL + MR.VRCREDFCP + AJ_CREDITOS + MR.VRSLDCRANTE + MR.VRDEDUCAO) > 0
                                                                        THEN (MR.VRDEBIDIFAL + AJ_DEBITOS + MR.VRDEBIFCP) - (MR.VRCREDDIFAL + MR.VRCREDFCP + AJ_CREDITOS + MR.VRSLDCRANTE + MR.VRDEDUCAO)
                                                                        ELSE 0 END,2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(CASE WHEN (MR.VRCREDDIFAL + MR.VRCREDFCP + AJ_CREDITOS + MR.VRSLDCRANTE + MR.VRDEDUCAO) - (MR.VRDEBIDIFAL + AJ_DEBITOS + MR.VRDEBIFCP) > 0
                                                                        THEN (MR.VRCREDDIFAL + MR.VRCREDFCP + AJ_CREDITOS + MR.VRSLDCRANTE + MR.VRDEDUCAO) - (MR.VRDEBIDIFAL + AJ_DEBITOS + MR.VRDEBIFCP)
                                                                        ELSE 0 END,2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VR_DEB_ESP,   2),0),'999999999990.00')),'.',',') || '|' AS ARQE310
                              FROM (SELECT NVL(M.VRSALDOCREDDIFAL,0) + NVL(M.VRSALDOCREDFCP,0) AS VRSALDOCRED,
                                           NVL(M.VRSALDODEVEDIFAL,0) + NVL(M.VRSALDODEVEFCP,0) AS VRSALDODEVE,
                                           NVL(M.VRSLDCRANTEDIFAL,0) + NVL(M.VRSLDCRANTEFCP,0) AS VRSLDCRANTE,
                                           M.VRDEBIDIFAL, M.VRDEBIFCP, M.VRCREDDIFAL, M.VRCREDFCP,
                                           (V_AJ_DEBITOS_DIFAL + V_AJ_DEBITOS_FCP) AS AJ_DEBITOS,
                                           (V_AJ_CREDITOS_DIFAL + V_AJ_CREDITOS_FCP) AS AJ_CREDITOS,
                                           (M.VRDEDUCAODIFAL + M.VRDEDUCAOFCP) AS VRDEDUCAO,
                                           (V_VR_DEB_ESP_DIFAL + V_VR_DEB_ESP_FCP) AS VR_DEB_ESP
                                      FROM MAPARECUPNC M
                                     WHERE M.NRSEQUMAPAPU      = C_REGE300.NRSEQUMAPAPU
                                       AND M.NRSEQMAPAPURESTNC = C_REGE300.NRSEQMAPAPURESTNC
                                       AND P_DTINICIAL         < TO_DATE('01/01/2017')) MR
                             UNION ALL
                            SELECT '|E310'                                                                                || '|' ||
                                   CASE WHEN MR.VRSALDOCREDDIFAL > 0 OR MR.VRSALDODEVEDIFAL > 0 OR
                                             MR.VRSALDOCREDFCP   > 0 OR MR.VRSALDODEVEFCP   > 0 THEN '1' ELSE '0' END     || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRSLDCRANTEDIFAL,2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRDEBIDIFAL,     2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(V_AJ_DEBITOS_DIFAL, 2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRCREDDIFAL,     2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(V_AJ_CREDITOS_DIFAL,2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(CASE WHEN (MR.VRDEBIDIFAL + V_AJ_DEBITOS_DIFAL) - (MR.VRCREDDIFAL + V_AJ_CREDITOS_DIFAL + MR.VRSLDCRANTEDIFAL) > 0
                                                                        THEN (MR.VRDEBIDIFAL + V_AJ_DEBITOS_DIFAL) - (MR.VRCREDDIFAL + V_AJ_CREDITOS_DIFAL + MR.VRSLDCRANTEDIFAL)
                                                                        ELSE 0 END,    2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRDEDUCAODIFAL,  2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(CASE WHEN (MR.VRDEBIDIFAL + V_AJ_DEBITOS_DIFAL) - (MR.VRCREDDIFAL + V_AJ_CREDITOS_DIFAL + MR.VRSLDCRANTEDIFAL + MR.VRDEDUCAODIFAL) > 0
                                                                        THEN (MR.VRDEBIDIFAL + V_AJ_DEBITOS_DIFAL) - (MR.VRCREDDIFAL + V_AJ_CREDITOS_DIFAL + MR.VRSLDCRANTEDIFAL + MR.VRDEDUCAODIFAL)
                                                                        ELSE 0 END,    2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(CASE WHEN (MR.VRCREDDIFAL + V_AJ_CREDITOS_DIFAL + MR.VRSLDCRANTEDIFAL + MR.VRDEDUCAODIFAL) - (MR.VRDEBIDIFAL + V_AJ_DEBITOS_DIFAL) > 0
                                                                        THEN (MR.VRCREDDIFAL + V_AJ_CREDITOS_DIFAL + MR.VRSLDCRANTEDIFAL + MR.VRDEDUCAODIFAL) - (MR.VRDEBIDIFAL + V_AJ_DEBITOS_DIFAL)
                                                                        ELSE 0 END,    2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(V_VR_DEB_ESP_DIFAL, 2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRSLDCRANTEFCP,  2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRDEBIFCP,       2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(V_AJ_DEBITOS_FCP,   2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRCREDFCP,       2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(V_AJ_CREDITOS_FCP,  2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(CASE WHEN (MR.VRDEBIFCP + V_AJ_DEBITOS_FCP) - (MR.VRCREDFCP + V_AJ_CREDITOS_FCP + MR.VRSLDCRANTEFCP) > 0
                                                                        THEN (MR.VRDEBIFCP + V_AJ_DEBITOS_FCP) - (MR.VRCREDFCP + V_AJ_CREDITOS_FCP + MR.VRSLDCRANTEFCP)
                                                                        ELSE 0 END,    2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(MR.VRDEDUCAOFCP,    2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(CASE WHEN (MR.VRDEBIFCP + V_AJ_DEBITOS_FCP) - (MR.VRCREDFCP + V_AJ_CREDITOS_FCP + MR.VRSLDCRANTEFCP + MR.VRDEDUCAOFCP) > 0
                                                                        THEN (MR.VRDEBIFCP + V_AJ_DEBITOS_FCP) - (MR.VRCREDFCP + V_AJ_CREDITOS_FCP + MR.VRSLDCRANTEFCP + MR.VRDEDUCAOFCP)
                                                                        ELSE 0 END,    2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(CASE WHEN (MR.VRCREDFCP + V_AJ_CREDITOS_FCP + MR.VRSLDCRANTEFCP + MR.VRDEDUCAOFCP) - (MR.VRDEBIFCP + V_AJ_DEBITOS_FCP) > 0
                                                                        THEN (MR.VRCREDFCP + V_AJ_CREDITOS_FCP + MR.VRSLDCRANTEFCP + MR.VRDEDUCAOFCP) - (MR.VRDEBIFCP + V_AJ_DEBITOS_FCP)
                                                                        ELSE 0 END,    2),0),'999999999990.00')),'.',',') || '|' ||
                                   REPLACE(LTRIM(TO_CHAR(NVL(ROUND(V_VR_DEB_ESP_FCP,   2),0),'999999999990.00')),'.',',') || '|' AS ARQE310
                              FROM MAPARECUPNC MR
                             WHERE MR.NRSEQUMAPAPU      = C_REGE300.NRSEQUMAPAPU
                               AND MR.NRSEQMAPAPURESTNC = C_REGE300.NRSEQMAPAPURESTNC
                               AND P_DTINICIAL         >= TO_DATE('01/01/2017')) LOOP

            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('57'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE310.ARQE310, P_NRSEQARQMAG);
            V_CONTREGE := NVL(V_CONTREGE,0) + 1;

            FOR C_REGE311 IN (SELECT '|E311'             || '|' ||
                                     IT.CDAJUSTEITMAPA   || '|' ||
                                     IT.DSITEMMAPR       || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(NVL(ROUND(IT.VRITEMMAPR, 2),0),'999999999990.00')),'.',',') || '|' AS ARQE311,
                                     IT.NRSEQITMAPRECNC
                                FROM ITMAPARECUPNC IT
                               WHERE IT.NRSEQUMAPAPU      = C_REGE300.NRSEQUMAPAPU
                                 AND IT.NRSEQMAPAPURESTNC = C_REGE300.NRSEQMAPAPURESTNC)LOOP

               INSERT INTO ARQMAGNETICO
                  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                  ('57'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE311.ARQE311, P_NRSEQARQMAG);
               V_CONTREGE := NVL(V_CONTREGE,0) + 1;

               FOR C_REGE312 IN (SELECT '|E312'                     || '|' ||
                                        IT.NRDOCARRECAD             || '|' ||
                                        LPAD(IT.NRPROCESSO,15,'0')  || '|' ||
                                        CASE WHEN IT.NRPROCESSO IS NULL THEN '' ELSE IT.IDORIGEMPROC END || '|' ||
                                        IT.DSPROCESSO               || '|' ||
                                        ''                          || '|' AS ARQE312
                                   FROM ITMAPARECUPNC IT
                                  WHERE IT.NRSEQUMAPAPU      = C_REGE300.NRSEQUMAPAPU
                                    AND IT.NRSEQMAPAPURESTNC = C_REGE300.NRSEQMAPAPURESTNC
                                    AND IT.NRSEQITMAPRECNC   = C_REGE311.NRSEQITMAPRECNC
                                    AND (IT.NRDOCARRECAD IS NOT NULL OR IT.NRPROCESSO IS NOT NULL))LOOP

                  INSERT INTO ARQMAGNETICO
                     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                     ('57'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE312.ARQE312, P_NRSEQARQMAG);
                  V_CONTREGE := NVL(V_CONTREGE,0) + 1;
               END LOOP;

               FOR C_REGE313 IN (SELECT '|E313'                          || '|' ||
                                        NF.IDORIGDESTNF||REPLACE(REPLACE(REPLACE(REPLACE(DECODE(NF.IDORIGDESTNF, 'F', NF.CDFORNECED, DECODE(NF.IDORIGDESTNF, 'C', NF.CDCLIENTE , DECODE(NF.IDENTRSAIDOP, 'E', NF.CDFILIEMIT, NF.CDFILIRECE))),'.'),'-'),'/'),' ') || '|' ||
                                        NF.CDMODDOCFISC                  || '|' ||
                                        CASE WHEN LENGTH(NF.NRACESSONFE) = '44' THEN SUBSTR(NRACESSONFE,23,3) ELSE REPLACE(REPLACE(DECODE(NF.IDENTRSAIDOP, 'E', NF.CDSERIEENTR, NF.CDSERIE),'-',''),'.','') END  || '|' ||
                                        ''                               || '|' ||
                                        DECODE(NF.IDENTRSAIDOP,'E',LTRIM(NF.NRNOTAFISC,'0'),DECODE(NF.NRACESSONFE,'',LTRIM(NF.NRNOTAFISC,'0'),LTRIM(NF.NRNOTAFISCALELE,'0'))) || '|' ||
                                        NF.NRACESSONFE                   || '|' ||
                                        TO_CHAR(NF.DTEMISSAO,'DDMMYYYY') || '|' ||
                                        ''                               || '|' ||
                                        REPLACE(LTRIM(TO_CHAR(NVL(ROUND(IT.VRITEMMAPR, 2),0),'999999999990.00')),'.',',') || '|' AS ARQE313
                                   FROM ITMAPARECUPNC IT, NOTAFISCAL NF
                                  WHERE IT.NRSEQUMAPAPU      = C_REGE300.NRSEQUMAPAPU
                                    AND IT.NRSEQMAPAPURESTNC = C_REGE300.NRSEQMAPAPURESTNC
                                    AND IT.NRSEQITMAPRECNC   = C_REGE311.NRSEQITMAPRECNC
                                    AND IT.CDFILIAL          = NF.CDFILIAL
                                    AND IT.NRLANCTONF        = NF.NRLANCTONF)LOOP

                  INSERT INTO ARQMAGNETICO
                     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                     ('57'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE313.ARQE313, P_NRSEQARQMAG);
                  V_CONTREGE := NVL(V_CONTREGE,0) + 1;
               END LOOP;
            END LOOP;

            FOR C_REGE316 IN (SELECT '|E316'                          || '|' ||
                                     LPAD(G.CDOBRIGAGUIA,3,'0')       || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(NVL(ROUND(G.VRRECEITAGUIA, 2),0),'999999999990.00')),'.',',') || '|' ||
                                     TO_CHAR(G.DTVENCGUIA,'DDMMYYYY') || '|' ||
                                     G.CDRECEITAGUIA                  || '|' ||
                                     LPAD(G.NRPROCESSOGUIA,15,'0')    || '|' ||
                                     CASE WHEN G.NRPROCESSOGUIA IS NULL THEN '' ELSE G.IDORIGEMPROC END || '|' ||
                                     G.DSPROCESSOGUIA                 || '|' ||
                                     ''                               || '|' ||
                                     TO_CHAR(P_DTINICIAL,'MMYYYY')    || '|' AS ARQE316
                                FROM GUIAAPURMAPANC G
                               WHERE G.NRSEQUMAPAPU      = C_REGE300.NRSEQUMAPAPU
                                 AND G.NRSEQMAPAPURESTNC = C_REGE300.NRSEQMAPAPURESTNC)LOOP

               INSERT INTO ARQMAGNETICO
                  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                  ('57'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE316.ARQE316, P_NRSEQARQMAG);
               V_CONTREGE := NVL(V_CONTREGE,0) + 1;
            END LOOP;
         END LOOP;
      END LOOP;

      /*REGISTRO DE APURAÇÃO DO IPI*/
      V_EXISTE_IPI := 'N';
      FOR C_REGE510 IN (SELECT '|E510'                                                                                     || '|' ||
                               IT.CDFISCOPERIT                                                                             || '|' ||
                               IT.CDSITUTRIBITNFE                                                                          || '|' ||
                               REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(IT.VRCONTITIMP),2),0), '999999999990.00')), '.', ',')   || '|' ||
                               REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(DECODE(IT.CDFISCALIT,'1',IT.VRBASECALCIT,0)),2),0),'999999999990.00')),'.',',') || '|' ||
                               REPLACE(LTRIM(TO_CHAR(NVL(ROUND(SUM(DECODE(IT.CDFISCALIT,'1',IT.VRIMPOSTOIT, 0)),2),0),'999999999990.00')),'.',',') || '|' AS ARQ_E510
                          FROM ITEMPROIMPOS IT,
                               (SELECT DISTINCT N.NRLANCTONF, N.CDFILIAL, I.CDIMPOSTO
                                  FROM MAPAAPURAC M, NOTAFISCAL N, IMPOSTONF I
                                 WHERE M.CDEMPRESA       = P_CDEMPRESA
                                   AND M.DTINIPERIODO    = P_DTINICIAL
                                   AND M.DTFIMPERIODO    = P_DTFINAL
                                   AND M.CDIMPOSTO       = '10'
                                   AND ((I.NRSEQUMAPAPU  = M.NRSEQUMAPAPU) OR (M.NRSEQUMAPAPU = I.NRSEQMAPOIMP))
                                   AND NVL(I.IDIMPOSTONF,'1') <> '3'
                                   AND N.CDFILIAL        = I.CDFILIAL
                                   AND N.NRLANCTONF      = I.NRLANCTONF
                                   AND N.CDINSCESTA      = P_CDINSCESTA
                                   AND NVL(N.CDSERIE,' ') <> 'ECF'
                                   AND ((N.IDSTATUS = 'A') OR (N.IDSTATUS = 'E'))) N
                         WHERE IT.CDFILIAL = N.CDFILIAL
                           AND IT.NRLANCTONF = N.NRLANCTONF
                           AND IT.CDIMPOSTO = N.CDIMPOSTO
                           AND NVL(IT.NRITPROIMPOS,'1') <> '3'
                         GROUP BY IT.CDFISCOPERIT, IT.CDSITUTRIBITNFE)LOOP
         V_EXISTE_IPI := 'S';
         V_CONTREGE := NVL(V_CONTREGE,0) + 1;
         INSERT INTO ARQMAGNETICO
           (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
           ('59'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE510.ARQ_E510, P_NRSEQARQMAG);
      END LOOP;

      /*REGISTRO E500 - APURAÇÃO IPI*/
      IF V_EXISTE_IPI = 'S' THEN
         FOR C_REGE500 IN (SELECT ('|E500'                          || '|' ||
                                   '0'                              || '|' ||
                                   TO_CHAR(DTINIPERIODO,'DDMMYYYY') || '|' ||
                                   TO_CHAR(DTFIMPERIODO,'DDMMYYYY') || '|'  ) AS ARQ_E500,
                                   TO_CHAR(DTINIPERIODO,'DDMMYYYY') as DTINICIAL,
                                   TO_CHAR(DTFIMPERIODO,'DDMMYYYY') as DTFINAL
                              FROM MAPAAPURAC M, MAPARECUP R
                             WHERE M.CDEMPRESA    = P_CDEMPRESA
                               AND M.CDIMPOSTO    = '10'
                               AND M.DTINIPERIODO = P_DTINICIAL
                               AND M.DTFIMPERIODO = P_DTFINAL
                               AND M.NRSEQUMAPAPU = R.NRSEQUMAPAPU
                               AND (M.CDINSCESTA  = P_CDINSCESTA OR M.CDINSCESTA IS NULL)) LOOP
            V_CONTREGE := NVL(V_CONTREGE,0) + 1;
            INSERT INTO ARQMAGNETICO
              (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
              ('58'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE500.ARQ_E500, P_NRSEQARQMAG);
         END LOOP;

         /*REGISTRO E520*/
         FOR C_REGE520 IN (SELECT ('|E520'                                                                            || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRSLDCRANTE,2),0), '999999999990.00')), '.', ',')  || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRNORMDEBI,2),0), '999999999990.00')), '.', ',')   || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRNORMCRED,2),0), '999999999990.00')), '.', ',')   || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VROUTRDEBI+ VRESTOCRED,2),0), '999999999990.00')), '.', ',')   || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VROUTRCRED+VRESTODEBI,2),0), '999999999990.00')), '.', ',')   || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(NVL(ROUND(VRSALDOCRED,2),0), '999999999990.00')), '.', ',')  || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(NVL(ROUND((VRTOTAIMPOS),2),0), '999999999990.00')), '.', ',')   || '|' ) AS ARQ_E520,
                                  M.NRSEQUMAPAPU
                             FROM MAPAAPURAC M, MAPARECUP R
                            WHERE M.CDEMPRESA    = P_CDEMPRESA
                              AND M.CDIMPOSTO    = '10'
                              AND M.DTINIPERIODO = P_DTINICIAL
                              AND M.DTFIMPERIODO = P_DTFINAL
                              AND (M.CDINSCESTA  = P_CDINSCESTA OR M.CDINSCESTA IS NULL)
                              AND M.NRSEQUMAPAPU = R.NRSEQUMAPAPU) LOOP
            V_CONTREGE := NVL(V_CONTREGE,0) + 1;
            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('60'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE520.ARQ_E520, P_NRSEQARQMAG);
            FOR C_REGE530 IN (SELECT '|E530'                                                                                   ||'|'||
                                     DECODE(IT.IDTIPOITMAPR,'EC','0','ED','1','OD','0','OC','1')                               ||'|'||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(IT.VRITEMMAPR,2),'999999999990.00')),'.',',')                 ||'|'||
                                     SUBSTR(LPAD(TRIM(REPLACE(REPLACE(IT.CDAJUSTEITMAPA,CHR(10),' '),CHR(9),' ')),10,'0'),8,3) ||'|'||
                                     DECODE(IT.NRLANCTONF,'','9','3')                                                           ||'|'||
                                     NF.NRNOTAFISC                                                                             ||'|'||
                                     TRIM(REPLACE(REPLACE(IT.DSITEMMAPR,CHR(10),' '),CHR(9),' '))                              ||'|' AS ARQ_E530,
                                     IT.CDFILIAL, IT.NRLANCTONF, IT.VRITEMMAPR
                                FROM ITMAPARECUP IT, NOTAFISCAL NF
                               WHERE IT.NRSEQUMAPAPU = C_REGE520.NRSEQUMAPAPU
                                 AND IT.CDFILIAL     = NF.CDFILIAL(+)
                                 AND IT.NRLANCTONF   = NF.NRLANCTONF(+)) LOOP

               V_CONTREGE := NVL(V_CONTREGE,0) + 1;
               INSERT INTO ARQMAGNETICO
                  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                  ('60'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE530.ARQ_E530, P_NRSEQARQMAG);

               FOR C_REGC531 IN (SELECT '|E531'                                                                                  || '|' ||
                                        CNPJ                                                                                    || '|' ||
                                        CDMODDOCFISC                                                                            || '|' ||
                                        SERIE                                                                                   || '|' ||
                                        ''                                                                                      || '|' ||
                                        LTRIM(NRNOTAFISC,0)                                                                     || '|' ||
                                        REPLACE(TO_CHAR(DTEMISSAO,'DDMMYYYY'),'/','')                                           || '|' ||
                                        ''                                                                                      || '|' ||
                                        REPLACE(LTRIM(TO_CHAR(NVL(ROUND(C_REGE530.VRITEMMAPR,2),0), '999999999990.00')), '.', ',') || '|' ||
                                        NRACESSONFE  || '|' AS ARQ_E531
                                   FROM (SELECT NF.IDORIGDESTNF||FI.CDFILIAL AS CNPJ,
                                                CDMODDOCFISC,
                                                CASE WHEN IDENTRSAIDOP = 'E' THEN NF.CDSERIEENTR ELSE NF.CDSERIE END AS SERIE,
                                                NF.NRNOTAFISC, NF.DTEMISSAO, NF.NRLANCTONF, NF.CDFILIAL, NF.NRACESSONFE
                                           FROM NOTAFISCAL NF, FILIAL FI
                                          WHERE DECODE(IDENTRSAIDOP,'E',NF.CDFILIEMIT,NF.CDFILIRECE) = FI.CDFILIAL
                                            AND NF.CDEMPRESA  = FI.CDEMPRESA
                                            AND NVL(NF.IDORIGDESTNF,'L') = 'L'
                                            AND NF.NRLANCTONF = C_REGE530.NRLANCTONF
                                            AND NF.CDFILIAL   = C_REGE530.CDFILIAL
                                          UNION
                                         SELECT NF.IDORIGDESTNF||REPLACE(REPLACE(REPLACE(NF.CDCLIENTE,'.',''),'/',''),'-','') AS CNPJ,
                                                NF.CDMODDOCFISC,
                                                CASE WHEN IDENTRSAIDOP = 'E' THEN NF.CDSERIEENTR ELSE NF.CDSERIE END AS SERIE,
                                                NF.NRNOTAFISC, NF.DTEMISSAO, NF.NRLANCTONF, NF.CDFILIAL, NF.NRACESSONFE
                                           FROM CLIENTE CL, NOTAFISCAL NF
                                          WHERE CL.CDCLIENTE  = NF.CDCLIENTE
                                            AND NVL(NF.IDORIGDESTNF,'C') = 'C'
                                            AND NF.NRLANCTONF = C_REGE530.NRLANCTONF
                                            AND NF.CDFILIAL   = C_REGE530.CDFILIAL
                                          UNION
                                         SELECT NF.IDORIGDESTNF||REPLACE(REPLACE(REPLACE(NF.CDFORNECED,'.',''),'/',''),'-','') AS CNPJ,
                                                NF.CDMODDOCFISC,
                                                CASE WHEN IDENTRSAIDOP = 'E' THEN NF.CDSERIEENTR ELSE NF.CDSERIE END AS SERIE,
                                                NF.NRNOTAFISC, NF.DTEMISSAO, NF.NRLANCTONF, NF.CDFILIAL, NF.NRACESSONFE
                                           FROM FORNECEDOR FO, NOTAFISCAL NF
                                          WHERE FO.CDFORNECED = NF.CDFORNECED
                                            AND NVL(NF.IDORIGDESTNF,'F') = 'F'
                                            AND NF.NRLANCTONF = C_REGE530.NRLANCTONF
                                            AND NF.CDFILIAL   = C_REGE530.CDFILIAL)) LOOP

                  V_CONTREGE := NVL(V_CONTREGE,0) + 1;
                  INSERT INTO ARQMAGNETICO
                     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                     ('60'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGC531.ARQ_E531, P_NRSEQARQMAG);
               END LOOP;
            END LOOP;
         END LOOP;
      END IF;
   END IF;

   IF (NVL(P_GERAFORSALE,'N') = 'N')  AND (V_CDSITUCRT <> '3') THEN   /*SIMPLES NACIONAL*/
      FOR C_REGE100 IN (SELECT DISTINCT ('|E100'                   || '|' ||
                               TO_CHAR(DTINIPERIODO,'DDMMYYYY')    || '|' ||
                               TO_CHAR(DTFIMPERIODO,'DDMMYYYY')    || '|'  ) AS ARQ_E100,
                               TO_CHAR(DTINIPERIODO,'DDMMYYYY') as DTINICIAL,
                               TO_CHAR(DTFIMPERIODO,'DDMMYYYY') as DTFINAL,
                               NRSEQUMAPAPU
                          FROM MAPAAPURACSN
                         WHERE CDEMPRESA    = P_CDEMPRESA
                           AND DTINIPERIODO = P_DTINICIAL
                           AND DTFIMPERIODO = P_DTFINAL) LOOP
         V_CONTREGE := NVL(V_CONTREGE,0) + 1;
         INSERT INTO ARQMAGNETICO
           (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
           ('53'||LPAD(RTRIM(V_CONTREGE), 8, '0'), C_REGE100.ARQ_E100, P_NRSEQARQMAG);
         V_CONTREGE := NVL(V_CONTREGE,0) + 1;
         INSERT INTO ARQMAGNETICO
            (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
            ('54'||LPAD(RTRIM(V_CONTREGE), 8, '0'),'|E110|00000000000000|0,00|00000000000000|00000000000000|00000000000000|0,00|00000000000000|00000000000000|00000000000000|00000000000000|00000000000000|00000000000000|00000000000000|00000000000000|', P_NRSEQARQMAG);
      END LOOP;
   END IF;

   /* abertuta do bloco E */
   IF NVL(V_CONTREGE,0) <> 0 THEN
      V_MOVIMENT := 0;
   ELSE
      V_MOVIMENT := 1;
   END IF;
   V_CONTREGE := NVL(V_CONTREGE,0) + 1;
   INSERT INTO ARQMAGNETICO
     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     ('52'||LPAD(RTRIM(V_CONTREGE), 8, '0'), '|E001'|| '|' ||V_MOVIMENT|| '|', P_NRSEQARQMAG);

   /* ENCERRAMENTO DO BLOCO E */
   V_CONTREGE := NVL(V_CONTREGE,0) + 1;
   INSERT INTO ARQMAGNETICO
     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     ('61'||LPAD(RTRIM(V_CONTREGE), 8, '0'), '|E990'|| '|' ||V_CONTREGE|| '|', P_NRSEQARQMAG);
   RETURN(V_CONTREGE);
END;
