IF EXISTS (SELECT * FROM SYS.PROCEDURES WHERE NAME = 'P_GERA_PEND_DEVOLUCAO_TRANSF')
	DROP PROCEDURE P_GERA_PEND_DEVOLUCAO_TRANSF
GO
GO
	CREATE PROCEDURE 
		P_GERA_PEND_DEVOLUCAO_TRANSF
	AS
	INSERT INTO
		EST_NF_ENT_IT_DEVOLUCAO
    (CD_EMP,
	CD_FILIAL,
	CD_NF,
	CD_PROD,
	QTDE_PROD,
	QTDE_PROD_DEVO_GERADA,
	DT_DEVOLUCAO)
	SELECT 
		E.CD_EMP,
		E.CD_FILIAL_DEST AS CD_FILIAL,
		E.CD_NF_ENT AS CD_NF,
		E.CD_PROD,
		E.QT_IT_NOTA_SAIDA - E.QT_IT_CHECK AS QTDE_PROD,
		0 AS QTDE_PROD_DEVO_GERADA,
		GETDATE() AS DT_DEVOLUCAO
	FROM
		V_EST_NF_SAI_CHECKIN_SEM_RESSUPRIMENTO E
		LEFT JOIN EST_NF_ENT_IT_DEVOLUCAO D ON
			E.CD_EMP = D.CD_EMP
			AND E.CD_FILIAL_DEST = D.CD_FILIAL
			AND E.CD_NF_ENT = D.CD_NF
			AND E.CD_PROD = D.CD_PROD
		LEFT JOIN EST_NF_ENT_IT_DEVOLUCAO_AUDIT EX ON
			E.CD_EMP = EX.CD_EMP
			AND E.CD_FILIAL_DEST = EX.CD_FILIAL
			AND E.CD_NF_ENT = EX.CD_NF
			AND E.CD_PROD = EX.CD_PROD
	WHERE
		DT_ENT >= DATEADD(DAY,-4,GETDATE())
		AND QT_IT_NOTA_SAIDA > QT_IT_CHECK
		AND E.CD_FILIAL_DEST IN (SELECT CD_FILIAL FROM PRC_FILIAL WHERE FILIAL_MTZ = 1)
		AND D.CD_EMP IS NULL
		AND EX.CD_EMP IS NULL;
