create or replace FUNCTION ARQUIVO_DMA_CREDITO(
   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_NRSEQARQMAG  IN ARQMAGNETICO.NRSEQARQMAG%TYPE) RETURN NUMBER
   
AS
   V_CONTADOR      NUMBER;
   V_VRENTRADAS    NUMBER;
   V_VRCREDACUMUL  NUMBER;
   V_REGDADOS      VARCHAR2(4000);
   V_REGDADOS2     VARCHAR2(4000);
BEGIN
   V_CONTADOR := 0;
   SELECT '19'||
          TO_CHAR(P_DTINICIAL, 'YYYYMM')||
          LPAD(P_CDINSCESTA, 9, '0')||
          RPAD('0',12,'0')||
          RPAD('0',12,'0')||
          RPAD('0',12,'0')||
          RPAD('0',12,'0')||
          RPAD('0',12,'0')||
          LPAD(LTRIM(REPLACE(TO_CHAR(SUM(DECODE(CDFISCALNF, '2', ROUND(VRCONTABILNF,2), 0)), '9999999999.00'), '.', '')), 12, '0')||
          LPAD(LTRIM(REPLACE(TO_CHAR(SUM(VRPERREDBCNF), '9999999999.00'), '.', '')), 12, '0')
     INTO V_REGDADOS
     FROM MAPAAPURAC M, IMPOSTONF I
   WHERE M.CDEMPRESA    = P_CDEMPRESA
     AND M.CDIMPOSTO    = P_CDIMPOSTO
     AND M.CDINSCESTA   = P_CDINSCESTA
     AND M.DTINIPERIODO = P_DTINICIAL
     AND M.DTFIMPERIODO = P_DTFINAL
     AND M.NRSEQUMAPAPU = I.NRSEQUMAPAPU
     AND SUBSTR(CDFISCOPERNF,1,1) IN ('5','6','7')
     AND CDFISCALNF IN ('2','3');
   V_CONTADOR := NVL(V_CONTADOR, 0)+1;
   INSERT INTO ARQMAGNETICO
      (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
   VALUES
      (V_CONTADOR, V_REGDADOS, P_NRSEQARQMAG);

   /*
   SELECT '20'||
          TO_CHAR(P_DTINICIAL, 'YYYYMM')||
          LPAD(P_CDINSCESTA, 9, '0')||
          LPAD(LTRIM(REPLACE(TO_CHAR(SUM(DECODE(CDFISCALNF, '3', VRCONTABILNF, 0)), '9999999999.00'), '.', '')), 12, '0')||
          LPAD(LTRIM(REPLACE(TO_CHAR(SUM(VRCONTABILNF), '9999999999.00'), '.', '')), 12, '0')||
          RPAD('0',12,'0')||
          RPAD('0',12,'0')||
          RPAD('0',12,'0')||
          RPAD('0',12,'0')
    INTO V_REGDADOS2
    FROM MAPAAPURAC M, IMPOSTONF I
   WHERE M.CDEMPRESA    = P_CDEMPRESA
     AND M.CDIMPOSTO    = P_CDIMPOSTO
     AND M.CDINSCESTA   = P_CDINSCESTA
     AND M.DTINIPERIODO = P_DTINICIAL
     AND M.DTFIMPERIODO = P_DTFINAL
     AND M.NRSEQUMAPAPU = I.NRSEQUMAPAPU
     AND SUBSTR(CDFISCOPERNF,1,1) IN ('5','6','7')
     AND CDFISCALNF IN ('2','3');
   V_CONTADOR := NVL(V_CONTADOR, 0)+1;
   INSERT INTO ARQMAGNETICO
      (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
   VALUES
      (V_CONTADOR, V_REGDADOS2, P_NRSEQARQMAG);
   */   
   RETURN(V_CONTADOR);
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('ARQUIVO_DMA_CREDITO','6.49.010'); END;
/

