IF EXISTS (SELECT  * FROM SYS.TRIGGERS WHERE NAME = 'TRG_PDV_CUPOM_NAO_FISCAL_TEF_INTEGRA_BENNER_PIX')
BEGIN
	DROP TRIGGER TRG_PDV_CUPOM_NAO_FISCAL_TEF_INTEGRA_BENNER_PIX
END 
GO 

CREATE TRIGGER [dbo].[TRG_PDV_CUPOM_NAO_FISCAL_TEF_INTEGRA_BENNER_PIX]
ON 
	[dbo].[PDV_CUPOM_NAO_FISCAL_TEF]
FOR INSERT
AS

INSERT INTO
	INTEGRA_BENNER_EVENTOS (TABELA, CD_EMP, CD_FILIAL, CD_REGISTRO, TP_EVENTO, HR_EVENTO, ST_EVENTO, DT_ULT_ALT, CD_USU, DT_DOCUMENTO, APP_NAME, HOST_NAME, TOPICO)
SELECT 
	TOP 1
	'PDV_RECBTO_TEF' AS TABELA
	, 1 AS CD_EMP
	, I.CD_FILIAL AS CD_FILIAL
	, I.CD_RECTO_TEF AS CD_REGISTRO
	, 1 AS TP_EVENTO
	, GETDATE() AS HR_EVENTO
	, 0 AS ST_EVENTO
	, PV.DT_ULT_ALT AS DT_ULT_ALT
	, PV.CD_USU AS CD_USU
	, GETDATE() AS DT_DOCUMENTO
	, 'TRG_PDV_RECBTO_TEF_INTEGRA_BENNER_PIX - ' + APP_NAME() AS [APP_NAME]
	, HOST_NAME() AS HOST_NAME
	, 4 AS TOPICO
FROM 
	INSERTED I
	INNER JOIN PDV_RECBTO_TEF (NOLOCK) A ON
		I.CD_EMP = A.CD_EMP
		AND I.CD_FILIAL = A.CD_FILIAL
		AND I.CD_RECTO_TEF = A.CD_RECTO_TEF
	INNER JOIN PDV_CUPOM_NAO_FISCAL (NOLOCK) PV ON
		I.CD_EMP = PV.CD_EMP
		AND I.CD_FILIAL = PV.CD_FILIAL
		AND I.CD_CTR = PV.CD_CTR
	INNER JOIN RC_ADM_CARTAO (NOLOCK) RAC ON
		RAC.CD_EMP = A.CD_EMP
		AND A.CD_ADM_CARTAO = RAC.CD_ADM_CARTAO
WHERE
	RAC.TP_ADM = 7
	AND PV.TP_CUPOM_NAO_FISCAL = 3
	AND A.VL_CARTAO > 0
	AND NOT EXISTS (
		SELECT 
			1 
		FROM 
			INTEGRA_BENNER_EVENTOS (NOLOCK) AA 
		WHERE 
			AA.CD_EMP = I.CD_EMP
			AND AA.CD_FILIAL = I.CD_FILIAL
			AND AA.CD_REGISTRO = I.CD_RECTO_TEF
			AND AA.TABELA = 'PDV_RECBTO_TEF');
GO

ALTER TABLE [dbo].[PDV_CUPOM_NAO_FISCAL_TEF] ENABLE TRIGGER [TRG_PDV_CUPOM_NAO_FISCAL_TEF_INTEGRA_BENNER_PIX]
GO


