/****** Object:  Trigger [TRG_EST_NF_ENT_IT_ESTORNO_CUSTO_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_IT_ESTORNO_CUSTO_PROCESSAMENTO_PENDENTE]'))
	DROP TRIGGER [dbo].[TRG_EST_NF_ENT_IT_ESTORNO_CUSTO_PROCESSAMENTO_PENDENTE]
GO
GO


CREATE TRIGGER [dbo].[TRG_EST_NF_ENT_IT_ESTORNO_CUSTO_PROCESSAMENTO_PENDENTE] ON [dbo].[EST_NF_ENT_IT_ESTORNO] 
FOR INSERT 
AS
UPDATE
	p
SET 
	p.DT_PROC=i.DT_ENT,
	p.DT_CAD=GETDATE()
FROM
	EST_PROD_CPL_CUSTO_MEDIO_PROCESSAMENTO_PENDENTE p 
	INNER JOIN INSERTED i ON
	p.CD_EMP	= i.CD_EMP AND
	p.CD_FILIAL = i.CD_FILIAL AND
	p.CD_PROD	= i.CD_PROD 
	INNER JOIN GLB_MOV_OP m ON
	I.CD_MOV_OP = m.CD_MOV_OP
WHERE
	m.ATU_EST=1
	and p.DT_PROC > i.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(i.DT_ENT),
	GETDATE(),
	NULL
FROM
	INSERTED i 
	INNER JOIN GLB_MOV_OP m ON
	I.CD_MOV_OP = 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 INSERTED i ON
	p.CD_EMP = i.CD_EMP AND
	p.CD_FILIAL = i.CD_FILIAL AND
	p.CD_PROD = i.CD_PROD;
