/****** Object:  Trigger [TRG_EST_NF_SAI_CANCEL_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_SAI_CANCEL_CUSTO_PROCESSAMENTO_PENDENTE]'))
	DROP TRIGGER [dbo].[TRG_EST_NF_SAI_CANCEL_CUSTO_PROCESSAMENTO_PENDENTE]
GO
CREATE TRIGGER [dbo].[TRG_EST_NF_SAI_CANCEL_CUSTO_PROCESSAMENTO_PENDENTE] ON [dbo].[EST_NF_SAI_CANCEL] 
FOR INSERT 
AS
UPDATE
	p
SET 
	p.DT_PROC	=T.DT_EMI_NF,
	p.DT_CAD	=GETDATE()
FROM
	INSERTED I 
	INNER JOIN EST_NF_SAI S ON
	I.CD_EMP	= S.CD_EMP AND
	I.CD_FILIAL = S.CD_FILIAL AND
	I.CD_NF	= S.CD_NF
	INNER JOIN EST_NF_SAI_IT T ON
	S.CD_EMP	= T.CD_EMP AND
	S.CD_FILIAL = T.CD_FILIAL AND
	S.CD_NF		= T.CD_NF 
	INNER JOIN GLB_MOV_OP m ON
	S.CD_NT_MOV	= m.CD_MOV_OP
	INNER JOIN EST_PROD_CPL_CUSTO_MEDIO_PROCESSAMENTO_PENDENTE p    ON
	T.CD_EMP	= P.CD_EMP AND
	T.CD_FILIAL = P.CD_FILIAL AND
	T.CD_PROD	= P.CD_PROD  
WHERE
	m.BX_EST=1
	and p.DT_PROC > T.DT_EMI_NF;
INSERT INTO EST_PROD_CPL_CUSTO_MEDIO_PROCESSAMENTO_PENDENTE
	(CD_EMP,
	CD_FILIAL,
	CD_PROD,
	DT_PROC,
	DT_CAD,
	DT_PROC_ATUAL)
SELECT DISTINCT 
	T.CD_EMP,
	T.CD_FILIAL,
	T.CD_PROD,
	MIN(T.DT_EMI_NF),
	GETDATE(),
	NULL
FROM
	INSERTED I 
	INNER JOIN EST_NF_SAI S ON
	I.CD_EMP	= S.CD_EMP AND
	I.CD_FILIAL = S.CD_FILIAL AND
	I.CD_NF	= S.CD_NF
	INNER JOIN EST_NF_SAI_IT T ON
	S.CD_EMP	= T.CD_EMP AND
	S.CD_FILIAL = T.CD_FILIAL AND
	S.CD_NF		= T.CD_NF 
	INNER JOIN GLB_MOV_OP m ON
	S.CD_NT_MOV	= m.CD_MOV_OP
	LEFT OUTER JOIN EST_PROD_CPL_CUSTO_MEDIO_PROCESSAMENTO_PENDENTE p ON
	T.CD_EMP	= P.CD_EMP AND
	T.CD_FILIAL = P.CD_FILIAL AND
	T.CD_PROD	= P.CD_PROD  
WHERE
	m.BX_EST=1
	AND p.CD_PROD IS NULL
GROUP BY
	T.CD_EMP,
	T.CD_FILIAL,
	T.CD_PROD;
--Deletando ultimo processamento de custo medio
DELETE
	p
FROM
	INSERTED I 
	INNER JOIN EST_NF_SAI S ON
	I.CD_EMP	= S.CD_EMP AND
	I.CD_FILIAL = S.CD_FILIAL AND
	I.CD_NF	= S.CD_NF
	INNER JOIN EST_NF_SAI_IT T ON
	S.CD_EMP	= T.CD_EMP AND
	S.CD_FILIAL = T.CD_FILIAL AND
	S.CD_NF		= T.CD_NF 
	INNER JOIN EST_PROD_CPL_CUSTO_MEDIO_DT_PROC_ULTIMO p  ON
	p.CD_EMP	= T.CD_EMP AND
	p.CD_FILIAL = T.CD_FILIAL AND
	p.CD_PROD	= T.CD_PROD;

--deletar a pendencia de entrada
IF EXISTS (SELECT
			CD_EMP
		   FROM
			INSERTED
		   WHERE
			CANCEL_FORA_PRAZO=1)
begin
	DELETE 
		p 
	FROM
		EST_NF_SAI_PENDENCIA p INNER JOIN INSERTED c ON
		p.CD_EMP = c.CD_EMP AND
		p.CD_FILIAL = c.CD_FILIAL AND
		p.CD_NF = c.CD_NF 
	WHERE
		c.CANCEL_FORA_PRAZO=1
end

