IF EXISTS (SELECT * FROM SYS.TRIGGERS WHERE NAME = 'TRG_EST_NF_ENT_NF_SAI_INCLUI_PENDENCIA')
BEGIN
	DROP TRIGGER TRG_EST_NF_ENT_NF_SAI_INCLUI_PENDENCIA
END
GO
GO
GO
-------------------------------------INSERO EM EST_NF_ENT_NF_SAI--------------------------------------
CREATE TRIGGER [dbo].[TRG_EST_NF_ENT_NF_SAI_INCLUI_PENDENCIA] ON [dbo].[EST_NF_ENT_NF_SAI] FOR INSERT AS
--Devolucao de vendas entre grupo economico

IF NOT EXISTS (
	SELECT 
		* 
	FROM
		INSERTED I
		INNER JOIN EST_NF_SAI_PENDENCIA ON
			I.CD_EMP = EST_NF_SAI_PENDENCIA.CD_EMP
			AND I.CD_FILIAL = EST_NF_SAI_PENDENCIA.CD_FILIAL
			AND I.CD_NF_SAI = EST_NF_SAI_PENDENCIA.CD_NF)
BEGIN
	INSERT INTO EST_NF_SAI_PENDENCIA (
		CD_EMP, 
		CD_FILIAL, 
		CD_NF, 
		CD_FILIAL_DEST,
		DT_REGISTRO)
	SELECT
		 DISTINCT INSERTED.CD_EMP,
		 INSERTED.CD_FILIAL,
		 INSERTED.CD_NF_SAI,
		 V_EST_NF_SAI_CAB.CD_FILIAL_CLI,
		 GETDATE()
	FROM
		INSERTED
		INNER JOIN EST_NF_ENT_EST_NF_SAI_TRANSF ON
			INSERTED.CD_EMP = EST_NF_ENT_EST_NF_SAI_TRANSF.CD_EMP AND
			INSERTED.CD_FILIAL =	EST_NF_ENT_EST_NF_SAI_TRANSF.CD_FIL_DEST AND
			INSERTED.CD_NF_ENT= EST_NF_ENT_EST_NF_SAI_TRANSF.CD_NF_ENT
		INNER JOIN V_EST_NF_SAI_CAB ON
			INSERTED.CD_EMP = V_EST_NF_SAI_CAB.CD_EMP AND
			INSERTED.CD_FILIAL = V_EST_NF_SAI_CAB.CD_FILIAL AND
			INSERTED.CD_NF_SAI = V_EST_NF_SAI_CAB.CD_NF

	INSERT INTO EST_NF_SAI_PENDENCIA (
		CD_EMP, 
		CD_FILIAL, 
		CD_NF, 
		CD_FILIAL_DEST,
		DT_REGISTRO)
	SELECT
		 DISTINCT INSERTED.CD_EMP,
		 INSERTED.CD_FILIAL,
		 INSERTED.CD_NF_SAI,
		 V_EST_NF_SAI_CAB.CD_FILIAL_CLI,
		 GETDATE()
	FROM
		INSERTED
		INNER JOIN EST_NF_SAI_PED_VD ON
			INSERTED.CD_EMP = EST_NF_SAI_PED_VD.CD_EMP AND
			INSERTED.CD_FILIAL = EST_NF_SAI_PED_VD.CD_FILIAL AND
			INSERTED.CD_NF_SAI = EST_NF_SAI_PED_VD.CD_NF
		INNER JOIN EST_PED_VD ON
			EST_NF_SAI_PED_VD.CD_EMP = EST_PED_VD.CD_EMP AND
			EST_NF_SAI_PED_VD.CD_FILIAL = EST_PED_VD.CD_FILIAL AND
			EST_NF_SAI_PED_VD.CD_PED = EST_PED_VD.CD_PED
		INNER JOIN V_EST_NF_SAI_CAB ON
			INSERTED.CD_EMP = V_EST_NF_SAI_CAB.CD_EMP AND
			INSERTED.CD_FILIAL = V_EST_NF_SAI_CAB.CD_FILIAL AND
			INSERTED.CD_NF_SAI = V_EST_NF_SAI_CAB.CD_NF
	WHERE
		EST_PED_VD.FLAG_GRAVA_PENDENCIA = 1
		AND NOT EXISTS (
			SELECT
				*
			FROM
				EST_NF_ENT_EST_NF_SAI_TRANSF
			WHERE
				INSERTED.CD_EMP = EST_NF_ENT_EST_NF_SAI_TRANSF.CD_EMP AND
				INSERTED.CD_FILIAL = EST_NF_ENT_EST_NF_SAI_TRANSF.CD_FIL_DEST AND
				INSERTED.CD_NF_ENT= EST_NF_ENT_EST_NF_SAI_TRANSF.CD_NF_ENT)
END

