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

CREATE TRIGGER [dbo].[TRG_PDV_VD_TEF_INTEGRA_BENNER_PIX] ON [dbo].[PDV_VD_TEF]
FOR INSERT
AS
	
DECLARE @DS_HOSTNAME VARCHAR(100) = HOST_NAME()

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_VD'													AS TABELA
	,1														AS CD_EMP
	,I.CD_FILIAL						      					AS CD_FILIAL
	,I.CD_CTR 						        				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_VD_INTEGRA_BENNER_PIX - ' + APP_NAME() 		AS [APP_NAME]
	,@DS_HOSTNAME											AS HOST_NAME
	,4														AS TOPICO

FROM 
	PDV_VD_TEF (NOLOCK) A
	INNER JOIN INSERTED I ON 
		A.CD_EMP = I.CD_EMP
		AND A.CD_FILIAL = I.CD_FILIAL
		AND A.CD_VD = I.CD_VD
		AND A.CD_CTR = I.CD_CTR
	INNER JOIN PDV_VD (NOLOCK) PV ON 
		PV.CD_EMP = I.CD_EMP 
		AND PV.CD_FILIAL = I.CD_FILIAL 
		AND PV.CD_VD = I.CD_VD
	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 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_CTR
			AND AA.TABELA = 'PDV_VD')


GO

