CREATE OR REPLACE PROCEDURE FCT_CANC_FATURA_CONTRATO_APU (
    P_NRORG          IN ORGANIZACAO.NRORG%TYPE,
    P_NRSEQCONTRATO  IN FCT_CONTRATO.NRSEQCONTRATO%TYPE,
    P_NRVENCPREVCONT IN FCT_VENCPREVCONT.NRVENCPREVCONT%TYPE,
    P_NRAPURACAO     IN FCT_APURACAO.NRAPURACAO%TYPE)
AS
    V_NRLANCTONF         NOTAFISCAL.NRLANCTONF%TYPE;
    V_CDFILIAL           NOTAFISCAL.CDFILIAL%TYPE;
    V_MAX_NRVENCPREVCONT FCT_VENCPREVCONT.NRVENCPREVCONT%TYPE;
BEGIN
    SELECT MAX(NRVENCPREVCONT)
      INTO V_MAX_NRVENCPREVCONT
      FROM FCT_VENCPREVCONT
     WHERE NRSEQCONTRATO  = P_NRSEQCONTRATO
       AND NRORG          = P_NRORG
       AND IDSITUVENCPREV = 'F';

    -- Se o vencimento passado nao for o ultimo faturado para o contrato, retorna erro
    IF (P_NRVENCPREVCONT <> V_MAX_NRVENCPREVCONT) THEN
        RAISE_APPLICATION_ERROR('-20001', 'VENCIMENTO_NAO_ULTIMO');
    END IF;

    UPDATE FCT_VENCPREVCONT
       SET NRAPURACAO     = NULL,
           IDSITUVENCPREV = 'A',
           VRVENCIMENTO   = 0,
           VRFATURADO     = 0,
           VRFALTAFATURAR = 0
     WHERE NRSEQCONTRATO  = P_NRSEQCONTRATO
       AND NRVENCPREVCONT = P_NRVENCPREVCONT
       AND NRORG          = P_NRORG;

    UPDATE FCT_ITVENCPREVCONT
       SET VRVENCIMENTO   = 0
     WHERE NRSEQCONTRATO  = P_NRSEQCONTRATO
       AND NRVENCPREVCONT = P_NRVENCPREVCONT
       AND NRORG          = P_NRORG;

    -- Exclui o proximo vencimento com a situacao "Pendente para Apuracao"
    FOR C_PROX_VENC IN (
        SELECT NRVENCPREVCONT
          FROM FCT_VENCPREVCONT
         WHERE NRSEQCONTRATO      = P_NRSEQCONTRATO
           AND NRORG              = P_NRORG
           AND IDSITUVENCPREV     = 'A'
           AND TRUNC(DTINICOMPET) > (SELECT TRUNC(DTINICOMPET)
                                       FROM FCT_VENCPREVCONT
                                      WHERE NRSEQCONTRATO  = P_NRSEQCONTRATO
                                        AND NRVENCPREVCONT = P_NRVENCPREVCONT
                                        AND NRORG          = P_NRORG)
    ) LOOP

        DELETE FROM FCT_ITVENCPREVCONT
         WHERE NRSEQCONTRATO  = P_NRSEQCONTRATO
           AND NRVENCPREVCONT = C_PROX_VENC.NRVENCPREVCONT
           AND NRORG          = P_NRORG;

        DELETE FROM FCT_VENCPREVCONT
         WHERE NRSEQCONTRATO  = P_NRSEQCONTRATO
           AND NRVENCPREVCONT = C_PROX_VENC.NRVENCPREVCONT
           AND NRORG          = P_NRORG;

    END LOOP;

    -- Exclui a Nota Fiscal e a Apuracao
    BEGIN
        SELECT NRLANCTONF, CDFILIAL
          INTO V_NRLANCTONF, V_CDFILIAL
          FROM FCT_APURACAO
         WHERE NRAPURACAO = P_NRAPURACAO
           AND NRORG      = P_NRORG;
    EXCEPTION WHEN NO_DATA_FOUND THEN
        V_NRLANCTONF := NULL;
        V_CDFILIAL := NULL;
    END;

    DELETE FROM FCT_APURACAO
     WHERE NRAPURACAO = P_NRAPURACAO
       AND NRORG      = P_NRORG;

    IF (V_NRLANCTONF IS NOT NULL) THEN
        DELETA_NF(V_CDFILIAL, V_NRLANCTONF);
    END IF;

END;