IF OBJECT_ID('UFD_EXP_CTB_MOV_IMP_DEV_VENDA') IS NOT NULL
	BEGIN
		DROP FUNCTION UFD_EXP_CTB_MOV_IMP_DEV_VENDA
	END
	
GO	 
 
CREATE FUNCTION UFD_EXP_CTB_MOV_IMP_DEV_VENDA( @CD_EMP		INT,
											   @CD_FILIAL	INT,
											   @DT_INI		DATETIME,
											   @DT_FIM		DATETIME,
											   @TP_DEB_CRED INT)		

RETURNS @RS_RETURN TABLE(
		CD_EMP				INT, 
		CD_FILIAL			INT, 
		NM_FANT				VARCHAR(100),
		DT_EMI_NF			DATETIME,
		DS_MOV_OP			VARCHAR(100),
		VLR_BASE_PIS_COFINS MONEY,
		VLR_ICMS_ITENS		MONEY)		
AS
BEGIN

	INSERT INTO @RS_RETURN     
		SELECT 
			V_EST_NF_ENT.CD_EMP,
			V_EST_NF_ENT.CD_FILIAL,
			PRC_FILIAL.NM_FANT,
			V_EST_NF_ENT.DT_ENT AS DT_EMI_NF,
			V_EST_NF_ENT.DS_MOV_OP,
			SUM(CASE WHEN LISTA_PROD = 2 THEN VLR_TOT_IT ELSE 0 END) VLR_BASE_PIS_COFINS,
			SUM(VLR_ICMS_IT) AS VLR_ICMS_ITENS
		
		FROM V_EST_NF_ENT 
			INNER JOIN PRC_FILIAL ON 
				V_EST_NF_ENT.CD_EMP = PRC_FILIAL.CD_EMP AND 
				V_EST_NF_ENT.CD_FILIAL = PRC_FILIAL.CD_FILIAL 
	    
		WHERE 
			V_EST_NF_ENT.CD_EMP			= @CD_EMP 
			AND V_EST_NF_ENT.CD_FILIAL	= @CD_FILIAL 
			AND V_EST_NF_ENT.DT_ENT		BETWEEN @DT_INI AND @DT_FIM 
			AND V_EST_NF_ENT.TP_MOV		= 11
			
		GROUP BY
			V_EST_NF_ENT.CD_EMP,
			V_EST_NF_ENT.CD_FILIAL,
			DS_MOV_OP,NM_FANT,DT_ENT

	RETURN
	
END	    