/****** Object:  Trigger [TRG_EST_NF_ENT_DAR_IT_CUSTO_EXCLUSAO_PROCESSAMENTO_PENDENTE]    Script Date: 30/04/15 11:46:53 ******/
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_EST_NF_ENT_DAR_IT_CUSTO_EXCLUSAO_PROCESSAMENTO_PENDENTE]'))
DROP TRIGGER [dbo].[TRG_EST_NF_ENT_DAR_IT_CUSTO_EXCLUSAO_PROCESSAMENTO_PENDENTE]
GO
GO

--Versao 2700
CREATE TRIGGER [dbo].[TRG_EST_NF_ENT_DAR_IT_CUSTO_EXCLUSAO_PROCESSAMENTO_PENDENTE] ON [dbo].[EST_NF_ENT_DAR_IT] 
FOR DELETE
AS

UPDATE
	p
SET 
	p.DT_PROC=e.DT_ENT,
	p.DT_CAD=GETDATE()
FROM
	EST_PROD_CPL_CUSTO_MEDIO_PROCESSAMENTO_PENDENTE p 
	INNER JOIN DELETED i ON
	p.CD_EMP = i.CD_EMP AND
	p.CD_FILIAL = i.CD_FILIAL AND
	p.CD_PROD = i.CD_PROD		
	INNER JOIN EST_NF_ENT e ON
	i.CD_EMP = e.CD_EMP AND 
	i.CD_FILIAL = e.CD_FILIAL AND
	i.CD_NF = e.CD_NF 
	INNER JOIN GLB_MOV_OP m ON
	e.CD_NT_MOV = m.CD_MOV_OP
WHERE
	m.ATU_EST=1
	and p.DT_PROC > e.DT_ENT;

INSERT INTO EST_PROD_CPL_CUSTO_MEDIO_PROCESSAMENTO_PENDENTE
	(CD_EMP,
	CD_FILIAL,
	CD_PROD,
	DT_PROC,
	DT_CAD,
	DT_PROC_ATUAL)
SELECT DISTINCT 
	i.CD_EMP,
	i.CD_FILIAL,
	i.CD_PROD,
	MIN(e.DT_ENT),
	GETDATE(),
	NULL
FROM
	EST_NF_ENT e  INNER JOIN DELETED i ON
	e.CD_EMP = i.CD_EMP AND 
	e.CD_FILIAL = i.CD_FILIAL AND
	e.CD_NF = i.CD_NF 
	INNER JOIN GLB_MOV_OP m ON
	e.CD_NT_MOV = m.CD_MOV_OP
	LEFT OUTER JOIN EST_PROD_CPL_CUSTO_MEDIO_PROCESSAMENTO_PENDENTE p ON
	p.CD_EMP = i.CD_EMP AND
	p.CD_FILIAL = i.CD_FILIAL AND
	p.CD_PROD = i.CD_PROD
WHERE
	m.ATU_EST=1
	AND p.CD_PROD IS NULL
GROUP BY
	i.CD_EMP,
	i.CD_FILIAL,
	i.CD_PROD

--Deletando ultimo processamento de custo medio
DELETE
	p
FROM
	EST_PROD_CPL_CUSTO_MEDIO_DT_PROC_ULTIMO p INNER JOIN DELETED d ON
	p.CD_EMP = d.CD_EMP AND
	p.CD_FILIAL = d.CD_FILIAL AND
	p.CD_PROD = d.CD_PROD 