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

CREATE TRIGGER [dbo].[TRG_BLOQ_EST_NF_ENT_IT_QT_IT_ZERO] ON [dbo].[EST_NF_ENT_IT] 
FOR INSERT 
AS
begin
	IF EXISTS
	(SELECT i.CD_PROD
		FROM
			INSERTED i
			INNER JOIN EST_NF_ENT E ON
				I.CD_EMP = E.CD_EMP AND
				I.CD_NF = E.CD_NF AND
				I.CD_FILIAL = E.CD_FILIAL
			INNER JOIN GLB_MOV_OP O ON
				E.CD_NT_MOV = O.CD_MOV_OP
		WHERE
			O.FLAG_MOV_OP_NFE_CPL = 1 OR O.TP_MOV = 58 )

	Begin
		--NOTA FISCAL COMPLEMENTAR
		RETURN;
	End
	
	IF EXISTS
	(SELECT i.CD_PROD
		FROM
			INSERTED i INNER JOIN EST_NF_ENT E ON
				I.CD_EMP = E.CD_EMP AND
				I.CD_NF = E.CD_NF AND
				I.CD_FILIAL = E.CD_FILIAL
			INNER JOIN GLB_MOV_OP ON
				E.CD_NT_MOV = GLB_MOV_OP.CD_MOV_OP
			INNER JOIN EST_PROD ON
				i.CD_EMP = EST_PROD.CD_EMP AND
				i.CD_PROD = EST_PROD.CD_PROD
		WHERE
			NOT i.QT_IT >0
			AND GLB_MOV_OP.TP_MOV <> 25
			AND ISNULL(EST_PROD.FLAG_ADJUDICACAO , 0) = 0)

	Begin
		RAISERROR ('Produto com quantidade zerada.',16, 1);
		RETURN;
	End

	IF EXISTS
	(SELECT i.CD_PROD
		FROM
			INSERTED i INNER JOIN EST_NF_ENT E ON
				I.CD_EMP = E.CD_EMP AND
				I.CD_NF = E.CD_NF AND
				I.CD_FILIAL = E.CD_FILIAL
			INNER JOIN GLB_MOV_OP ON
				E.CD_NT_MOV = GLB_MOV_OP.CD_MOV_OP
			INNER JOIN EST_PROD ON
				i.CD_EMP = EST_PROD.CD_EMP AND
				i.CD_PROD = EST_PROD.CD_PROD
		WHERE
			NOT i.VLR_PRC_CUSTO >0
			AND GLB_MOV_OP.TP_MOV <> 25
			AND GLB_MOV_OP.CALC_CUSTO_MEDIO = 1
			AND ISNULL(EST_PROD.FLAG_ADJUDICACAO , 0) = 0)
	
	Begin
		RAISERROR ('Produto com preco de custo zerado.',16, 1);
		RETURN;
	End
End
;