

IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_EST_NF_ENT_IT_ICMS_ST_EFET]'))
	DROP TRIGGER [dbo].[TRG_EST_NF_ENT_IT_ICMS_ST_EFET]
GO

CREATE TRIGGER [dbo].[TRG_EST_NF_ENT_IT_ICMS_ST_EFET] ON [dbo].[EST_NF_ENT_IT]
FOR INSERT
AS

	DECLARE @SUBS_TRIB_INSERTED INT
	DECLARE @CD_NF_INSERTED INT
	DECLARE @CD_FILIAL_INSERTED INT
	DECLARE @CD_PROD_INSERTED INT

	SELECT @SUBS_TRIB_INSERTED = TRIB.SUBS_TRIB,
		   @CD_NF_INSERTED = IT.CD_NF,
		   @CD_FILIAL_INSERTED = IT.CD_FILIAL,
		   @CD_PROD_INSERTED = IT.CD_PROD
	FROM INSERTED IT
	INNER JOIN EST_TRIB TRIB ON TRIB.CD_TRIB = IT.CD_TRIB;

	IF (@SUBS_TRIB_INSERTED = 1 
		AND NOT EXISTS (SELECT 1 FROM EST_NF_ENT_EF_NF_CTR_NF EST WHERE EST.CD_NF_ENT = @CD_NF_INSERTED AND EST.CD_FILIAL = @CD_FILIAL_INSERTED)
		)
	BEGIN
		
		IF NOT EXISTS (SELECT 1 FROM [EST_NF_ENT_IT_ICMS_ST_EFET] WHERE CD_PROD = @CD_PROD_INSERTED AND CD_FILIAL = @CD_FILIAL_INSERTED)
		BEGIN
			INSERT INTO [EST_NF_ENT_IT_ICMS_ST_EFET]
			(CD_EMP, 
			 CD_FILIAL, 
			 CD_NF, 
			 CD_PROD
			)
			SELECT CD_EMP, 
				   CD_FILIAL, 
				   CD_NF, 
				   CD_PROD
			FROM INSERTED IT;
		END
		ELSE
		BEGIN
			UPDATE [EST_NF_ENT_IT_ICMS_ST_EFET]
			SET CD_NF = @CD_NF_INSERTED
			WHERE CD_PROD = @CD_PROD_INSERTED 
				  AND CD_FILIAL = @CD_FILIAL_INSERTED
		END

		/*Forçar o produto a descer para a carga*/
		UPDATE EST_PROD_CPL
		SET CD_EMP = 1
		WHERE CD_PROD = @CD_PROD_INSERTED
		AND CD_FILIAL = @CD_FILIAL_INSERTED
	
	END


GO

ALTER TABLE [dbo].[EST_NF_ENT_IT] ENABLE TRIGGER [TRG_EST_NF_ENT_IT_ICMS_ST_EFET]
GO

