CREATE OR REPLACE FUNCTION ARQUIVO_GIA_MS_52(
   P_CDEMPRESA   IN EMPRESA.CDEMPRESA%TYPE,
   P_CDINSCESTA  IN NOTAFISCAL.CDINSCESTA%TYPE,
   P_CDIMPOSTO   IN IMPOSTO.CDIMPOSTO%TYPE,
   P_DTINICIAL   IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DTFINAL     IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_TPDEC       IN VARCHAR,
   P_PDEC        IN VARCHAR,
   P_CONTADOR    IN VARCHAR,
   P_SEQMAGNET   IN VARCHAR)
RETURN VARCHAR
AS
   V_CONTADOR            NUMBER;
   V_INSERT              VARCHAR2(100);
   V_MESINI              VARCHAR2(2);
BEGIN
   V_CONTADOR := NVL(P_CONTADOR,0);

   IF P_PDEC = '2' THEN
      V_MESINI := '00';                         
   ELSE
      V_MESINI := TO_CHAR(P_DTINICIAL,'MM');
   END IF;


   V_INSERT := SUBSTR(RPAD(REPLACE(REPLACE(REPLACE(NVL(P_CDINSCESTA, ' '),'.',''),'-',''),'ISENT','ISENTO'),9,' '),1,9)
               ||TO_CHAR(P_DTINICIAL,'YYYY')
               ||V_MESINI
               ||TO_CHAR(P_DTFINAL,'MM')
               ||P_TPDEC
               ||'52';

   FOR C_REGISTRO_52 IN(
      SELECT LPAD(NVL(SUBSTR(I.NRSEQITMAPR,9,2),0),2,'0')
             ||LPAD(REPLACE(LTRIM(TO_CHAR(ROUND(NVL(SUM(I.VRITEMMAPR),0),2),'9999999999990.00')),'.',''),15,0) AS REGISTRO_52
        FROM MAPAAPURAC M ,ITMAPARECUP I
       WHERE M.CDEMPRESA = P_CDEMPRESA
         AND M.CDINSCESTA = P_CDINSCESTA
         AND M.CDIMPOSTO = P_CDIMPOSTO
         AND M.DTINIPERIODO >= P_DTINICIAL
         AND M.DTFIMPERIODO <= P_DTFINAL
         AND M.NRSEQUMAPAPU = I.NRSEQUMAPAPU
         AND I.IDTIPOITMAPR = 'DD'
         AND SUBSTR(I.NRSEQITMAPR,9,2) IN ('51','52','53','54','55','56','57','58','59','60')
       GROUP BY I.NRSEQITMAPR) LOOP

      V_CONTADOR := NVL(V_CONTADOR,0)+1;
      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
         (LPAD(V_CONTADOR, 10, '0'),V_INSERT||C_REGISTRO_52.REGISTRO_52,P_SEQMAGNET);

   END LOOP;

RETURN (TO_CHAR(LPAD(V_CONTADOR, 10, '0')));
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('ARQUIVO_GIA_MS_52','5.30.000'); END;
/

