CREATE OR REPLACE PROCEDURE ARQITENS_NFES_4101(
   P_CDEMPRESA    IN EMPRESA.CDEMPRESA%TYPE,
   P_NRINSJURFILI IN FILIAL.NRINSJURFILI%TYPE,
   P_CDIMPOSTO    IN IMPOSTONF.CDIMPOSTO%TYPE,
   P_DTINICIAL    IN NOTAFISCAL.DTEMISSAO%TYPE,
   P_DTFINAL      IN NOTAFISCAL.DTEMISSAO%TYPE,
   P_NRSEQARQMAG  IN ARQMAGNETICO.NRSEQARQMAG%TYPE)
AS
   DADOSPIS     VARCHAR(100);
   DADOSCOFINS  VARCHAR(100);
BEGIN

   FOR C_NOTAS_MAPA IN (SELECT SUBSTR(TP.CDCAMPO1,2,24) || SUBSTR(LPAD(IT.NRSEQITPROD, 4, 0), 2, 3) AS CORPONF,
                               IT.NRLANCTONF, IT.CDFILIAL, IT.NRSEQITPROD, TP.CDCAMPO2
                          FROM TMP_REGDADOS_IN86 TP, ITEMPRODUTO IT
                         WHERE TP.CDREGISTRO = '431'
                           AND TP.CDCAMPO3 = 'S'
                           AND IT.CDFILIAL = SUBSTR(TP.CDCHAVEREG,1,4)
                           AND IT.NRLANCTONF = SUBSTR(TP.CDCHAVEREG,5,10)
                         ORDER BY IT.CDFILIAL, IT.NRLANCTONF, IT.NRSEQITPROD)LOOP
       DADOSPIS:=NULL;
       DADOSCOFINS:=NULL;
       BEGIN
          SELECT LPAD(NVL(IT.CDSITUTRIBITNFE,' '),2,' ')||
                 LTRIM(REPLACE(TO_CHAR(NVL(IT.VRALIQITEM,0),'0000.00'),'.'))||'00'||
                 LTRIM(REPLACE(TO_CHAR(NVL(IT.VRBASECALCIT,0),'00000000000000.00'),'.'))||'0'||
                 LTRIM(REPLACE(TO_CHAR(NVL(IT.VRIMPOSTOIT,0),'000000000000000.00'),'.'))
            INTO DADOSPIS
            FROM ITEMPROIMPOS IT, IMPOSTO I
           WHERE I.CDIMPOSTONFE = '50'
             AND I.CDIMPOSTO   = IT.CDIMPOSTO
             AND NRLANCTONF    = C_NOTAS_MAPA.NRLANCTONF
             AND CDFILIAL      = C_NOTAS_MAPA.CDFILIAL
             AND NRSEQITPROD   = C_NOTAS_MAPA.NRSEQITPROD
             AND NRITPROIMPOS  = '1';
       EXCEPTION
          WHEN NO_DATA_FOUND THEN
             DADOSPIS:= '08'||LPAD('0',42,'0');
       END;

       BEGIN
          SELECT LPAD(NVL(IT.CDSITUTRIBITNFE,' '),2,' ')||
                 LTRIM(REPLACE(TO_CHAR(NVL(VRALIQITEM,0),'0000.00'),'.'))||'00'||
                 LTRIM(REPLACE(TO_CHAR(NVL(VRBASECALCIT,0),'00000000000000.00'),'.'))||'0'||
                 LTRIM(REPLACE(TO_CHAR(NVL(VRIMPOSTOIT,0),'000000000000000.00'),'.'))
            INTO DADOSCOFINS
            FROM ITEMPROIMPOS IT, IMPOSTO I
           WHERE I.CDIMPOSTONFE = '60'
             AND I.CDIMPOSTO    = IT.CDIMPOSTO
             AND NRLANCTONF    = C_NOTAS_MAPA.NRLANCTONF
             AND CDFILIAL      = C_NOTAS_MAPA.CDFILIAL
             AND NRSEQITPROD   = C_NOTAS_MAPA.NRSEQITPROD
             AND NRITPROIMPOS  = '1';
       EXCEPTION
          WHEN NO_DATA_FOUND THEN
             DADOSCOFINS:= '08'||LPAD('0',42,'0');
       END;
       INSERT INTO ARQMAGNETICO
        (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES('01'||LPAD(RTRIM('0'), 7, '0')||'1',C_NOTAS_MAPA.CORPONF||DADOSPIS||DADOSCOFINS||C_NOTAS_MAPA.CDCAMPO2,P_NRSEQARQMAG);
   END LOOP;
END;
/
-- VERSAO --
BEGIN ATUVEROBJ('ARQITENS_NFES_4101','5.33.xxx'); END;
/