IF NOT OBJECT_ID('TRG_PDV_VD_TEF_CARTAO_CONV_PEND') IS NULL
	BEGIN 
		DROP TRIGGER TRG_PDV_VD_TEF_CARTAO_CONV_PEND  
	END
GO	

CREATE TRIGGER [dbo].[TRG_PDV_VD_TEF_CARTAO_CONV_PEND] ON [dbo].[PDV_VD_TEF] FOR INSERT, UPDATE AS
BEGIN 
	
	IF UPDATE(CD_ADM_CARTAO)
		BEGIN
			INSERT INTO PDV_VD_TEF_CARTAO_CONV_PEND (CD_EMP, CD_FILIAL, CD_VD, CD_CTR)
				SELECT 
					DISTINCT 
					I.CD_EMP, I.CD_FILIAL, I.CD_VD, I.CD_CTR
				FROM INSERTED I
					INNER JOIN PDV_VD V ON 
						I.CD_EMP		= V.CD_EMP
						AND I.CD_FILIAL = V.CD_FILIAL
						AND I.CD_VD		= V.CD_VD
					
				WHERE 
					I.VL_CARTAO > 0
					AND EXISTS (SELECT T.CD_EMP
								FROM RC_ADM_CARTAO_RC_CLI_CONV  T
								WHERE T.CD_EMP		= V.CD_EMP
									AND T.CD_CONV	= V.CD_CONV)
								
					AND NOT EXISTS (SELECT T.CD_EMP
									FROM PDV_VD_TEF_CARTAO_CONV_PEND T
									WHERE T.CD_EMP		= I.CD_EMP
										AND T.CD_FILIAL = I.CD_FILIAL
										AND T.CD_VD		= I.CD_VD
										AND T.CD_CTR	= I.CD_CTR)
		END
							
END


GO


