CREATE OR REPLACE FUNCTION ARQUIVO_DACON_R05(
   P_CDEMPRESA              IN EMPRESA.CDEMPRESA%TYPE,
   P_DTINICIO               IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DTFIM                  IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_NRSEQARQMAG            IN ARQMAGNETICO.NRSEQARQMAG%TYPE) RETURN NUMBER

AS
   V_CONTREG05        NUMBER;

BEGIN

 /*----------------------------------TIPO R05A-------------------------------------*/

   FOR C_REG_R05A IN (SELECT (RPAD('R05A',4,' ')                           ||
                              LPAD(P.CDARVPROD,9,'0')                      ||
                              '0000000000'                                 ) AS REG_R05A
                        FROM ITEMPROIMPOS IT, ITEMPRODUTO IP,PRODUTO P,IMPOSTO IM,
                            (SELECT DISTINCT I.CDFILIAL, I.NRLANCTONF
                               FROM IMPOSTONF I, MAPAAPURAC M
                              WHERE M.CDIMPOSTO     = '50'
                                AND M.CDEMPRESA     =  P_CDEMPRESA
                                AND M.DTINIPERIODO  >= P_DTINICIO
                                AND M.DTFIMPERIODO  <= P_DTFIM
                                AND M.NRSEQUMAPAPU  = I.NRSEQUMAPAPU) NOTA
                       WHERE IT.CDFILIAL     = NOTA.CDFILIAL
                         AND IT.NRLANCTONF   = NOTA.NRLANCTONF
                         AND IT.CDIMPOSTO    = IM.CDIMPOSTO
                         AND IM.CDIMPOSTONFE = '50'
                         AND IT.CDFILIAL     = IP.CDFILIAL
                         AND IT.NRLANCTONF   = IP.NRLANCTONF
                         AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                         AND IP.CDPRODUTO    = P.CDPRODUTO
                         AND IT.CDSITUTRIBITNFE = '03') LOOP

      V_CONTREG05 := NVL(V_CONTREG05,0) + 1;

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         ('06'||LPAD(RTRIM(V_CONTREG05), 8, '0'), C_REG_R05A.REG_R05A, P_NRSEQARQMAG);

   END LOOP;

   RETURN(V_CONTREG05);

END;
/