
/****** Object:  StoredProcedure [dbo].[DSS_Ventas_Pvta_Fechas]    Script Date: 05/21/2013 14:58:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[DSS_Ventas_Pvta_Fechas] 
	@cod_pvta     varchar(5),
	@f_desde      datetime,
	@f_hasta      datetime,
	@cod_mone     varchar(3) ,
	@tasa_result  numeric(13,8),
	@result       numeric(19,2) output   
AS
begin

   declare @id_peri        int,
		   @id_mone_result int,
		   @id_ejer        tinyint

   Select @id_mone_result = dbo.ex_Get_Id_Mone (@cod_mone),
		  @cod_pvta 	  = COALESCE( UPPER(@cod_pvta) , ''),
		  @result   	  = 0
   
   if @tasa_result is Null or @tasa_result = 0
      Select @tasa_result = mone.tasa 
      From Siclamon mone
      where id_mone = @id_mone_result

	--Select moau.id_mone, Sum(hfal.importe_neto_cont  * hfad.cantidad) neto
	--INTO #DSSPOSNeto
	----From       VResthfad      hfad -- Original
	--From       DSS_VSTHistFad hfad
	--Inner Join RESTHFAL       hfal  on hfad.id_fali  = hfal.id_fali
	--Inner Join Resthfac       hfac  on hfal.id_fact  = hfac.id_fact
	--Inner Join RESTMOAU       moau  on hfac.id_moau  = moau.id_moau
	--Inner Join Restpvta       pvta  on moau.id_pvta  = pvta.id_pvta
	--INNER JOIN RestTurn       Turn  ON hfac.id_turn  = turn.id_turn 
	--Where  hfac.estado = 4 		
	--   AND dbo.Es_CtaCasa_Hist(hfac.id_fact) = 0	         
	--   and DateDiff(day, @f_desde, turn.fecha_ini) >=0  
	--   and DateDiff(day, @f_hasta, turn.fecha_ini) <=0  
	--   and @cod_pvta =  UPPER(LTRIM(RTRIM(pvta.cod_pvta)))
	--GROUP BY moau.id_mone
	
	-- v2.0.82: La consulta anterior evaluaba si cada factura en la totalidad 
	--          del histórico era cuenta casa lo que en HDS, hacía que durara 30 segundos (225000+ facturas)
	
	Select hfad.*, moau.id_mone, hfal.importe_neto_cont
	INTO #DSSPOSFact
	--From       VResthfad      hfad -- Original
	From       DSS_VSTHistFad hfad
	Inner Join RESTHFAL       hfal  on hfad.id_fali  = hfal.id_fali
	Inner Join Resthfac       hfac  on hfal.id_fact  = hfac.id_fact
	Inner Join RESTMOAU       moau  on hfac.id_moau  = moau.id_moau
	Inner Join Restpvta       pvta  on moau.id_pvta  = pvta.id_pvta
	INNER JOIN RestTurn       Turn  ON hfac.id_turn  = turn.id_turn 
	Where  hfac.estado = 4 		
	   --AND dbo.Es_CtaCasa_Hist(hfac.id_fact) = 0	         
	   and DateDiff(day, @f_desde, turn.fecha_ini) >=0  
	   and DateDiff(day, @f_hasta, turn.fecha_ini) <=0  
	   and @cod_pvta =  UPPER(LTRIM(RTRIM(pvta.cod_pvta)))
	   
	DELETE FROM #DSSPOSFact WHERE dbo.Es_CtaCasa_Hist(id_fact) = 1
	
	Select id_mone, Sum(importe_neto_cont  * cantidad) neto
	INTO #DSSPOSNeto
	FROM #DSSPOSFact
	GROUP BY id_mone

	SELECT @result = ABS(ROUND(SUM((ne.neto / mo.tasa) * @tasa_result), 2))
	FROM       #DSSPOSNeto ne
	INNER JOIN SICLAMON    mo ON ne.id_mone = mo.id_mone

	DROP TABLE #DSSPOSNeto

	Select @result = Coalesce(ROUND(@result, 2), 0)

	Return @result
   
end










