/****** Object:  Trigger [TRG_EST_PED_VD_INCLUI_PENDENCIA]    Script Date: 21/07/2014 14:34:01 ******/
IF EXISTS(SELECT NAME FROM SYS.TRIGGERS WHERE NAME = 'TRG_EST_PED_VD_INCLUI_PENDENCIA')
BEGIN
	DROP TRIGGER [dbo].[TRG_EST_PED_VD_INCLUI_PENDENCIA]
END
GO
GO
--------------------------------------INSERCAO EM EST_PED_VD--------------------------------------
CREATE TRIGGER [dbo].[TRG_EST_PED_VD_INCLUI_PENDENCIA] ON [dbo].[EST_PED_VD] FOR INSERT AS
DELETE FROM p FROM EST_PED_VD_PENDENCIA p WHERE EXISTS
    (SELECT * FROM INSERTED 
     WHERE CD_EMP=p.CD_EMP AND CD_FILIAL=p.CD_FILIAL AND CD_PED=p.CD_PED)

--Pendencia de entrada pre-faturas transferencias (SEPARADO NO ESTOQUE)
INSERT INTO EST_PED_VD_PENDENCIA (
		CD_EMP, 
		CD_FILIAL, 
		CD_PED, 
		CD_FILIAL_DEST,
		FLAG_REALIZAR_FAT)
	SELECT 
		p.CD_EMP, 
		p.CD_FILIAL, 
		p.CD_PED, 
		CASE WHEN O.DEST_ORIG=2 THEN
			 P.CD_CLI
		ELSE 
			ISNULL(PRC_FILIAL_RC_CLI.CD_FILIAL, P.CD_CLI) END CD_DEST,
		ISNULL(p.FLAG_REALIZAR_FAT,0)
    FROM 
		INSERTED p 
		INNER JOIN GLB_MOV_OP O ON
		P.CD_NT_MOV = O.CD_MOV_OP

		LEFT OUTER JOIN (SELECT A.CD_FILIAL,
							    A.CD_CLI
						   FROM PRC_FILIAL_RC_CLI A 
								LEFT JOIN EF_NF_CTR_NR_COMPARTILHADO B ON A.CD_EMP     = B.CD_EMP   
																	  AND A.CD_FILIAL = B.CD_FILIAL  
						  WHERE   ISNULL (B.FILIAL_PADRAO,1) = 1
						  ) PRC_FILIAL_RC_CLI ON p.CD_CLI = PRC_FILIAL_RC_CLI.CD_CLI
		
		
	WHERE 
		p.STS_PED <> 2
		AND NOT EXISTS (SELECT 
							* 
						FROM 
							EST_NF_SAI_PED_VD
						WHERE 
							p.CD_EMP=CD_EMP AND 
							p.CD_FILIAL=CD_FILIAL AND 
							p.CD_PED=CD_PED)
		AND NOT EXISTS (SELECT 
								* 
							FROM 
								EST_NF_ENT_PED_VD
						  WHERE 
								p.CD_EMP=CD_EMP AND 
								p.CD_FILIAL=CD_FILIAL AND 
								p.CD_PED=CD_PED);