IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_EST_NF_ENT_EST_NF_SAI_TRANSF_EXCLUI_PENDENCIA]'))
	DROP TRIGGER [dbo].[TRG_EST_NF_ENT_EST_NF_SAI_TRANSF_EXCLUI_PENDENCIA]
GO
CREATE TRIGGER [dbo].[TRG_EST_NF_ENT_EST_NF_SAI_TRANSF_EXCLUI_PENDENCIA] ON [dbo].[EST_NF_ENT_EST_NF_SAI_TRANSF] FOR INSERT AS

	--Proibe alterao na nota fiscal de sada quando j existe registro da transferncia
	IF EXISTS (SELECT top 1
					t.CD_EMP
					FROM 
						EST_NF_SAI_NF_ENT t INNER JOIN EST_NF_ENT ON
						t.CD_EMP = EST_NF_ENT.CD_EMP AND
						t.CD_FILIAL = EST_NF_ENT.CD_FILIAL AND
						t.CD_NF_ENT = EST_NF_ENT.CD_NF
						INNER JOIN INSERTED s  ON 
						t.CD_FILIAL		= s.CD_FIL_ORIG AND 
						t.CD_EMP		= s.CD_EMP AND 
						t.CD_NF_SAI		= s.CD_NF_SAI
					WHERE
						EST_NF_ENT.STS_NF=0)
	begin
		RAISERROR ('Nota fiscal com entrada devolucao na origem, operacao cancelada.',16, 1);
		RETURN;
	end  

--Exclui pendência de entrada de nota fiscal 
DELETE FROM p FROM EST_NF_SAI_PENDENCIA p WHERE EXISTS
    (SELECT * FROM INSERTED WHERE CD_EMP=p.CD_EMP AND CD_FIL_ORIG=p.CD_FILIAL AND CD_NF_SAI=p.CD_NF)
--Ciencia da operacao
IF NOT EXISTS (SELECT
				P.CD_EMP
			FROM
				EST_NF_ENT_EST_NF_SAI_TRANSF_MANIFESTO_PENDENTE p INNER JOIN INSERTED i ON 
				p.CD_EMP = i.CD_EMP AND
				p.CD_FIL_ORIG = i.CD_FIL_ORIG AND
				p.CD_FIL_DEST = i.CD_FIL_DEST AND
				p.CD_NF_SAI = i.CD_NF_SAI AND
				p.CD_NF_ENT = i.CD_NF_ENT
			WHERE
				P.TIPO_MANIFESTO=0)
begin
	INSERT INTO EST_NF_ENT_EST_NF_SAI_TRANSF_MANIFESTO_PENDENTE
	(CD_EMP,
	CD_FIL_ORIG,
	CD_FIL_DEST,
	CD_NF_SAI,
	CD_NF_ENT,
	TIPO_MANIFESTO,
	DT_CAD)
	SELECT
		CD_EMP,
		CD_FIL_ORIG,
		CD_FIL_DEST,
		CD_NF_SAI,
		CD_NF_ENT,
		0,
		GETDATE()
	FROM
		 INSERTED
end

--Confirmacao da operacao
IF NOT EXISTS (SELECT
				P.CD_EMP
			FROM
				EST_NF_ENT_EST_NF_SAI_TRANSF_MANIFESTO_PENDENTE p INNER JOIN INSERTED i ON 
				p.CD_EMP = i.CD_EMP AND
				p.CD_FIL_ORIG = i.CD_FIL_ORIG AND
				p.CD_FIL_DEST = i.CD_FIL_DEST AND
				p.CD_NF_SAI = i.CD_NF_SAI AND
				p.CD_NF_ENT = i.CD_NF_ENT
			WHERE
				P.TIPO_MANIFESTO=1)
begin
	INSERT INTO EST_NF_ENT_EST_NF_SAI_TRANSF_MANIFESTO_PENDENTE
	(CD_EMP,
	CD_FIL_ORIG,
	CD_FIL_DEST,
	CD_NF_SAI,
	CD_NF_ENT,
	TIPO_MANIFESTO,
	DT_CAD)
	SELECT
		CD_EMP,
		CD_FIL_ORIG,
		CD_FIL_DEST,
		CD_NF_SAI,
		CD_NF_ENT,
		1,
		GETDATE()
		FROM
		 INSERTED

end