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


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE TRIGGER [dbo].[TRG_PDV_VD_IT_EST_SNGPC_PENDENTE] ON [dbo].[PDV_VD_IT] FOR  INSERT AS
BEGIN
	--TESTANDO SE O CUPOM FISCAL JÁ ESTA EM PENDENCIA DE
	--LANCAMENTO DO SNGPC
	IF NOT EXISTS (SELECT 
						* 
				    FROM 
						PDV_VD_IT_EST_SNGPC_PENDENTE S INNER JOIN INSERTED I ON
						S.CD_EMP    = I.CD_EMP AND
						S.CD_FILIAL = I.CD_FILIAL AND
						S.CD_VD     = I.CD_VD AND
						S.CD_IT     = I.CD_IT)	
	BEGIN
		--PEDENCIA DE LANCAMENTO SNGPC
		INSERT INTO PDV_VD_IT_EST_SNGPC_PENDENTE
			SELECT 
				I.CD_EMP, 
				I.CD_FILIAL,
				I.CD_VD,
				I.CD_IT,
				GETDATE()
			FROM 
				INSERTED I INNER JOIN EST_PROD P ON
				I.CD_EMP = P.CD_EMP AND
				I.CD_PROD = P.CD_PROD
			WHERE
				p.CONTROLE_SNGPC = 1 OR
				p.FLAG_PRODUTO_CONTROLADO = 1 OR
				P.ANTIBIOTICO=1
	END
END

GO
