IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_PDV_VD_NAO_ALTERAR_CUPOM_FISCAL]'))
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
			WHERE				    
				NOT i.QT_IT >0
				AND GLB_MOV_OP.TP_MOV <> 25)

		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
			WHERE				    
				NOT i.VLR_PRC_CUSTO >0
				AND GLB_MOV_OP.TP_MOV <> 25
				AND GLB_MOV_OP.CALC_CUSTO_MEDIO = 1)
		Begin
			RAISERROR ('Produto com preco de custo zerado.',16, 1); 
			RETURN;		
		End
End

GO
