CREATE OR REPLACE PROCEDURE EAM_CANCELAR_ENTRADA(
	P_CDOPERADOR		IN OPERADOR.CDOPERADOR%TYPE,
	P_CDEMPRESA			IN EMPRESA.CDEMPRESA%TYPE,
	P_NRSEQCAPAENTBEM	IN CAPAENTRADABEM.NRSEQCAPAENTBEM%TYPE)
AS

BEGIN
	--584 adqItensParaCancel
	FOR C_ITENSPARACANCEL IN  (SELECT CDEMPRESA, NRSEQCAPAENTBEM, NRSEQITCAPAENT
								 FROM ITCAPAENTRABEM
								WHERE P_CDEMPRESA       = CDEMPRESA
								  AND P_NRSEQCAPAENTBEM = NRSEQCAPAENTBEM)
	LOOP
		--acmDelBemNaoImobilizado
		DELETE
		 FROM BEMATIVO
		WHERE C_ITENSPARACANCEL.CDEMPRESA       = CDEMPRESA
		  AND C_ITENSPARACANCEL.NRSEQCAPAENTBEM = NRSEQCAPAENTBEM
		  AND C_ITENSPARACANCEL.NRSEQITCAPAENT  = NRSEQITCAPAENT;
		  
		--acmUpdItCapaCancel
		UPDATE ITCAPAENTRABEM
           SET ITCAPAENTRABEM.IDBEMITCAPAENT 		= '3'
         WHERE C_ITENSPARACANCEL.CDEMPRESA 			= ITCAPAENTRABEM.CDEMPRESA
           AND C_ITENSPARACANCEL.NRSEQCAPAENTBEM    = ITCAPAENTRABEM.NRSEQCAPAENTBEM
           AND C_ITENSPARACANCEL.NRSEQITCAPAENT		= ITCAPAENTRABEM.NRSEQITCAPAENT
           AND ITCAPAENTRABEM.IDBEMITCAPAENT 		= '5'
           AND NOT EXISTS
             (SELECT DISTINCT BEMATIVO.CDBEMATIVO
                FROM BEMATIVO, OPERACAOBEM
               WHERE BEMATIVO.CDEMPRESA       = ITCAPAENTRABEM.CDEMPRESA
                 AND BEMATIVO.NRSEQCAPAENTBEM = ITCAPAENTRABEM.NRSEQCAPAENTBEM
                 AND BEMATIVO.NRSEQITCAPAENT  = ITCAPAENTRABEM.NRSEQITCAPAENT
                 AND BEMATIVO.CDEMPRESA       = OPERACAOBEM.CDEMPRESA
                 AND BEMATIVO.CDBEMATIVO      = OPERACAOBEM.CDBEMATIVO
                 AND OPERACAOBEM.IDIDENTOPERABEM = '01');
	END LOOP;
	--acmUpdCapaOperaBem
	UPDATE CAPAENTRADABEM
       SET IDSITCAPAENTBEM 		= 1,
           CDOPECANCAPAENT 		= P_CDOPERADOR,
           DTCANCAPAENTBEM 		= SYSDATE
     WHERE P_CDEMPRESA 			= CDEMPRESA
       AND P_NRSEQCAPAENTBEM	= NRSEQCAPAENTBEM;
END;
/