CREATE OR REPLACE PROCEDURE APAGA_DEVOLVENDAANTECIPADA
(
	P_NRDEVOLVENDAANTEC IN NUMBER,
	P_CDOPERADOR IN VARCHAR2,
	P_NRORG IN NUMBER,
	P_ERRO OUT VARCHAR2
)
AS
	V_CDFILIAL VARCHAR2(4);
	V_CDCLIENTE VARCHAR2(21);
	V_DTINICIAL DATE;
	V_DTFINAL DATE;
	V_NRAPURACFAT VARCHAR2(10);
	V_IDBLOQUEADO VARCHAR2(1);
	V_IDSTATUS VARCHAR2(1);
	V_IDSTATUSNFE VARCHAR2(1);
BEGIN
	SELECT MAX(CDFILIAL), MAX(NRAPURACFAT), MAX(CDCLIENTE)
	  INTO V_CDFILIAL, V_NRAPURACFAT, V_CDCLIENTE
	  FROM DEVOLVENDAANTEC
	 WHERE NRDEVOLVENDAANTEC = P_NRDEVOLVENDAANTEC;

	IF V_CDFILIAL IS NULL THEN
		RETURN;
	END IF;

	-- Verifica o status das notas fiscais
	FOR CURS_NF IN (SELECT CDFILIAL, NRLANCTONF, IDBLOQUEADO, IDSTATUS, IDSTATUSNFE
                     FROM NOTAFISCAL
                    WHERE CDFILIAL = V_CDFILIAL AND
                          NRAPURACFAT = V_NRAPURACFAT) LOOP

		IF CURS_NF.IDBLOQUEADO = 'S' THEN
			P_ERRO := 'NF_DEVOL_BLOQUEADA';
		END IF;
		-- 
		IF CURS_NF.IDSTATUS IN ('E', 'A') THEN
			P_ERRO := 'NF_DEVOL_EMITIDA_APROVADA';
		END IF;

		-- Nota fiscal denegada
		IF CURS_NF.IDSTATUS IN ('C') THEN
			P_ERRO := 'NF_DEVOL_CANCELADA';
		END IF;

		-- Nota fiscal transmitida
		IF CURS_NF.IDSTATUSNFE IN ('A','T','D') THEN
			P_ERRO := 'NF_DEVOL_TRANSMITIDA';
		END IF;

		IF P_ERRO IS NULL THEN
      	DELETA_NF(CURS_NF.CDFILIAL, CURS_NF.NRLANCTONF);
      ELSE
      	RETURN;
      END IF;

      
   END LOOP;	

	IF P_ERRO IS NULL THEN	
		

		DELETE FROM DEVOLVENDAANTEC
		 WHERE NRDEVOLVENDAANTEC = P_NRDEVOLVENDAANTEC;

		DELETE FROM CTRLAPURFAT
		 WHERE CDFILIAL = V_CDFILIAL
		   AND NRAPURACFAT = V_NRAPURACFAT;
	END IF;
END;
/

