create or replace PROCEDURE RATEIO_PARTIDA(
    P_CDEMPRESA   IN EMPRESA.CDEMPRESA%TYPE,
    P_CDLOTE      IN CAPALOTE.CDLOTE%TYPE,
    P_DTMOVI      IN DATE,
    P_NRLANCLOTE  IN LANCLOTE.NRLANCLOTE%TYPE, 
    P_CDFILIAL     IN FILIAL.CDFILIAL%TYPE,
    P_CDCENTCUST  IN CENTCUST.CDCENTCUST%TYPE,
    P_VRRATECCUS IN RATECCUS.VRRATECCUS%TYPE)
IS
    V_RATEEXISTE FLOAT;    
    V_MAXSEQLANCLOTE VARCHAR2(05);
    V_IDCONTCCUS VARCHAR2(01);
    V_CDCONTCTBL VARCHAR2(20);
    V_IDCONTGERE VARCHAR2(1);
BEGIN
   IF P_CDCENTCUST IS NOT NULL THEN
       BEGIN
          SELECT MAX(NRSEQLANLOTE)
            INTO V_MAXSEQLANCLOTE
            FROM LANCLOTE
           WHERE CDEMPRESA = P_CDEMPRESA
             AND CDLOTE = P_CDLOTE
             AND NRLANCLOTE = P_NRLANCLOTE;
       EXCEPTION
          WHEN NO_DATA_FOUND THEN
           V_MAXSEQLANCLOTE := NULL;
       END;

       BEGIN
          SELECT L.CDCONTCTBL, C.IDCONTCCUS
            INTO V_CDCONTCTBL, V_IDCONTCCUS
            FROM LANCLOTE L, CONTCTBL C
           WHERE CDEMPRESA = P_CDEMPRESA
             AND CDLOTE = P_CDLOTE
             AND NRLANCLOTE = P_NRLANCLOTE
             AND NRSEQLANLOTE = V_MAXSEQLANCLOTE
             AND C.CDCONTCTBL = L.CDCONTCTBL;
       EXCEPTION
         WHEN NO_DATA_FOUND THEN
          V_CDCONTCTBL := NULL;
          V_IDCONTCCUS := NULL;
       END;

       BEGIN
          SELECT IDCONTGERE
            INTO V_IDCONTGERE
            FROM CONTOPECTBL
           WHERE CDEMPRESA = P_CDEMPRESA;
       EXCEPTION
        WHEN NO_DATA_FOUND THEN
         V_IDCONTGERE := NULL;
       END;

       IF V_IDCONTGERE = 'S' THEN
          IF V_IDCONTCCUS <> 'O' THEN

             SELECT COUNT(*)
               INTO V_RATEEXISTE
               FROM RATECCUS
              WHERE CDEMPRESA = P_CDEMPRESA
                AND CDLOTE = P_CDLOTE
                AND NRLANCLOTE = P_NRLANCLOTE
                AND NRSEQLANLOTE = V_MAXSEQLANCLOTE
                AND CDFILIAL = P_CDFILIAL
                AND CDCENTCUST = P_CDCENTCUST;

             IF V_MAXSEQLANCLOTE IS NOT NULL THEN
                IF V_RATEEXISTE = 1 THEN

                     UPDATE RATECCUS SET VRRATECCUS = VRRATECCUS + P_VRRATECCUS
                      WHERE CDEMPRESA = P_CDEMPRESA
                        AND CDLOTE = P_CDLOTE
                        AND NRLANCLOTE = P_NRLANCLOTE
                        AND NRSEQLANLOTE = V_MAXSEQLANCLOTE
                        AND CDFILIAL = P_CDFILIAL
                        AND CDCENTCUST = P_CDCENTCUST;
                ELSE
                     INSERT INTO RATECCUS
                        (CDEMPRESA, CDLOTE, NRLANCLOTE, NRSEQLANLOTE, CDFILIAL, CDCENTCUST, VRRATECCUS, DTCOMPRATECCUS)
                     VALUES
                        (P_CDEMPRESA, P_CDLOTE, P_NRLANCLOTE, V_MAXSEQLANCLOTE, P_CDFILIAL, P_CDCENTCUST, P_VRRATECCUS, P_DTMOVI);
                END IF;
             END IF;
          END IF;
       END IF;
   END IF;
END;
/