DECLARE V_VRPARCELAS  FLOAT;
        V_VRACUMULADO FLOAT;
        V_NRCONTADOR  NUMBER;
        V_NRPARCELAS  NUMBER;
BEGIN
   FOR C IN (
      SELECT C.*, N.CDFILIEMIT
      FROM CONTARECEBER C, NOTAFISCAL N
      WHERE N.CDFILIAL = C.CDFILIAL
        AND N.NRLANCTONF = C.NRLANCTONF
        AND C.DTATUAVENREC >= '01/01/2008'
        AND N.IDSISTEMA <> 'REC')
   LOOP
      DELETE RATCTRECEBER
      WHERE CDFILIAL    = C.CDFILIAL
        AND NRLANCTONF  = C.NRLANCTONF
        AND NRSEQVENREC = C.NRSEQVENREC;

      V_NRCONTADOR  := 1;
      V_NRPARCELAS  := 0;
      V_VRPARCELAS  := 0;
      V_VRACUMULADO := 0;

      SELECT COUNT(*)
      INTO V_NRPARCELAS
      FROM RATTPCTR
      WHERE CDTPCTRECEB = C.CDTPCTRECEB;

      FOR C_RATTPCTR IN (SELECT CDTPCTRECEB, CDCENTCUST,
                                NVL(LTRIM(REPLACE(CDFIRATTPCTR, '----', C.CDFILIEMIT)), C.CDFILIEMIT) AS CDFIRATTPCTR,
                                CDFILIAL, VRPERATTPCTR
                         FROM RATTPCTR
                         WHERE CDTPCTRECEB = C.CDTPCTRECEB) LOOP

         V_VRPARCELAS  := ROUND(C.VRATUAREC * (C_RATTPCTR.VRPERATTPCTR/100),2);
         V_VRACUMULADO := V_VRACUMULADO + V_VRPARCELAS;

         IF V_NRPARCELAS = V_NRCONTADOR THEN
            IF V_VRACUMULADO > C.VRATUAREC THEN
               V_VRPARCELAS := ROUND(V_VRPARCELAS - (ABS(C.VRATUAREC - V_VRACUMULADO)),2);
            ELSE
               IF V_VRACUMULADO < C.VRATUAREC THEN
                  V_VRPARCELAS := ROUND(V_VRPARCELAS + (ABS(C.VRATUAREC - V_VRACUMULADO)),2);
               END IF;
            END IF;
         END IF;

         INSERT INTO RATCTRECEBER
            (CDFILIAL, NRLANCTONF, NRSEQVENREC, NRPARCELAREC,
             CDCENTCUST, CDFIRATCTREC, VRRATCCCTREC)
         VALUES
            (C.CDFILIAL, C.NRLANCTONF, C.NRSEQVENREC, C.NRPARCELAREC,
             C_RATTPCTR.CDCENTCUST, C_RATTPCTR.CDFIRATTPCTR, V_VRPARCELAS);

         V_NRCONTADOR := V_NRCONTADOR + 1;
      END LOOP;
      COMMIT;
   END LOOP;
END;
/
