USE [FrontAlma]
GO
/****** Object:  StoredProcedure [dbo].[ex_Calc_Importe_GrupoTarifa_Periodo]    Script Date: 08/09/2012 11:09:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------
ALTER PROCEDURE [dbo].[ex_Calc_Importe_GrupoTarifa_Periodo]
		( @grupo_tarifa varchar(40)  ,
		  @periodo      varchar(20)  ,
	          @ejercicio    smallint     ,					   	       
		  @result       numeric(19,2) output)
AS
BEGIN
  declare @id_targ  int,
	  @id_peri  int,
	  @id_ejer  tinyint,
	  @f_desde  datetime,
	  @f_hasta  datetime

  SET @result  = 0

  Select @id_ejer  =  dbo.ex_Get_Id_Ejer(@ejercicio)

  if @id_ejer is null
      return 0

  Select @id_targ = dbo.ex_Get_Id_Targ(@grupo_tarifa),
	 @id_peri =  dbo.ex_Get_Id_Peri( @id_ejer, @periodo )

  if @id_peri is null
      return 0

   Select @f_desde = peri.desde,
	  @f_hasta = peri.hasta
     From  Contperi peri
     Where id_peri = @id_peri
    
  Select @result = Sum( COALESCE(carg.importe,0) )
    From htellam llam
	Inner join htelexte exte on llam.id_exte = exte.id_exte 
	Inner join htelarea area on llam.id_area = area.id_area 
	Inner join hteltarg targ on area.id_targ = targ.id_targ
	Inner join htelcarg carg on llam.id_llam = carg.id_llam and 
				    carg.cobrado = 1
    Where DateDiff(day, @f_desde, llam.fecha) >= 0 	and
	  DateDiff(day, @f_hasta, llam.fecha) <= 0 	and
	  ( @id_targ is null or targ.id_targ = @id_targ )
   
   Select @result = Coalesce(@result,0)             
END

