/****** Object:  Trigger [TRG_PDV_VD_NAO_ALTERAR_CUPOM_FISCAL]    Script Date: 03/02/2015 11:45:38 ******/
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_PDV_VD_NAO_ALTERAR_CUPOM_FISCAL]'))
DROP TRIGGER [dbo].[TRG_PDV_VD_NAO_ALTERAR_CUPOM_FISCAL]
GO
GO
GO
GO
GO
-------------------------------------INSERO EM PDV_VD--------------------------------------
CREATE TRIGGER [dbo].[TRG_PDV_VD_NAO_ALTERAR_CUPOM_FISCAL] ON [dbo].[PDV_VD] FOR INSERT, UPDATE AS
DECLARE @DT_MOV DATETIME
IF NOT UPDATE(CD_CLI)
	IF NOT UPDATE(CGC_CPF)
		BEGIN
			SET @DT_MOV=(SELECT
							TOP 1
							DT_VD
						  FROM
							INSERTED)
			IF EXISTS (SELECT 
							TOP 1 PDV_VD_FECHA_MOV.CD_FILIAL
						FROM
							PDV_VD_FECHA_MOV INNER JOIN INSERTED ON
							PDV_VD_FECHA_MOV.CD_EMP = INSERTED.CD_EMP AND
							PDV_VD_FECHA_MOV.CD_FILIAL = INSERTED.CD_FILIAL 
						WHERE
							PDV_VD_FECHA_MOV.DT_MOV = @DT_MOV
							AND PDV_VD_FECHA_MOV.BLQ_ALT_FECHA = 1)
			BEGIN
				RAISERROR ('DATA DO CUPOM COM FECHAMENTO DE CAIXA BLOQUEADO PARA ALTERACAO.',16, 1);
				
				rollback;
			END
		END
		INSERT INTO PDV_CONSLD_VD_MOVIMENTO_REPROCESSAR(CD_EMP,CD_FILIAL,DT_MOV,TIPO_ORIGEM,DT_CAD)
		SELECT DISTINCT
			i.CD_EMP,
			i.CD_FILIAL,
			i.DT_VD,
			'CUPOM FISCAL',
			GETDATE()
		FROM
			INSERTED i LEFT OUTER JOIN PDV_CONSLD_VD_MOVIMENTO_REPROCESSAR p ON
			i.CD_EMP = p.CD_EMP AND
			i.CD_FILIAL = p.CD_FILIAL AND
			i.DT_VD = p.DT_MOV 
		WHERE
			p.DT_MOV IS NULL		