CREATE OR REPLACE FUNCTION ARQUIVO_GIM_RN_08(
   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,
   P_CONTADOR     IN NUMBER) RETURN VARCHAR
AS
   V_DADOS          VARCHAR2(4000);
   V_CONTADOR       NUMBER;
   V_CDIMPOSTRIB    VARCHAR2(02);

BEGIN
   V_CONTADOR := P_CONTADOR;

   V_CDIMPOSTRIB := '80';

   SELECT LPAD(REPLACE(LTRIM(TO_CHAR(ROUND(NVL(SUM(I.VRCONTABILNF),'0'),2), '999999999990.00')), '.', ''), 14, '0')||
          LPAD(REPLACE(LTRIM(TO_CHAR(ROUND(NVL(SUM(I.VRBASECALCNF),'0'),2), '999999999990.00')), '.', ''), 14, '0')||
          LPAD(REPLACE(LTRIM(TO_CHAR(ROUND(NVL(SUM(I.VRIMPOSTONF),'0'),2), '999999999990.00')), '.', ''), 14, '0')||
          LPAD(REPLACE(LTRIM(TO_CHAR(ROUND(NVL(SUM(VALOR_IMPOSTO_NFE(I.CDFILIAL, I.NRLANCTONF, V_CDIMPOSTRIB, 'C')),'0'),2), '999999999990.00')), '.', ''), 14, '0')
   INTO V_DADOS
   FROM IMPOSTONF I, MAPAAPURAC M
   WHERE M.CDEMPRESA = P_CDEMPRESA
     AND M.CDINSCESTA = P_CDINSCESTA
     AND M.DTINIPERIODO = P_DTINICIAL
     AND M.DTFIMPERIODO = P_DTFINAL
     AND M.CDIMPOSTO = P_CDIMPOSTO
     AND SUBSTR(I.CDFISCOPERNF,1,1) = '7'
     AND I.IDIMPOSTONF <> '3'
     AND I.NRSEQUMAPAPU = M.NRSEQUMAPAPU;

   IF V_DADOS IS NOT NULL THEN
      V_CONTADOR := NVL(V_CONTADOR,0)+1;
      INSERT INTO ARQMAGNETICO
        (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        (RPAD('08',10,'0'), V_DADOS, P_NRSEQARQMAG);
   END IF;

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

-- VERSAO --
BEGIN ATUVEROBJ('ARQUIVO_GIM_RN_08','5.05.024'); END;
/

