
--SELECT PROD_USO_CONT, * FROM EST_PROD WHERE PROD_USO_CONT = 1
--SELECT * FROM PRC_EMP_CONFIG WHERE CD_CHAVE = 'QTDE_LIMITE_PONTOS_FIDEL'
--SELECT * FROM PRC_EMP_CONFIG WHERE CD_CHAVE = 'QTDE_LIMITE_VD_FIDEL_DIA'
--SELECT * FROM PRC_EMP_CONFIG WHERE CD_CHAVE = 'QTDE_LIMITE_VD_FIDEL_MES'


IF EXISTS( SELECT * FROM SYS.OBJECTS 
			WHERE NAME ='TR_PDV_VD_TELEVENDAS_ETAPA'AND TYPE = 'TR')
BEGIN
	DROP TRIGGER dbo.TR_PDV_VD_TELEVENDAS_ETAPA 
END

GO

SET QUOTED_IDENTIFIER ON
GO


CREATE TRIGGER [dbo].[TR_PDV_VD_TELEVENDAS_ETAPA] ON [dbo].[PDV_VD] FOR INSERT AS
BEGIN 
--Verificando se tem pedido no televendas
IF EXISTS(SELECT
				* 
			  FROM
				INSERTED i				
			  WHERE
				i.NR_PED_TELEVD > 0 AND i.ST_VD <> 1)
BEGIN
--Verificando se a etapa de conferido ta OK
	IF NOT EXISTS(SELECT
					* 
				  FROM
					TELE_ORC_ETAPA t INNER JOIN INSERTED i ON
					t.CD_ORC = i.NR_PED_TELEVD 
				  WHERE
					i.NR_PED_TELEVD > 0
					AND ((t.CD_ETAPAS =3
					AND t.CD_TIPO = 2 ) 
					or (t.CD_ETAPAS = 6
					AND t.CD_TIPO = 1 )
					or (t.CD_ETAPAS = 13
					AND t.CD_TIPO = 0)))
		BEGIN
			INSERT INTO TELE_ORC_ETAPA
				 (CD_ORC
				  ,CD_ETAPAS
				  ,CD_TIPO
				  ,CD_USU
				  ,DTHR_ETAPA
				  ,OBS_ETAPA
				  ,DTHR_DBSQL
				  ,DTHR_FIM
				  ,CD_USU_RESP_INI
				  ,DTHR_INI
				  ,CD_USU_RESP_FIM)
				 SELECT 
					  NR_PED_TELEVD    -- cdigo do pedido
					  , 3
					  , 2
					  , 1      -- cdigo do operador (no mudar)
					  , getdate()
					  , 'Pedido Conferido. Automaticamente'
					  , getdate()
					  , null
					  , null
					  , null
					  , null
				FROM
					INSERTED INNER JOIN TELE_ORC ON
					INSERTED.NR_PED_TELEVD = TELE_ORC.CD_ORC
			
			--Marcando na venda que a etapa foi realizada 
			--pela trigger
			UPDATE
				v
			SET
				v.STS_ORC_PEND_TELEVD=2
			FROM
				PDV_VD v INNER JOIN INSERTED i ON
				v.CD_EMP = i.CD_EMP AND
				v.CD_FILIAL = i.CD_FILIAL AND
				v.CD_VD = i.CD_VD
		END
	END
END


                                            
                                            