/****** Object:  UserDefinedTableType [dbo].[AdhocServices]    Script Date: 02/01/2022 04:06:46 PM ******/
CREATE TYPE [dbo].[AdhocServices] AS TABLE(
	[ServiceId] [bigint] NULL,
	[ServiceCost] [numeric](18, 2) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[KPIAssignmentIDs]    Script Date: 02/01/2022 04:06:46 PM ******/
CREATE TYPE [dbo].[KPIAssignmentIDs] AS TABLE(
	[ASSIGNMENTIDS] [varchar](10) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[MaintenancePlanAssignment]    Script Date: 02/01/2022 04:06:46 PM ******/
CREATE TYPE [dbo].[MaintenancePlanAssignment] AS TABLE(
	[VehicleId] [bigint] NULL,
	[VehicleDescription] [varchar](20) NULL,
	[IsActive] [bit] NULL,
	[OdometerOpeningValue] [int] NULL,
	[EngineHrsSIValue] [int] NULL,
	[OdometerSIValue] [int] NULL,
	[TimeBasedSIValue] [datetime] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[MaintenancePlanDetails]    Script Date: 02/01/2022 04:06:46 PM ******/
CREATE TYPE [dbo].[MaintenancePlanDetails] AS TABLE(
	[PlanDetailsId] [bigint] NULL,
	[ServiceType] [tinyint] NULL,
	[ServiceInterval] [int] NULL,
	[Frequency] [tinyint] NULL,
	[Notification1] [tinyint] NULL,
	[Notification2] [tinyint] NULL,
	[Notification3] [tinyint] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[MaintenancePlanServices]    Script Date: 02/01/2022 04:06:46 PM ******/
CREATE TYPE [dbo].[MaintenancePlanServices] AS TABLE(
	[ServiceId] [bigint] NULL,
	[PlannedCost] [numeric](18, 2) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[MaintenanceServiceDetails]    Script Date: 02/01/2022 04:06:46 PM ******/
CREATE TYPE [dbo].[MaintenanceServiceDetails] AS TABLE(
	[ServiceId] [bigint] NULL,
	[ServicedOn] [datetime] NULL,
	[ServiceCost] [decimal](18, 2) NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[NotificaitonUserList]    Script Date: 02/01/2022 04:06:46 PM ******/
CREATE TYPE [dbo].[NotificaitonUserList] AS TABLE(
	[UserID] [bigint] NULL,
	[Email] [bit] NULL,
	[SMS] [bit] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[PIII_ParamList]    Script Date: 02/01/2022 04:06:46 PM ******/
CREATE TYPE [dbo].[PIII_ParamList] AS TABLE(
	[controllerID] [tinyint] NULL,
	[RefID] [tinyint] NULL,
	[CmdId] [tinyint] NULL,
	[Seconday_Current_Limit] [smallint] NULL,
	[Secondary_Voltage] [tinyint] NULL,
	[Spark_Rate] [tinyint] NULL,
	[Operating_Charge_Ratio] [smallint] NULL,
	[Optinal_Input_Power] [tinyint] NULL,
	[Corona_Power] [smallint] NULL,
	[VDC_peak] [tinyint] NULL,
	[VDC_Through] [tinyint] NULL,
	[IAC_PRI] [tinyint] NULL,
	[Operating_IDC_Limit] [int] NULL,
	[Mains_Frequency] [tinyint] NULL,
	[Total_Accumulated_Spark] [smallint] NULL,
	[Total_Operating_Time] [smallint] NULL,
	[Operating_Corona_Energy] [smallint] NULL,
	[Input_Energy] [int] NULL,
	[Secondary_current_Limit] [int] NULL,
	[Sec_Current_Drop_AfterSpark] [smallint] NULL,
	[T_Recovery_cyc] [smallint] NULL,
	[T_Fast_Ramp_cyc] [smallint] NULL,
	[Charge_Ratio] [smallint] NULL,
	[Recharge_HW] [int] NULL,
	[BC_IDC_Min] [smallint] NULL,
	[RAP_IDC_Limit] [smallint] NULL,
	[BC_CR_Maximum] [smallint] NULL,
	[Load_Status1_IDC_Limit] [smallint] NULL,
	[LS_1_V_Limit] [smallint] NULL,
	[LS_1_IDC_Setbk] [smallint] NULL,
	[RAP_TM1_Pause] [smallint] NULL,
	[RAP_TM1_Run] [smallint] NULL,
	[RAP_TM2_Pause] [smallint] NULL,
	[RAP_TM2_Run] [smallint] NULL,
	[RAP_TM3_Pause] [smallint] NULL,
	[RAP_TM3_Run] [smallint] NULL,
	[RAP_MOT1_ON_OFF] [bit] NULL,
	[RAP_MOT2_ON_OFF] [bit] NULL,
	[RAP_MOT3_ON_OFF] [bit] NULL,
	[RAP_CONT_ON_OFF] [bit] NULL,
	[Back_Corona_ON_OFF] [bit] NULL,
	[HT_ON_OFF] [bit] NULL,
	[Sec_Curr_drop_after_dbleSpark] [smallint] NULL,
	[MAX_Spark_Rate] [tinyint] NULL,
	[TQuench_CYC] [tinyint] NULL,
	[Back_Corona_MEAS] [smallint] NULL,
	[BC_IDC_Step] [smallint] NULL,
	[BC_Hold_Time] [tinyint] NULL
)
GO
/****** Object:  UserDefinedTableType [dbo].[PR_ParamList]    Script Date: 02/01/2022 04:06:46 PM ******/
CREATE TYPE [dbo].[PR_ParamList] AS TABLE(
	[RefID] [tinyint] NULL,
	[CmdId] [tinyint] NULL,
	[Primary_Voltage_Value] [smallint] NULL,
	[Primary_Current_Value] [smallint] NULL,
	[Primary_Power_Value] [smallint] NULL,
	[Secondary_Voltage_Value] [tinyint] NULL,
	[Secondary_Current_Value] [smallint] NULL,
	[Spark_Per_Minute] [smallint] NULL,
	[Arcs_Per_Minute] [smallint] NULL,
	[Under_Voltage_TripMode] [smallint] NULL,
	[Program_no_of_Rapper] [tinyint] NULL,
	[Primary_Voltage_limit] [smallint] NULL,
	[Primary_Current_Limit] [smallint] NULL,
	[Secondary_Voltage_Limit] [tinyint] NULL,
	[Secondary_Current_Limit] [smallint] NULL,
	[Under_Voltage_Set_Point] [smallint] NULL,
	[Secondary_Current_Peak_Limit] [smallint] NULL,
	[Ramp] [smallint] NULL,
	[Pedestal] [tinyint] NULL,
	[Quench_Time] [tinyint] NULL,
	[Spark_Rate] [tinyint] NULL,
	[IE_Charge_Halfcycle] [tinyint] NULL,
	[IE_Discharge_Cycle] [tinyint] NULL,
	[IE_Background_Power] [tinyint] NULL,
	[IE_Optimise_Timer] [tinyint] NULL,
	[Power_Down_Rapping] [tinyint] NULL,
	[Rapper1_Interval_Timer] [int] NULL,
	[Rapper1_On_timer] [int] NULL,
	[Rapper2_Interval_timer] [int] NULL,
	[Rapper2_On_Timer] [int] NULL,
	[Rapper3_Interval_Timer] [int] NULL,
	[Rapper3_On_Timer] [int] NULL,
	[Rapper4_Interval_Timer] [int] NULL,
	[Rapper4_On_Timer] [int] NULL,
	[Phase_Back] [tinyint] NULL
)
GO
/****** Object:  UserDefinedFunction [dbo].[adr_fn_GetESPLayout]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 03-04-2017
-- Updated Date : 06-12-2017
-- Updated User : Kalaivanan
-- Description:	To Fetch the ESP Layout HTML data from the Template given
-- =============================================
CREATE FUNCTION [dbo].[adr_fn_GetESPLayout] 
(
	-- Add the parameters for the function here
	@bigEquipmentId			bigint,
	@PassageId				tinyint,
	@FieldId				tinyint,
	@DCSIMId				tinyint,
	@ControllerSNo			tinyint,
	@ControllerId			bigint,
	@ControllerName			varchar(50),
	@ControllerType			tinyint
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
 
--Declare @bigEquipmentId			bigint  =1011
--Declare @PassageId				tinyint =1
--Declare @FieldId				tinyint =1
--Declare @DCSIMId				tinyint =4
--Declare @ControllerSNo			tinyint =3
--Declare @ControllerId			bigint =3
--Declare @ControllerName			varchar(50) ='TR-D1'
--Declare @ControllerType			tinyint=2	

	-- Declare the return variable here
	DECLARE @ChangedTemplate NVARCHAR(MAX)

	-- Add the T-SQL statements to compute the return value here
	DECLARE @Template NVARCHAR(MAX)
	SET		@Template = '<div id="divController_#" class="row padding-width-sm Controller">
			<div id="divIdContainer_Cntrl_#" class="col-sm-6 padding-width-md ControllerId form-controllinebreak">
				<img id="icnStatus_Cntrl_#" src=$StatusIcnSrc$ class="ControllerStatusIcon" /><br />
				<span><b>$ControllerId$</b></span><br />
				<span><b>$ControllerName$</b></span>
			</div>
			<div id="divStatisticsContainer_Cntrl_#" class="col-sm-6 form-controllinebreak ControllerStatistics">
				<span>$Amps$<b> AMPS</b></span><br />
				<span>$KV$<b> KV</b></span><br />
				<span>$MA$<b> MA</b></span><br />				
				<span>$SPM$<b> SPM</b></span><br/>
			</div>
			<div id="divStatusContainer_Cntrl_#" class="col-xs-6 nullpadding CntrlStatusContainer">
				<div id="divStatusIndicatorTxt_Cntrl_#" class="CntrlStatusIndicator">
					<span class="$StatusIndicator$"><b>$StatusIndicator$</b></span>
				</div>
			</div>
		</div>' 
		--<span>$ChargeRatio$<b> Oper.CR</b></span><br />
	--Frames Controller Identification details
	SET @Template = REPLACE(@Template, '#', @ControllerId) 
	SET @Template = REPLACE(@Template, '$ControllerId$', 'ID ' + CAST(@ControllerSNo AS VARCHAR(3)))
	SET @Template = REPLACE(@Template, '$ControllerName$', @ControllerName)

	--PRINT '@ControllerId : ' + cast(@ControllerId as varchar(5)) + '   ControllerId : ' + CAST(@ControllerSNo AS VARCHAR(3)) + '   @ControllerName : ' + cast(@ControllerName as varchar(5))

	--Frames Controller current Parameters
	DECLARE @Amps varchar(10), @KV varchar(10), @MA varchar(10), @ChargeRatio varchar(10), @SPM varchar(10), @IsAlarm bit, @TimeIntr varchar(10), @Status bit  
	
	IF @ControllerType = 1
	BEGIN
		--SELECT	Top 1	@Amps = IAC_PRI, @KV = Secondary_Voltage, @MA = [Seconday_Current_Limit(IDC)],
		--				@ChargeRatio = Operating_Charge_Ratio, @SPM = Spark_Rate,
		--				@TimeIntr = DATEDIFF(MINUTE, H.OriginDateTime, GETDATE()), 
		--				@IsAlarm = CASE WHEN H.CustomProp LIKE '%IsAlarm=1%' THEN 1 ELSE 0 END
		--FROM	rvlfMsgInHst H
		--INNER	JOIN rvlfMsgInHstParam_PIII PR On PR.MessageInID = H.MessageInID AND PR.controllerID = H.controllerID
		--WHERE 
		--	H.BoxMsgInTypeId = 4
		--AND	H.BoxId = @bigEquipmentId 
		--AND	PR.controllerID = @ControllerId
		--ORDER BY H.OriginDateTime Desc

		--SELECT 
		--	@Amps = IAC_PRI, @KV = Secondary_Voltage, @MA = [Seconday_Current_Limit(IDC)],
		--	@ChargeRatio = Operating_Charge_Ratio, @SPM = Spark_Rate,
		--	@TimeIntr = DATEDIFF(MINUTE, PR.OriginDateTime, GETDATE()),
		--	@IsAlarm=CM.IsAlarm
	 --   FROM 
		--	rvlfMsgInHstParam_PIII PR INNER JOIN  adrControllerMaster CM ON PR.MessageInID =CM.MessageInID 
		--WHERE 
		--	--PR.BoxID= CM.EquipmentID AND PR.ControllerID = CM.ControllerPositionID AND PR.DCSIM = CM.DCSIM
		--	 PR.BoxID= @bigEquipmentId AND PR.ControllerID = @ControllerId

		SELECT 
			@Amps = Amps, @KV = KV, @MA = MA,
			--@ChargeRatio = Operating_Charge_Ratio, 
			@SPM = SPM,
			@TimeIntr = DATEDIFF(MINUTE, LastReporteDateTime, GETDATE()),
			@IsAlarm = IsAlarm,
			@Status = HT_ON_OFF
	    FROM 
			adrControllerMaster
		WHERE 
			--PR.BoxID= CM.EquipmentID AND PR.ControllerID = CM.ControllerPositionID AND PR.DCSIM = CM.DCSIM
			 EquipmentID = @bigEquipmentId AND ControllerPositionID = @ControllerId AND DCSIMId  = @DCSIMId AND PassageId = @PassageId AND FieldID = @FieldId

	END
	ELSE 
	BEGIN 
		--SELECT	Top 1	@Amps = Primary_Current_Value, @KV = Secondary_Voltage_Value, @MA = Secondary_Current_Value,
		--				--@ChargeRatio = IE_Charge_Halfcycle, @SPM = Spark_Rate,
		--				@TimeIntr = DATEDIFF(MINUTE, H.OriginDateTime, GETDATE()),
		--				@IsAlarm = CASE WHEN H.CustomProp LIKE '%IsAlarm=1%' THEN 1 ELSE 0 END
		--FROM	rvlfMsgInHst H
		--INNER	JOIN rvlfMsgInHstParam_PR PR On PR.MessageInID = H.MessageInID AND PR.controllerID = H.controllerID
		--WHERE	
		--	H.BoxMsgInTypeId = 24
		--AND	H.BoxId = @bigEquipmentId 
		--AND	PR.controllerID = @ControllerId		
		--AND H.DCSIM = @DCSIMId
		--ORDER	BY H.OriginDateTime Desc

		--SELECT 
		--	@Amps = Primary_Current_Value, @KV = Secondary_Voltage_Value, @MA = Secondary_Current_Value,
		--	@TimeIntr = DATEDIFF(MINUTE, PR.OriginDateTime, GETDATE()),
		--	@IsAlarm=CM.IsAlarm
	 --   FROM 
		--	rvlfMsgInHstParam_PR PR INNER JOIN  adrControllerMaster CM ON PR.MessageInID =CM.MessageInID 
		--WHERE 
		--	--PR.BoxID= CM.EquipmentID AND PR.ControllerID = CM.ControllerPositionID AND PR.DCSIM = CM.DCSIM
		--	 PR.BoxID= @bigEquipmentId AND PR.ControllerID = @ControllerId AND CM.DCSIMID = @DCSIMId 

		SELECT 
			@Amps = Amps, @KV = KV, @MA = MA,@SPM = SPM,
			--@TimeIntr = DATEDIFF(MINUTE, LastReporteDateTime, GETDATE()),
			@TimeIntr = CASE WHEN DATEDIFF(HH,LastReporteDateTime,GETUTCDATE()) > 1 THEN 'Offline' when IsAlarm>0 THEN 'Alarm' ELSE 'Online' END,
			@IsAlarm = IsAlarm,
			@Status = HT_ON_OFF
	    FROM 
			adrControllerMaster
		WHERE 
			 EquipmentID = @bigEquipmentId AND ControllerPositionID = @ControllerId AND  DCSIMID = @DCSIMId AND PassageId = @PassageId AND FieldID = @FieldId

	END	

	--PRINT '@Amps : '+CAST(@Amps AS VARCHAR(10))  + '  @KV  : ' +CAST(@KV  AS VARCHAR(10)) + '  @MA : ' +CAST( @MA  AS VARCHAR(10)) 
	--		+ '  @TimeIntr : ' + CAST(@TimeIntr  AS VARCHAR(10)) + '  @IsAlarm : '+ cast(@IsAlarm  AS VARCHAR(10)) + ' @ChargeRatio : ' + CAST(ISNULL(@ChargeRatio,'0') AS VARCHAR(10))

	--IF @TimeIntr > 30
	--BEGIN
	--	--SET @Status = 0 
	--	--SET @Template = REPLACE(@Template, '$Volts$', @Volts)
	--	SET @Template = REPLACE(@Template, '$Amps$', ISNULL(@Amps,'0'))
	--	SET @Template = REPLACE(@Template, '$KV$', ISNULL(@KV,'0'))
	--	SET @Template = REPLACE(@Template, '$MA$', ISNULL(@MA,'0'))
	--	--SET @Template = REPLACE(@Template, '$ChargeRatio$', ISNULL(@ChargeRatio,'0'))
	--	SET @Template = REPLACE(@Template, '$SPM$', ISNULL(@SPM,'0'))

	--END
	--ELSE
	--BEGIN
	--	--SET @Status = 1 
	--	--SET @Template = REPLACE(@Template, '$Volts$', @Volts)
	--	SET @Template = REPLACE(@Template, '$Amps$', ISNULL(@Amps,'0'))
	--	SET @Template = REPLACE(@Template, '$KV$', ISNULL(@KV,'0'))
	--	SET @Template = REPLACE(@Template, '$MA$', ISNULL(@MA,'0'))
	--	--SET @Template = REPLACE(@Template, '$ChargeRatio$', ISNULL(@ChargeRatio,'0'))
	--	SET @Template = REPLACE(@Template, '$SPM$', ISNULL(@SPM,'0'))
	--END

	SET @Template = REPLACE(@Template, '$Amps$', ISNULL(@Amps,'0'))
	SET @Template = REPLACE(@Template, '$KV$', ISNULL(@KV,'0'))
	SET @Template = REPLACE(@Template, '$MA$', ISNULL(@MA,'0'))
	SET @Template = REPLACE(@Template, '$SPM$', ISNULL(@SPM,'0'))
	
	--SET @Template = REPLACE(@Template, '$StatusIcnSrc$', CASE WHEN @IsAlarm = 1 THEN '../images/fuellow-1_.png' ELSE (CASE WHEN @Status = 1 THEN '../images/1_.png' ELSE '../images/Y_.png' END) END)
	SET @Template = REPLACE(@Template, '$StatusIcnSrc$', CASE WHEN @IsAlarm = 1 THEN '../images/fuellow-1_.png' ELSE (CASE WHEN @TimeIntr = 'Online' THEN '../images/1_.png' ELSE '../images/Y_.png' END) END)
	SET @Template = REPLACE(@Template, '$StatusIndicator$', CASE WHEN @Status = 0 THEN 'ON' ELSE 'OFF' END)

	-- Return the result of the function
	SELECT @ChangedTemplate = @Template
	--SELECT @ChangedTemplate
	RETURN @ChangedTemplate
END


--Select Top 100 * From rvlfMsgInHstParam_PIII order by originDatetime Desc
--Select Top 100 * From rvlfMsgInHstParam_PR order by originDatetime Desc
--Select * From adrControllerMaster where EquipmentID=1011
GO
/****** Object:  UserDefinedFunction [dbo].[CalcDistanceBetweenLocations]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[CalcDistanceBetweenLocations]
      (@LatitudeA       FLOAT = NULL,
       @LongitudeA       FLOAT = NULL,
       @LatitudeB       FLOAT = NULL,
       @LongitudeB       FLOAT = NULL,
       @InKilometers      BIT = 0
       )
RETURNS FLOAT
AS
BEGIN
      -- just set @InKilometers to 0 for miles or 1 for km
      -- ex:  SELECT dbo.CalcDistanceBetweenLocations (30.123,27.1,28.14,32.23, 0)

      -- select field1, field2, dbo.CalcDistanceBetweenLocations(lat1, long1, lat2,
      -- long2, 0) as distance from yourtable
      -- where dbo.CalcDistanceBetweenLocations(lat1, long1, lat2,
      -- long2, 0) <= 10 --within the ten miles range
      DECLARE @Distance FLOAT

      SET @Distance = (SIN(RADIANS(@LatitudeA)) *
              SIN(RADIANS(@LatitudeB)) +
              COS(RADIANS(@LatitudeA)) *
              COS(RADIANS(@LatitudeB)) *
              COS(RADIANS(@LongitudeA - @LongitudeB)))

      --Get distance in miles
        SET @Distance = (DEGREES(ACOS(@Distance))) * 69.09

      --If specified, convert to kilometers
      IF @InKilometers = 1
            SET @Distance = @Distance * 1.609344

      RETURN @Distance

END


GO
/****** Object:  UserDefinedFunction [dbo].[fn_diagramobjects]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

	CREATE FUNCTION [dbo].[fn_diagramobjects]() 
	RETURNS int
	WITH EXECUTE AS N'dbo'
	AS
	BEGIN
		declare @id_upgraddiagrams		int
		declare @id_sysdiagrams			int
		declare @id_helpdiagrams		int
		declare @id_helpdiagramdefinition	int
		declare @id_creatediagram	int
		declare @id_renamediagram	int
		declare @id_alterdiagram 	int 
		declare @id_dropdiagram		int
		declare @InstalledObjects	int

		select @InstalledObjects = 0

		select 	@id_upgraddiagrams = object_id(N'dbo.sp_upgraddiagrams'),
			@id_sysdiagrams = object_id(N'dbo.sysdiagrams'),
			@id_helpdiagrams = object_id(N'dbo.sp_helpdiagrams'),
			@id_helpdiagramdefinition = object_id(N'dbo.sp_helpdiagramdefinition'),
			@id_creatediagram = object_id(N'dbo.sp_creatediagram'),
			@id_renamediagram = object_id(N'dbo.sp_renamediagram'),
			@id_alterdiagram = object_id(N'dbo.sp_alterdiagram'), 
			@id_dropdiagram = object_id(N'dbo.sp_dropdiagram')

		if @id_upgraddiagrams is not null
			select @InstalledObjects = @InstalledObjects + 1
		if @id_sysdiagrams is not null
			select @InstalledObjects = @InstalledObjects + 2
		if @id_helpdiagrams is not null
			select @InstalledObjects = @InstalledObjects + 4
		if @id_helpdiagramdefinition is not null
			select @InstalledObjects = @InstalledObjects + 8
		if @id_creatediagram is not null
			select @InstalledObjects = @InstalledObjects + 16
		if @id_renamediagram is not null
			select @InstalledObjects = @InstalledObjects + 32
		if @id_alterdiagram  is not null
			select @InstalledObjects = @InstalledObjects + 64
		if @id_dropdiagram is not null
			select @InstalledObjects = @InstalledObjects + 128
		
		return @InstalledObjects 
	END
	
GO
/****** Object:  UserDefinedFunction [dbo].[Fn_Interval]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[Fn_Interval] 
(   
    @startnum int, 
    @endnum int
)
RETURNS @dt TABLE 
(
    IntervalValue bigint not null
)
AS
BEGIN

  WITH gen AS (
    SELECT @startnum AS num
    UNION ALL
    SELECT num+1 FROM gen WHERE num+1<=@endnum
)
    INSERT @dt
    SELECT * FROM gen

   

    RETURN;
END
GO
/****** Object:  UserDefinedFunction [dbo].[fn_Split]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE FUNCTION [dbo].[fn_Split] (@text VARCHAR(8000), @delimiter VARCHAR(20) = ' ')

	RETURNS @Strings TABLE (
		position INT IDENTITY PRIMARY KEY
		, value VARCHAR(8000)
		)

AS BEGIN
	DECLARE @index int
	SET @index = -1

	WHILE (LEN(@text) > 0) BEGIN
		-- Find the first delimiter
		SET @index = CHARINDEX(@delimiter , @text)

		-- No delimiter left?
		-- Insert the remaining @text and break the loop
		IF (@index = 0) AND (LEN(@text) > 0) BEGIN  
			INSERT INTO @Strings VALUES (@text)
			BREAK 
		END 

		-- Found a delimiter
		-- Insert left of the delimiter and truncate the @text
		IF (@index > 1) BEGIN
			INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))
			SET @text = RIGHT(@text, (LEN(@text) - @index))
		END
		-- Delimiter is 1st position = no @text to insert
		ELSE SET @text = RIGHT(@text, (LEN(@text) - @index))
	END
	RETURN
END


GO
/****** Object:  UserDefinedFunction [dbo].[ProperCasing]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create function [dbo].[ProperCasing](@Text as varchar(8000))
returns varchar(8000)
as
begin
   declare @Reset bit;
   declare @Ret varchar(8000);
   declare @i int;
   declare @c char(1);

   select @Reset = 1, @i=1, @Ret = '';

   while (@i <= len(@Text))
    select @c= substring(@Text,@i,1),
               @Ret = @Ret + case when @Reset=1 then UPPER(@c) else LOWER(@c) end,
               @Reset = case when @c like '[a-zA-Z]' then 0 else 1 end,
               @i = @i +1
   return @Ret
end

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_Compactordetails]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_Compactordetails](
 @vehicleId Int = null 
)
RETURNS @rtnParams TABLE(
 ParamId TINYINT,
 ParamName varchar(50)
)
AS
BEGIN
  DECLARE @tbl TABLE(Id Int identity(1,1),Comptype tinyint,compModel varchar(20),isven bit,venmodel varchar(20), seqno tinyint, Nooffan tinyint, addparam tinyint)

  INSERT INTO @tbl(Comptype,compModel,isven,venmodel,seqno,Nooffan,addparam)
   SELECT C.CompType,    
     C.CompModel,CASE WHEN C.IsVentilator =1 THEN '1' ELSE '0' END AS IsVentilator,C.VentilatorModel ,C.SeqNo, Md.VFantype AS NoofFan,ISNULL(MD.isAddParams,'0') AS AddParam 
   FROM rvlf_CompactorDetails C inner join rvlfMAKDevices Md on C.DeviceId = Md.BoxId
   inner join rvlfVehicleAssignment VA ON VA.BoxId = Md.BoxId
   Inner join rvlfVehicle V ON V.VehicleId = VA.VehicleId
   WHERE V.VehicleId = @vehicleId and Md.IsDelete= 0 
    Declare @Count int = 1
    Declare @totalCount int
    declare @compactortype tinyint
    declare @isventilator bit
    
    --Create table @rtnParams(ParamId int, ParamName varchar(50))
    
    SET @totalCount = (SELECT COUNT(*) FROM @tbl)
    WHILE(@Count <= @totalCount)
    BEGIN
    
     SELECT @compactortype=Comptype, @isventilator =isven FROM @tbl WHERE Id = @Count and seqno = @Count 
     IF(@Count = 1)
     BEGIN
      IF((@compactortype =1 OR @compactortype =2) and (@isventilator =1))
      BEGIN
        INSERT INTO @rtnParams(ParamId, ParamName)
        SELECT ParamId, ParamDescr FROM rvlfTrendParamMst Where ParamId IN(30,31)
      END
      ELSE
        INSERT INTO @rtnParams(ParamId, ParamName)
        SELECT ParamId, ParamDescr FROM rvlfTrendParamMst Where ParamId =30
     END 
     IF(@Count = 2)
     BEGIN
       IF((@compactortype =1 OR @compactortype =2) and (@isventilator =1))
       BEGIN
        INSERT INTO @rtnParams(ParamId, ParamName)
        SELECT ParamId, ParamDescr FROM rvlfTrendParamMst Where ParamId IN(32,33)
       END
       ELSE 
        INSERT INTO @rtnParams(ParamId, ParamName)
        SELECT ParamId, ParamDescr FROM rvlfTrendParamMst Where ParamId =32
     END
     IF(@Count = 3)
     BEGIN
       IF((@compactortype =1 OR @compactortype =2) and (@isventilator =1))
       BEGIN
        INSERT INTO @rtnParams(ParamId, ParamName)
        SELECT ParamId, ParamDescr FROM rvlfTrendParamMst Where ParamId IN(34,35)
       END
       ELSE
       BEGIN
        INSERT INTO @rtnParams(ParamId, ParamName)
        SELECT ParamId, ParamDescr FROM rvlfTrendParamMst Where ParamId =34
       END   
     END 
     IF(@Count = 4)
     BEGIN
       IF((@compactortype =1 OR @compactortype =2) and (@isventilator =1))
       BEGIN
        INSERT INTO @rtnParams(ParamId, ParamName)
        SELECT ParamId, ParamDescr FROM rvlfTrendParamMst Where ParamId IN(36,37)
       END
       ELSE
       BEGIN
        INSERT INTO @rtnParams(ParamId, ParamName)
        SELECT ParamId, ParamDescr FROM rvlfTrendParamMst Where ParamId =36
       END   
     END 
     SET @Count = @Count +1  
  END
  Return 
END

 ---select * from #TblParam 


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_ConvertArrayToTable]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_ConvertArrayToTable]
    (
      @ParamaterList VARCHAR(MAX),
      @Delimiter CHAR(1)
    )
RETURNS @ReturnList TABLE
    (
      FieldValue VARCHAR(MAX)
    )
 /*******************************************************************************************
*	Name		:	rvlf_fn_ConvertArrayToTable
*	Author		:	M. Jebamalai Jaya Chitra
*	Company		:	Angler Technologies
*	Purpose		:	To Convert a String Array to Tabular Data in SQL Server 2005
*	Modified	: 
*******************************************************************************************/
AS BEGIN
    DECLARE @ArrayList TABLE
        (
          FieldValue VARCHAR(MAX)
        )
    DECLARE @Value VARCHAR(MAX)
    DECLARE @CurrentPosition INT
 
    SET @ParamaterList = LTRIM(RTRIM(@ParamaterList))
        + CASE WHEN RIGHT(@ParamaterList, 1) = @Delimiter THEN ''
               ELSE @Delimiter
          END
    SET @CurrentPosition = ISNULL(CHARINDEX(@Delimiter, @ParamaterList, 1), 0)  

    IF @CurrentPosition = 0
        INSERT  INTO @ArrayList ( FieldValue )
                SELECT  @ParamaterList
    ELSE
        BEGIN
            WHILE @CurrentPosition > 0
                BEGIN
                    SET @Value = LTRIM(RTRIM(LEFT(@ParamaterList,
                                                  @CurrentPosition - 1))) --make sure a value exists between the delimiters
                    IF LEN(@ParamaterList) > 0
                        AND @CurrentPosition <= LEN(@ParamaterList)
                        BEGIN
                            INSERT  INTO @ArrayList ( FieldValue )
                                    SELECT  @Value
                        END
                    SET @ParamaterList = SUBSTRING(@ParamaterList,
                                                   @CurrentPosition
                                                   + LEN(@Delimiter),
                                                   LEN(@ParamaterList))
                    SET @CurrentPosition = CHARINDEX(@Delimiter,
                                                     @ParamaterList, 1)
                END
        END
    INSERT  @ReturnList ( FieldValue )
            SELECT  FieldValue
            FROM    @ArrayList
    RETURN
   END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_ConvertArrayToTableWithIdentity]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_ConvertArrayToTableWithIdentity]  
    (  
      @ParamaterList VARCHAR(MAX),  
      @Delimiter CHAR(1)  
    )  
RETURNS @ReturnList TABLE  
    (  
      [Identity] int identity(1,1),
      FieldValue VARCHAR(MAX)  
    )  
 /*******************************************************************************************  
* Name  : rvlf_fn_ConvertArrayToTable  
* Author  : M. Jebamalai Jaya Chitra  
* Company  : Angler Technologies  
* Purpose  : To Convert a String Array to Tabular Data in SQL Server 2005  
* Modified :   
*******************************************************************************************/  
AS BEGIN  
    DECLARE @ArrayList TABLE  
        (  
          FieldValue VARCHAR(MAX)  
        )  
    DECLARE @Value VARCHAR(MAX)  
    DECLARE @CurrentPosition INT  
   
    SET @ParamaterList = LTRIM(RTRIM(@ParamaterList))  
        + CASE WHEN RIGHT(@ParamaterList, 1) = @Delimiter THEN ''  
               ELSE @Delimiter  
          END  
    SET @CurrentPosition = ISNULL(CHARINDEX(@Delimiter, @ParamaterList, 1), 0)    
  
    IF @CurrentPosition = 0  
        INSERT  INTO @ArrayList ( FieldValue )  
                SELECT  @ParamaterList  
    ELSE  
        BEGIN  
            WHILE @CurrentPosition > 0  
                BEGIN  
                    SET @Value = LTRIM(RTRIM(LEFT(@ParamaterList,  
                                                  @CurrentPosition - 1))) --make sure a value exists between the delimiters  
                    IF LEN(@ParamaterList) > 0  
                        AND @CurrentPosition <= LEN(@ParamaterList)  
                        BEGIN  
                            INSERT  INTO @ArrayList ( FieldValue )  
                                    SELECT  @Value  
                        END  
                    SET @ParamaterList = SUBSTRING(@ParamaterList,  
                                                   @CurrentPosition  
                                                   + LEN(@Delimiter),  
                                                   LEN(@ParamaterList))  
                    SET @CurrentPosition = CHARINDEX(@Delimiter,  
                                                     @ParamaterList, 1)  
                END  
        END  
    INSERT  @ReturnList ( FieldValue )  
            SELECT  FieldValue  
            FROM    @ArrayList  
    RETURN  
   END  

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_DayLightSavings]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- rvlf_fn_DayLightSavings '6/26/2012 08:00:00 AM',90, 6,30,107,'6/26/2012 08:00:00 AM'
-- Author:	Selvakumar
-- Create date: 27-Mar-2011
-- Description:	DayLightSavings Functionality
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_DayLightSavings]
(
@StartDate datetime = NULL,
@bigQueryingUser int=0,
@HoursToBeAdded int =0,
@MinsToBeAdded Int =0,
@DefaultDateFormat INT = 0,
@OriginDateTime DateTime =NULL
)
RETURNS  VARCHAR(MAX)
AS
BEGIN
DECLARE @ReturnTime VARCHAR(MAX) =NULL
DECLARE @Hours INT = 0
DECLARE @Minutes INT = 0
DECLARE @Sign char =0
DECLARE @ToDate Datetime = NULL 
DECLARE @FromDate Datetime = NULL
DECLARE @DayLIghtHoursToBeAdded INT = 0
DECLARE @DayLightMinsToBeAdded INT = 0
Select @Hours= SUBSTRING(HOURS,2,2),@ToDate = ToDate,@FromDate = FromDate,@Sign = SUBSTRING(Hours,1,1),@Minutes = SUBSTRING(Hours,5,2) 
from rvlfUserPreferences where UserId = @bigQueryingUser
IF(@Hours IS NOT NULL)
BEGIN
IF(@Sign = '+')
BEGIN
SET  @DayLIghtHoursToBeAdded = @HoursToBeAdded + @Hours
SET @DayLightMinsToBeAdded = @MinsToBeAdded +@Minutes
END
ELSE 
BEGIN
SET  @DayLIghtHoursToBeAdded =  @HoursToBeAdded  - @Hours
SET  @DayLightMinsToBeAdded = @MinsToBeAdded  -  @Minutes	
END	
END
SET @ReturnTime = (CASE WHEN CONVERT(VARCHAR,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,@OriginDateTime)),101) BETWEEN CONVERT(Date,@FromDate) AND CONVERT(Date, @ToDate)
--CONVERT(VARCHAR,@FromDate,101) AND CONVERT(VARCHAR, @ToDate,101)
THEN Convert(varchar,(DATEADD(N,@DayLightMinsToBeAdded,DATEADD(hh,@DayLIghtHoursToBeAdded,@OriginDateTime))),@DefaultDateFormat)
ELSE Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,@OriginDateTime)),@DefaultDateFormat)
END + ' ' + 
CASE WHEN CONVERT(VARCHAR,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,@OriginDateTime)),101) BETWEEN CONVERT(VARCHAR,@FromDate,101) AND CONVERT(VARCHAR,@ToDate,101)
THEN Convert(varchar,cast(DateAdd(n,@DayLightMinsToBeAdded,DateAdd(hh,@DayLIghtHoursToBeAdded,@OriginDateTime))as Time),22) +' (DS)'
ELSE Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,@OriginDateTime))as Time),22)
END)

RETURN @ReturnTime
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_DayLightSavings_Date]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- rvlf_fn_DayLightSavings '3/26/2012 08:00:00 AM',90, 6,30,107,'3/26/2012 08:00:00 AM'
-- Author:	Selvakumar
-- Create date: 29-Mar-2011
-- Description:	DayLightSavings Functionality
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_DayLightSavings_Date]
(
@StartDate Datetime = NULL,
@bigQueryingUser Bigint=0,
@HoursToBeAdded int =0,
@MinsToBeAdded Int =0,
@OriginDateTime DateTime =NULL
)
RETURNS  DateTime
AS
BEGIN
DECLARE @ReturnTime DateTime =NULL
DECLARE @Hours INT = 0
DECLARE @Minutes INT = 0
DECLARE @Sign char =0
DECLARE @ToDate Datetime = NULL 
DECLARE @FromDate Datetime = NULL
DECLARE @DayLIghtHoursToBeAdded INT = 0
DECLARE @DayLightMinsToBeAdded INT = 0
Select @Hours= SUBSTRING(HOURS,2,2),@ToDate = ToDate,@FromDate = FromDate,@Sign = SUBSTRING(Hours,1,1),@Minutes = SUBSTRING(Hours,5,2) 
from rvlfUserPreferences where UserId = @bigQueryingUser
IF(@Sign = '+')
BEGIN
SET  @DayLIghtHoursToBeAdded = @HoursToBeAdded + @Hours
SET @DayLightMinsToBeAdded = @MinsToBeAdded +@Minutes
END
ELSE 
BEGIN
SET  @DayLIghtHoursToBeAdded =  @HoursToBeAdded  - @Hours
SET  @DayLightMinsToBeAdded = @MinsToBeAdded  -  @Minutes	
END	
SET @ReturnTime = (CASE WHEN CONVERT(VARCHAR,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,@OriginDateTime)),103) BETWEEN CONVERT(VARCHAR,@FromDate,103) AND CONVERT(VARCHAR,@ToDate,103)
THEN DATEADD(N,@DayLightMinsToBeAdded,DATEADD(hh,@DayLIghtHoursToBeAdded,@OriginDateTime))
ELSE DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,@OriginDateTime))
END)
RETURN @ReturnTime
END




GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetAdvHistoryLatLong_PhoneGap]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

                 
CREATE FUNCTION [dbo].[rvlf_fn_GetAdvHistoryLatLong_PhoneGap]    
(                  
 @vehicleId varchar(50),                  
 @startdate as datetime,                  
 @enddate datetime,                  
@interval as int,                  
@orderby varchar(10),                  
@bigQueryingUser bigint = 0,                  
@bitIsMDTMsg bit=0 ,                   
 @bigLastHours int = null                   
)    
RETURNS nvarchar(MAX)                
as                 
Begin       
DECLARE @vcLatLongDetail nvarchar(MAX)             
   declare @Lang varchar(50),  @LangSetting varchar(20)                               
   select @Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings from rvlfUserPreferences up             
    inner join rvlfUser u on u.UserId = up.UserId            
 inner join rvlfOrganization o on o.OrganizationId = u.OrganizationId            
   where up.UserId = @bigQueryingUser                 
 ------- Included by Kumuthini on 16-July-09 ---------------------                  
                  
 DECLARE @HoursToBeAdded INT = 0                  
 DECLARE @MinsToBeAdded INT = 0                  
 DECLARE @Distance varchar(20)                  
 DECLARE @bigOrganizationID  bigint                   
 DECLARE @DefaultDateFormat INT = 0                  
                   
 DECLARE @ConversionFactor numeric (10,2) = 1.0            
    
  SELECT @HoursToBeAdded = 0,@MinsToBeAdded = 0,@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                    
   @DefaultDateFormat=(case when ISNULL(up.DefaultDateFormat,0)=0 then 106 else up.DefaultDateFormat end),              
   @Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings                            
  FROM rvlfUserPreferences up                     
   INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId          
   inner join rvlfUser u on u.UserId = up.UserId      
   inner join rvlfOrganization o on o.OrganizationId = u.OrganizationId                 
  WHERE up.UserId = @bigQueryingUser         
                      
            
                      
 DECLARE @userIds table (userId bigint)                  
                   
 DECLARE @bigVehOrganizationID  bigint =(SELECT OrganizationId FROM rvlfVehicle WHERE VehicleId =@vehicleId)                  
 --getting the user group id                   
 DECLARE @intUserGroupId int=(SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId =@bigQueryingUser)                  
                   
 IF @bigOrganizationID > 1                   
  INSERT INTO @userIds SELECT UserID FROM rvlfUser WHERE OrganizationId = @bigOrganizationID                   
                      
    -------------------date conversion--included by Narayanasamy on 03-Nov-09---------------------------------                  
 SET @startDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@startDate))                  
 SET @endDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@endDate))                  
 ----------------------------------------------------------------------------------------------------------                  
         if(@bigLastHours <> 0)                      
         Begin                  
          SET @endDate=@startdate                        
          SET @startDate= DATEADD(hh,(-1 * @bigLastHours) ,@startdate)                            
         End            
   ---------------Ranjith for OBD data Enter key issue -----------------------                
    declare @NewLine char(2)                
    set @NewLine=char(13)+char(10)                
    -----------------------------------------------------------------------                                 
                 
Declare @tmpHistory table (MessageInID uniqueidentifier,Latitude varchar(200),Longitude varchar(200),Distance varchar(200),Speed varchar(100),Heading varchar(50),
[Timestamp] datetime,DateTimeReceived varchar(100),VehicleDescription varchar(500),MessageDetails varchar(1000),[Address] varchar(max),IgnitionStatus int,StreetAddress varchar(max),
Landmark varchar(max),isMapIT int,AutoID bigint,mapitFunction varchar(max))

insert into @tmpHistory 
      select *, ROW_NUMBER() over (order by timestamp) as AutoID,                  
     ';SetMapItValue('''+                  
      CAST(Latitude as varchar(15)) +'~#~'+CAST(Longitude as varchar(15))+'~#~'                  
      +StreetAddress+'~#~'+ ISNULL( cast(Speed as varchar(15))+@Distance  ,'-')+'~#~'+                  
      --Convert(varchar,[TimeStamp],101)+' '+ Convert(varchar,[TimeStamp],108) +'~#~'+              
      Convert(varchar,[TimeStamp],101)+' '+ SubString(Convert(varchar,[TimeStamp],9),12,9) + SUBSTRING(Convert(varchar,[TimeStamp],9), 25, 2) + '~#~' +                  
      --CAST(Heading as varchar(3))+'~#~'+ Distance +'~#~'+ cast(isNull(IgnitionStatus,0) as CHAR(1))+'~#~'+Landmark                  
      (CASE WHEN (SELECT ISNULL(OrgId,0) FROM rvlfOrganizationServiceURL_App WHERE OrgId=@bigOrganizationID) <> 0 THEN '-1' ELSE CAST(Heading as varchar(3)) END)+              
      --CAST(Heading as varchar(3))+              
      '~#~'+ISNULL(cast(a.Distance as varchar(5)),'')+'~#~'+              
      (CASE WHEN (SELECT ISNULL(OrgId,0) FROM rvlfOrganizationServiceURL_App WHERE OrgId=@bigOrganizationID) <> 0  THEN '2' ELSE cast(isNull(IgnitionStatus,0) as CHAR(1)) END)+              
       --cast(isNull(IgnitionStatus,0) as CHAR(1))+              
       '~#~'+Landmark +'~#~'+                
      --MessageDetails                
       replace(MessageDetails,@NewLine,'')                
      +'~#~'+CAST(MessageInID AS varchar(40))+'~&~'', this.checked, this.id);'                  
      as mapitFunction                   
        from (                  
   select distinct(H.MessageInID),  
   --H.CustomProp,  
  cast(H.Latitude as decimal(14,6)) as Latitude, cast(H.Longitude as decimal(14,6)) as Longitude,                  
   H.NearestLandMark as Distance,                   
   /***************** Changed the Speed as numeric data type by Jaya Chitra on 25-Aug-2009******************/                  
   
   Case WHEN H.BoxMsgInTypeId IN(9,14,15,16,17,24,51,90,113) THEN '-'               
   WHEN H.ValidGps <> 0 AND H.CustomProp LIKE '%MA_Model_No%' THEN '-'               
   WHEN ISNULL(H.Speed,0) = 0 THEN '-'              
   ELSE  SUBSTRING(CAST(Speed  * @ConversionFactor as VARCHAR),0,CHARINDEX('.',CAST(Speed  * @ConversionFactor as VARCHAR),0)) END  as Speed,                  
   CASE WHEN H.Speed = 0 OR H.ValidGps > 0 THEN -1 ELSE CAST(Heading as varchar(3))  END as Heading,                   
   [Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime),                
   DateTimeReceived = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,OriginDateTime), -- DateTimeReceived                 
   v.VehicleDescription,               
     replace(Case WHEN H.BoxMsgInTypeId = 28 THEN (case when @Lang='LanguageArNew' then isnull (CT.BoxMsgInTypeDesc_Ar,CT.BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi' THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc) else CT.BoxMsgInTypeDesc end)       

          WHEN H.BoxMsgInTypeId = 73 THEN 'Generator Information'                  
          WHEN H.BoxMsgInTypeId = 74 THEN 'External Sensor Status Info'                  
          WHEN H.BoxMsgInTypeId = 75 THEN 'Driver Status Info'                  
          WHEN H.BoxMsgInTypeId = 97 THEN 'Harsh Thresholds'                  
          WHEN H.BoxMsgInTypeId=105 THEN 'Keep Alive Interval : '+ CASE WHEN CustomProp LIKE '%Interval=%' THEN dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Interval=',';')+' Min' ELSE     '' END                  
          WHEN H.BoxMsgInTypeId=104 THEN 'Live Track Parameters : ' + CASE WHEN H.CustomProp LIKE '%Frequency=%' THEN dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Frequency=',';') +' Sec for '+                  
         dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Duration=',';') +' Min'                  
       ELSE '' END                  
       WHEN H.BoxMsgInTypeId = 51 THEN                   
        (case when @Lang='LanguageArNew' THEN N'تخرق السرعة لل ' when @Lang='LanguageHindi' THEN N'स्पीड के लिए उल्लंघन'  ELSE 'Speed Violated for ' END)  + '(' +dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'                        
       
       WHEN H.BoxMsgInTypeId = 95 THEN                                     
       Replace(REPLACE(H.CustomProp,'Default Dial Number=','Dial Number : '), 'Default Dial Number2=','Dial Number2 : ')                       
       WHEN H.BoxMsgInTypeId = 111 THEN                   
       'MDT Error Code - '+SUBSTRING(CustomProp,CHARINDEX('Error Code=',CustomProp,0)+11,(CHARINDEX(';',CustomProp,CHARINDEX('Error Code=',CustomProp,0))-(CHARINDEX('Error Code=',CustomProp,0)+11)))                  
       WHEN H.BoxMsgInTypeId=113 THEN                  
        dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Band Name=',';') +' ['+                  
       dbo.rvlf_fn_GetTimeFromSeconds(CAST(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Duration=',';') as int))+']'                  
              WHEN H.BoxMsgInTypeId = 114 and H.customprop like '%SendSMSQuery:%'  THEN                                            
       dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime ) 
  WHEN H.BoxMsgInTypeId = 114 and H.customprop like '%ImgHeader:%' and SUBSTRING(H.customprop, CHARINDEX('ImgHeader:', H.customprop)+10,1) = '1'  THEN  'Camera Image' --'Camera Image'               
    WHEN H.BoxMsgInTypeId = 114 and H.customprop like '%CameraSettings:%' and SUBSTRING(H.customprop, CHARINDEX('CameraSettings:', H.customprop)+15,1) ='1' Then 'Camera Settings'                   
    When H.BoxMsgInTypeId = 114 and H.customprop like '%IButtonCommand:%' and SUBSTRING(H.CustomProp, CHARINDEX('IButtonCommand:', H.CustomProp)+15,1) = '1' Then              
    dbo.rvlf_fn_GetAlarmDetails_New(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)              
    WHEN H.BoxMsgInTypeId = 114 and H.customprop like '%GeozoneInOutWithDuration:%' and SUBSTRING(H.customprop, CHARINDEX('GeozoneInOutWithDuration:', H.customprop)+25,1) ='1' Then              
    REPLACE(dbo.rvlf_fn_GetAlarmDetails_New(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang),'Geozone=','')                                
       WHEN H.BoxMsgInTypeId=114 AND CharIndex('ETA:',CustomProp) <> 0  THEN --Sakthi 23-Feb-2012 for Garmin ETA                 
  CASE WHEN CAST(SUBSTRING(CustomProp,8,CHARINDEX(';Distance',CustomProp,1)-8) AS bigint) = -1 THEN                
   'No Navigation'          
  ELSE                
   'ETA : '+CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,DATEADD(SECOND,CAST(SUBSTRING(CustomProp,8,CHARINDEX(';Distance',CustomProp,1)-8) AS bigint),CAST('1989-12-31 00:00:00.000' AS DATETIME)))),@DefaultDateFormat)+               
 
   + ' ' + Convert(varchar,cast(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,DATEADD(SECOND,CAST(SUBSTRING(CustomProp,8,CHARINDEX(';Distance',CustomProp,1)-8) AS bigint),CAST('1989-12-31 00:00:00.000' AS DATETIME)))) as Time),22)+                
   ' Distance : '+SUBSTRING(CustomProp,CHARINDEX(';Distance',CustomProp,1)+10,LEN(Customprop)-CHARINDEX(';Distance',CustomProp,1)+10) + ' meters'                
  END                
  when H.BoxMsgInTypeId = 114 and CHARINDEX('18;GPRS',H.CustomProp,0) <> 0  THEN 'Send Health Status'              
  when H.BoxMsgInTypeId = 114 and CHARINDEX('20;GeozoneSpeedAlert',H.CustomProp,0) <> 0  THEN               
  'Geozone Speed Alert (Geozone : ' +ISNULL((SELECT GeozoneName FROM rvlfOrganizationGeozone WHERE         
  OrganizationId=@bigVehOrganizationID AND               
  GeozoneId = CAST(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'GeozoneId=',';')AS INT)),'Deleted')+              
  '; Speed Limit: '+ dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'SpeedThreshold=',';')+' KMPH)'              
  when H.BoxMsgInTypeId = 114 and CHARINDEX('21;GeozoneSpeedViolation',H.CustomProp,0) <> 0  THEN               
  (SELECT ISNULL(GeozoneName,'Deleted') FROM rvlfOrganizationGeozone WHERE OrganizationId=V.OrganizationId AND GeozoneId = CAST(SUBSTRING(H.CustomProp,CHARINDEX(';GeozoneId:',H.CustomProp,0)+11,(CHARINDEX(';Duration:',H.CustomProp,0) -         
  (CHARINDEX(';GeozoneId:',H.CustomProp,0)+11))) AS INT)) +                        
  ' Speed Violation ('+dbo.rvlf_fn_GetTimeFromSeconds(CAST(SUBSTRING(H.CustomProp,CHARINDEX('Duration:',H.CustomProp,0)+9,(LEN(H.CustomProp)-(CHARINDEX('Duration:',H.CustomProp,0)+8))) AS INT))+')'                        
  when H.BoxMsgInTypeId = 114 and CHARINDEX('28;GeozoneId',H.CustomProp,0) <> 0  THEN                                     
      (SELECT ISNULL(GeozoneName,'Deleted') FROM rvlfOrganizationGeozone WHERE OrganizationId=V.OrganizationId AND GeozoneId = CAST(SUBSTRING(H.CustomProp,CHARINDEX(';GeozoneId:',H.CustomProp,0)+11,(CHARINDEX(';Duration:',H.CustomProp,0) -                
  
      (CHARINDEX(';GeozoneId:',H.CustomProp,0)+11))) AS INT)) +    case when CHARINDEX('ExtDuration:',H.CustomProp,0)=0 then  ' Time Violation ('                  
      +dbo.rvlf_fn_GetTimeFromSeconds(CAST(SUBSTRING(H.CustomProp,CHARINDEX('Duration:',H.CustomProp,0)+9,(LEN(H.CustomProp)-(CHARINDEX('Duration:',H.CustomProp,0)+8))) AS INT))+')'               
      else            
       case when CAST(SUBSTRING(H.CustomProp,CHARINDEX('ExtDuration:',H.CustomProp,0)+12,(LEN(H.CustomProp)-(CHARINDEX('ExtDuration:',H.CustomProp,0)+11))) AS INT)=1 then            
       ' Extended Time Violation (' else ' Time Violation (' end            
      +dbo.rvlf_fn_GetTimeFromSeconds(CAST( SUBSTRING(H.CustomProp, CHARINDEX('Duration:',H.CustomProp,0)+9,(CHARINDEX(';',H.CustomProp,CHARINDEX('Duration:',H.CustomProp,1)))                    
      -(CHARINDEX('Duration:',H.CustomProp,1)+9)) AS INT))+')'     end         
          
  WHEN (H.BoxMsgInTypeId=1 OR H.BoxMsgInTypeId=4) AND H.CustomProp LIKE '%IsAck:1%' THEN 'Asset settings changed'              
  WHEN H.BoxMsgInTypeId=4 AND H.CustomProp LIKE '%IsAlarm=1;AlarmMsg=%' THEN               
   'Alarm : '+SUBSTRING(H.CustomProp,CHARINDEX('AlarmMsg=',H.CustomProp,0)+9,LEN(H.CustomProp)-(CHARINDEX(H.CustomProp,'AlarmMsg=',0)+9))               
     ELSE                  
     dbo.rvlf_fn_GetAlarmDetails_New(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)--CT.BoxMsgInTypeDesc                   
     END + CASE WHEN @intUserGroupId=1 AND @bigVehOrganizationID=47 THEN  CASE WHEN H.customprop LIKE '%SensorInfo1%' THEN +' ; S1 = '+ SUBSTRING(H.customprop,CHARINDEX('SensorInfo1=',H.customprop,1)+12,CHARINDEX(';',H.customprop,                  
         CHARINDEX('SensorInfo1=',H.customprop,1)) - (CHARINDEX('SensorInfo1=',H.customprop,1)+12)) ELSE '' END+ CASE WHEN H.customprop LIKE '%SensorInfo2%' THEN +' ; S2 = '+ SUBSTRING(H.customprop,CHARINDEX('SensorInfo2=',H.customprop,1)+12,             




 
         CHARINDEX(';',H.customprop,                  
         CHARINDEX('SensorInfo2=',H.customprop,1)) - (CHARINDEX('SensorInfo2=',H.customprop,1)+12))  ELSE '' END ELSE ''  END,'°C',' degrees')    as MessageDetails,         
             
   
                     
       CASE WHEN (H.LandMarkID IS NULL OR H.LandMarkID = 0) THEN                          
  Replace(ISNULL((Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(H.StreetAddress_Ar,H.StreetAddress)          
  When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN ISNULL(H.StreetAddress_Hin,H.StreetAddress)               
  ELSE H.StreetAddress END),'Address is not resolved'),'''','\''')              
  ELSE isnull(L.LandmarkName,          
  Replace(ISNULL((Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(H.StreetAddress_Ar,H.StreetAddress)               
  When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN ISNULL(H.StreetAddress_Hin,H.StreetAddress)               
  ELSE H.StreetAddress END),'Address is not resolved'),'''','\''')          
  ) END AS Address,                
      CASE                   
         WHEN H.BoxMsgInTypeId = 37 /* Analog (Fuel) Sensor Status - LOW*/ THEN 3                  
         WHEN H.BoxMsgInTypeId = 38 /* Analog (Fuel) Sensor Status - MEDIUM*/ THEN 4                  
         WHEN H.BoxMsgInTypeId = 39 /* Analog (Fuel) Sensor Status - HIGH */ THEN 5                  
         WHEN H.BoxMsgInTypeId = 42 /* Alamr Fuel Drain */ THEN 6                  
         WHEN CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1 /* Violation or Alarms */ THEN 7                  
         WHEN H.BoxMsgInTypeId = 3 THEN 0                  
         WHEN H.BoxMsgInTypeId = 12 THEN 10 /*Sleep mode*/                  
         WHEN H.BoxMsgInTypeId = 24 THEN 9 /*Extended Idling*/                  
         WHEN H.BoxMsgInTypeId = 9 THEN /*Idling started and end*/                  
          CASE WHEN CAST(SUBSTRING(CustomProp,CHARINDEX(':',CustomProp,LEN('Idling:')+1)+8,CHARINDEX(';',CustomProp,8) - CHARINDEX(':',CustomProp,LEN('Idling:'))-1) AS INT) = 0 THEN 8                   
         ELSE 9                  
         END                  
         WHEN H.BoxMsgInTypeId = 2 THEN                  
        CASE WHEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,                   
         CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) = 3 THEN                  
          CASE WHEN (SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,                   
           CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1)) = 'ON'                  
           THEN 1 ELSE 0 End End                  
        ELSE 2 END as IgnitionStatus,                  
        --Replace( ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''')  AS StreetAddress,           
        Replace(ISNULL( (              
  Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(H.StreetAddress_AR,H.StreetAddress)               
  When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN ISNULL(H.StreetAddress_Hin,H.StreetAddress)               
  ELSE H.StreetAddress END),'Address is not resolved'),'''','\''')  as StreetAddress,                          
        ISNULL(CASE WHEN (L.LandMarkID IS NULL OR H.LandMarkID = 0) THEN '-' ELSE L.LandmarkName END,'-')                  
        AS Landmark,        
           (case when h.ValidGps = 0 and h.IsProcessed = 0 and h.StreetAddress not like 'N/A' and h.StreetAddress not like '%Address could not be Resolved!%'  then 1 else 0 end) as isMapIT                  

   from rvlfMsgInHst H                   
    INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                  
    INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                  
    INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId                  
    LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID                  
    INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID                  
   where VA.VehicleId = @VehicleID and OriginDateTime between                  
   CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109)                  
   and                   
   (H.BoxMsgInTypeId <> 89 OR 1 = (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser)) AND -- Vehicle Fuel Fill visible for only Angler Admin                  
   CT.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity s                  
     WHERE s.ModuleId = 26 and s.UserGroupId IN                  
     (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))                  
    AND CommInfo1 IS NOT NULL                  
    AND (@bitIsMDTMsg=0 OR H.BoxMsgInTypeId IN(77,98,109,110,111))                   
  ) as a  
		 
  Select @vcLatLongDetail  = (Stuff((Select '~&~' + cast (Latitude as varchar(max)) + '~#~' + cast (Longitude as varchar(max)) + '~#~' +  Replace( cast (StreetAddress as varchar(max)) ,',',' ') + '~#~' +  Replace( cast (MessageDetails as varchar(max)),',
'

,' ')  + '~#~' +  cast ([Timestamp] as varchar(max)) from @tmpHistory where isMapIT = 1  order by Timestamp desc , MessageInID desc FOR XML PATH('')),1,7,''))
		 
  Return @vcLatLongDetail
		  
End 

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetAlarmDetails]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE FUNCTION [dbo].[rvlf_fn_GetAlarmDetails]                      
(                      
 @vcAlarmDesc varchar(1000),                      
 @tiBoxMsgInTypeID tinyint,                      
 @intBoxID varchar(15) = null,                      
 @uiMessageInId uniqueidentifier = null,                      
 @dtOriginDateTime DateTime = null                      
)                      
RETURNS varchar(MAX)                      
AS                      
BEGIN                      
 DECLARE @vcAlarmDetail varchar(MAX)                      
 DECLARE @tiSensorID tinyint                      
 DECLARE @SecondsToConvert bigint                      
 DECLARE @vcMoxMsgInTypeName varchar(100)                      
 DECLARE @tankCapacity int                       
 DECLARE @FuelLevelPercentage int                      
 DECLARE @vcFuelUnits varchar(10)                      
                       
 SELECT @vcMoxMsgInTypeName = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                      
                       
 IF @tiBoxMsgInTypeID = 11 OR @tiBoxMsgInTypeID = 2 OR @tiBoxMsgInTypeID = 3                      
  OR @tiBoxMsgInTypeID= 13                      
 BEGIN                      
  DECLARE @vcActionOn varchar(15)                      
  DECLARE @vcActionOff varchar(15)                      
                          
  SET @tiSensorID = CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('=',@vcAlarmDesc)+1,                      
  CHARINDEX(';',@vcAlarmDesc,1)-CHARINDEX('=',@vcAlarmDesc)-1                      
  ) As tinyint)                      
                        
  IF @tiSensorID = 31                       
   BEGIN                      
    SET @vcAlarmDetail = 'Alarm - Tamper'                      
   END                      
  ELSE IF @tiSensorID = 27                      
   BEGIN                      
    SET @vcAlarmDetail = 'Alarm - Fuel drain'                      
                          
    SELECT @vcAlarmDetail = @vcAlarmDetail + ' ' +                       
     CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                      
     THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                      
     LEN(@vcAlarmDesc)), ';', '%') ELSE '' END                       
   END                      
  ELSE IF NOT  EXISTS (SELECT SensorName FROM rvlfBoxSensorsCfg WHERE SensorId = @tiSensorId and BoxID = @intBoxID)                      
   BEGIN                      
    SET @vcAlarmDetail = 'Unknown sensor'                      
   END                      
  ELSE                       
   BEGIN                      
    SELECT @vcAlarmDetail = ISNULL(SensorName, 'Unknown sensor') ,                       
     @vcActionOn = ISNULL(ActionOn,''), @vcActionOff = ISNULL(ActionOff,'')                      
     FROM rvlfBoxSensorsCfg WHERE SensorId = @tiSensorId and BoxID = @intBoxID                      
    SET @vcAlarmDetail = @vcAlarmDetail                       
    DECLARE @intSensorStateStart int                       
                      
    SET @intSensorStateStart = CHARINDEX('SENSOR_STATUS=', @vcAlarmDesc) + 14                      
    SET @vcAlarmDetail = @vcAlarmDetail + ' '+                       
     CASE WHEN (SUBSTRING(@vcAlarmDesc, @intSensorStateStart, 2)) = 'ON' THEN                       
      @vcActionOn                      
     ELSE                        
      @vcActionOff                       
     END                      
    IF RIGHT(@vcAlarmDetail,1) = ';'                      
    BEGIN                      
     SET @vcAlarmDetail = SUBSTRING(@vcAlarmDetail,1,LEN(@vcAlarmDetail)-1)                      
    END                            
                          
    SET @vcAlarmDetail = @vcAlarmDetail+CASE WHEN @tiBoxMsgInTypeID= 13 THEN ' - Bad Sensor' ELSE '' END                       
    If EXISTS(select BoxId from rvlfBoxId where BoxId IN (@intBoxID) AND @dtOriginDateTime >= '04/27/2012' AND (organizationid =139 OR organizationid = 23))                      
    BEGIN              
    SET @SecondsToConvert =                       
    (CASE WHEN @vcAlarmDesc  like '%SENSOR_NUM=2;%' and @vcAlarmDesc LIKE '%SENSOR_DURATION=%' THEN                      
    CONVERT(VARCHAR,ISNULL((CASE WHEN @vcAlarmDesc LIKE '%SENSOR_DURATION=%' THEN CAST( SUBSTRING (@vcAlarmDesc,CHARINDEX('SENSOR_DURATION=',@vcAlarmDesc,1)+16,CHARINDEX(';',@vcAlarmDesc,                                    
    CHARINDEX('SENSOR_DURATION=',@vcAlarmDesc,1)) - (CHARINDEX('SENSOR_DURATION=',@vcAlarmDesc,1)+16)) as bigint) END ),0)) END)                      
    SET @vcAlarmDetail = @vcAlarmDetail + ' ' +                      
    CASE WHEN @SecondsToConvert = 0                      
    THEN '' ELSE  CASE WHEN @vcAlarmDesc LIKE '%SENSOR_NUM=2;%' and @vcAlarmDesc LIKE '%SENSOR_DURATION=%' THEN '(Durations: ' + dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert * 60) +')'  ELSE '' END END                      
    END                      
  END                   
 END                      
 ELSE IF @tiBoxMsgInTypeID = 9                       
 BEGIN                      
  SET @SecondsToConvert = CAST(SUBSTRING (@vcAlarmDesc, CHARINDEX(':',@vcAlarmDesc,1)+1,                      
   CHARINDEX(';',@vcAlarmDesc)-1 -CHARINDEX(':',@vcAlarmDesc,1)) AS bigint)                      
  SET @vcAlarmDetail = @vcMoxMsgInTypeName + ' '+ CASE WHEN @SecondsToConvert = 0                      
  THEN 'started' ELSE 'end ' + dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert) END                      
 END                      
 ELSE IF @tiBoxMsgInTypeID = 14 OR @tiBoxMsgInTypeID = 15 OR @tiBoxMsgInTypeID = 16 OR                       
 @tiBoxMsgInTypeID = 17 OR @tiBoxMsgInTypeID = 24 OR @tiBoxMsgInTypeID = 96 OR @tiBoxMsgInTypeID = 51                      
 BEGIN                      
  SET @SecondsToConvert = CAST(SUBSTRING (@vcAlarmDesc, CHARINDEX(':',@vcAlarmDesc,1)+1,                      
   CHARINDEX(';',@vcAlarmDesc)-1 -CHARINDEX(':',@vcAlarmDesc,1)) AS bigint)                      
  SET @vcAlarmDetail = @vcMoxMsgInTypeName + ' '+                       
   dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert)                      
 END                      
                      
 ELSE IF @tiBoxMsgInTypeID = 5 OR @tiBoxMsgInTypeID = 6                      
 BEGIN                      
  IF @uiMessageInId IS NOT NULL                      
   BEGIN                      
    SELECT @vcAlarmDetail = g.GeozoneName FROM rvlfOrganizationGeozone g INNER JOIN rvlfVehicle v                       
     ON g.OrganizationId=v.OrganizationId INNER JOIN rvlfVehicleAssignment va ON                       
     v.VehicleId = va.VehicleId                       
     --INNER JOIN rvlfVehicleGeozone vg ON vg.VehicleID = v.VehicleID AND vg.GeozoneNo = g.GeozoneId                      
     WHERE BoxId = @intBoxID and g.GeozoneId = --CAST(@vcAlarmDesc as bigint)                      
     (CAST( SUBSTRING(@vcAlarmDesc,                      
      CHARINDEX('=',@vcAlarmDesc,1)+1,(CHARINDEX(';',@vcAlarmDesc,1)                      
      - CHARINDEX('=',@vcAlarmDesc,1))-1) as bigint))                      
    SET @vcAlarmDetail = ISNULL(@vcAlarmDetail,'Geozone Deleted') + ' '+                       
     CASE WHEN @tiBoxMsgInTypeID = 5 THEN ' - In' ELSE ' - Out' END                      
   END                      
  ELSE                      
   BEGIN                      
    SELECT @vcAlarmDetail = g.GeozoneName FROM rvlfOrganizationGeozone g INNER JOIN rvlfVehicle v                       
    ON g.OrganizationId=v.OrganizationId INNER JOIN rvlfVehicleAssignment va ON                       
      v.VehicleID = va.VehicleID                      
      --INNER JOIN rvlfVehicleGeozone vg ON vg.VehicleID = v.VehicleID AND vg.GeozoneNo = g.GeozoneId                      
     WHERE BoxId = @intBoxID and g.GeozoneId = --CAST(@vcAlarmDesc as bigint)                      
     (CAST( @vcAlarmDesc as bigint))                       
    SET @vcAlarmDetail = ISNULL(@vcAlarmDetail,'Geozone Deleted') + ' '+    
     CASE WHEN @tiBoxMsgInTypeID = 5 THEN ' - In' ELSE ' - Out' END                      
   END                      
 END                      
 ELSE IF @tiBoxMsgInTypeID = 28                      
 BEGIN                      
  DECLARE @bigOrganizationID bigint                      
  SELECT @bigOrganizationID = v.OrganizationId  FROM rvlfVehicle v                      
   INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId and va.BoxId = @intBoxID                      
  SET @vcAlarmDetail = (SELECT g.GeozoneName from rvlfOrganizationGeozone g WHERE g.GeozoneId IN                       
   (select * from dbo.rvlf_fn_ConvertArrayToTable(@vcAlarmDesc,','))                      
   AND g.OrganizationID = @bigOrganizationID FOR XML AUTO)                      
  IF @vcAlarmDetail IS NULL                      
   BEGIN                      
    SET @vcAlarmDetail = ''                      
   END                      
  ELSE                      
   BEGIN                      
    SET @vcAlarmDetail = '<GeozoneList>'+@vcAlarmdetail+'</GeozoneList>'                      
   END                      
 END   
 
 ELSE IF @tiBoxMsgInTypeID = 153 --GetAdvancedGeozoneIDs                                                  
 begin                                                   
 declare @tbl table (f1 varchar(max),f2 int identity(1,1))                                                  
 declare @tbl1 table (Geozone varchar(max),Timelimit varchar(max),Restricted varchar(max))                            
 declare @Geoid varchar (max)                                                  
 declare @timelimit varchar (max)                                                  
 declare @Restricted varchar (max)                                                  
 --DECLARE @bigOrganizationID bigint                                                        
    SELECT @bigOrganizationID = v.OrganizationId  FROM rvlfVehicle v                                                        
    INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId and va.BoxId = @intBoxID                                                 
 insert into @tbl                                                  
 select * from dbo.rvlf_fn_ConvertArrayToTable(@vcAlarmDesc,';')                                                  
 insert into @tbl1                                                  
 select * from @tbl a                                                  
 PIVOT                                                  
 (                                                  
     max([f1])                                                  
 FOR [f2] IN ([1], [2], [3])                                                  
 )AS [pivot]                                                  
 select @Geoid=Geozone,@timelimit=Timelimit,@Restricted=Restricted from @tbl1                                                    
 --select * from @tbl1                                                   
 delete from @tbl1                             
 insert into @tbl1                                                  
 SELECT g.GeozoneName,a.Timelimit,a.Rest from rvlfOrganizationGeozone g                                                    
 inner join (select g.FieldValue as geoid,t.FieldValue as Timelimit,r.FieldValue as Rest from                                                   
 (select * from dbo.rvlf_fn_ConvertArrayToTableWithIdentity(@Geoid,'|')) g inner join                                                   
 (select * from dbo.rvlf_fn_ConvertArrayToTableWithIdentity(@timelimit,'|')) t on t.[identity]= g.[identity]                                                  
 inner join (select * from dbo.rvlf_fn_ConvertArrayToTableWithIdentity(@Restricted,'|')) R on g.[identity]=r.[identity]) as a                                            
 on g.GeozoneId=a.geoid                          
 where g.OrganizationID = @bigOrganizationID --FOR XML AUTO                                                  
 set @vcAlarmDetail=(select Geozone,dbo.rvlf_fn_GetTimeFromSeconds((cast(Timelimit as bigint) * 60)) as Timelimit,Restricted from @tbl1 FOR XML AUTO)                                          
 IF @vcAlarmDetail IS NULL                                                        
 BEGIN                                       
     SET @vcAlarmDetail = ''                                                        
    END                                                        
  ELSE                                                  
    BEGIN                                                        
  SET @vcAlarmDetail = '<GeozoneList>'+@vcAlarmdetail+'</GeozoneList>'                                                        
    END                                                    
 END     
                 
 ELSE IF @tiBoxMsgInTypeID = 19                      
  BEGIN                      
   DECLARE @intIPReason int                       
   SET @intIPReason  = CAST(SUBSTRING(@vcAlarmDesc, CHARINDEX('=',@vcAlarmDesc,1)+1,CHARINDEX(';',@vcAlarmDesc,1)-(CHARINDEX('=',@vcAlarmDesc,1)+1) ) as int)                       
   SET @vcAlarmDetail = 'IP Update - '+                      
    CASE WHEN @intIPReason = 1 THEN 'Power Up' WHEN @intIPReason = 2 THEN 'Failed'                      
      WHEN @intIPReason = 3 THEN 'Sleep' WHEN @intIPReason = 4 THEN 'Attach ERROR'                      
      WHEN @intIPReason = 5 THEN 'PPP TERMINATE' WHEN @intIPReason = 6 THEN 'Long PPP Negotiation'                       
      WHEN @intIPReason = 7 THEN 'PPP Negotiated To' WHEN @intIPReason = 8 THEN 'No Diag'                       
      WHEN @intIPReason = 9 THEN 'Force Reset' WHEN @intIPReason = 10 THEN 'Std Msg Failed'                       
      WHEN @intIPReason = 11 THEN 'Mdm Reset Fail' WHEN @intIPReason = 12 THEN 'Wake Up'                       
      WHEN @intIPReason = 13 THEN 'Register To' WHEN @intIPReason = 14 THEN 'Attach To'                       
      WHEN @intIPReason = 15 THEN 'AT failed' WHEN @intIPReason = 16 THEN 'Dial To'                       
      WHEN @intIPReason = 17 THEN 'Dial failed' WHEN @intIPReason = 18 THEN 'Errors > 10'                       
      WHEN @intIPReason = 19 THEN 'Can''t attached'                      
      ELSE 'Unknown' END                      
  END                      
 ELSE IF @tiBoxMsgInTypeID = 42                      
   BEGIN                      
    SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                      
                          
    SET @FuelLevelPercentage = CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                      
										 THEN dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'Fuel%=',';') END as int)
										 --REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6, LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int)
    
	SET @FuelLevelPercentage = CASE WHEN @FuelLevelPercentage <=0 THEN 0 ELSE @FuelLevelPercentage END                      
	
	SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = CASE CapacityUnits WHEN 1 THEN 'litres' WHEN 2 THEN 'gals' ELSE 'litres' END
	FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID                      
                         
	SELECT @vcAlarmDetail = @vcAlarmDetail + ' (Actual Fuel Drained - ' +	--+ ' (' + cast(@FuelLevelPercentage as varchar(3)) + '% - ' +
							cast(cast(((@FuelLevelPercentage / 100.00) * @tankCapacity)as int) as varchar(5)) +' '+ @vcFuelUnits +')'
    
	 --CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                      
     -- THEN ' (' +  REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                      
     -- LEN(@vcAlarmDesc)), ';', '%)') ELSE '' END                      
   END                      
 ELSE IF @tiBoxMsgInTypeID = 41                      
   BEGIN                        
	SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                      
                          
    --SELECT @vcAlarmDetail = @vcAlarmDetail + ' ' +                       
    -- CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                      
    -- THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                      
    -- LEN(@vcAlarmDesc)), ';', '%') ELSE '' END                       
   END                      
 ELSE IF @tiBoxMsgInTypeID = 73                      
   BEGIN                      
    SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                      
                          
    DECLARE @vcCustomProperty VARCHAR(1000) = @vcAlarmDesc                      
    SET @vcCustomProperty = REPLACE(@vcCustomProperty, '$$', ':')                      
                      
    DECLARE @vcGenParams varchar(max)                      
    DECLARE @RI AS VARCHAR(8)                      
    DECLARE @ReportingInterval AS VARCHAR(35)                      
    SET @RI = SUBSTRING (@vcCustomProperty, CHARINDEX('=',@vcCustomProperty,1)+1,                
        CHARINDEX(';',@vcCustomProperty)-1 -CHARINDEX('=',@vcCustomProperty,1))                      
                                       
                SET @ReportingInterval = CASE WHEN @RI = '00:00:30' THEN 'Reporting Interval=30sec'                      
     WHEN @RI = '00:01:00' THEN 'Reporting Interval=1min'                      
     WHEN @RI = '00:02:00' THEN 'Reporting Interval=2min'                      
     WHEN @RI = '00:05:00' THEN 'Reporting Interval=5min'                      
     WHEN @RI = '00:10:00' THEN 'Reporting Interval=10min'                      
     WHEN @RI = '00:15:00' THEN 'Reporting Interval=15min'                      
     WHEN @RI = '00:30:00' THEN 'Reporting Interval=30min'                      
     WHEN @RI = '01:00:00' THEN 'Reporting Interval=1hr'                       
     WHEN @RI = '02:00:00' THEN 'Reporting Interval=2hrs' ELSE '' END                       
                     
    SELECT @vcGenParams = ISNULL(@vcGenParams + ';', '') +                       
      CASE WHEN CHARINDEX('Gen Param No',FieldValue) <> 0 THEN                      
      REPLACE(REPLACE(REPLACE(FieldValue, 'Gen Param No='+SUBSTRING(FieldValue, CHARINDEX('Gen Param No',FieldValue)+ 13,                       
      (CHARINDEX('Gen Param Val',FieldValue) - (CHARINDEX('Gen Param No',FieldValue) + 13)))+'',                       
      dbo.rvlf_fn_GetGeneratorParameterName(SUBSTRING(FieldValue, CHARINDEX('Gen Param No',FieldValue)+ 13,                       
      (CHARINDEX('Gen Param Val',FieldValue) - (CHARINDEX('Gen Param No',FieldValue) + 13) - 1)))), 'Gen Param Val',''),                      
      'Reporting Interval='+@RI+';','') ELSE '' END                      
    FROM [dbo].[rvlf_fn_ConvertArrayToTable] (@vcCustomProperty, '|')                      
                      
    SET @vcAlarmDetail = @ReportingInterval + ';' + @vcGenParams                       
   END                      
 ELSE IF @tiBoxMsgInTypeID = 74                      
  BEGIN                      
   --SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                      
                         
   --SET @vcAlarmDetail = @vcAlarmDetail --+ '-'                      
   --SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, ' degree Celsius' ,'°C')               
   --SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, ' mV' ,'lit.')                 
                   
   SET @vcAlarmDetail = @vcAlarmDesc                      
                         
   SET @vcAlarmDetail = REPLACE(REPLACE(REPLACE(@vcAlarmDetail, 'ExSensorNo=0', 'Sensor=Temperature Sensor-1'), 'ExSensorNo=1', 'Sensor=Fuel Guage Sensor'), 'ExSensorNo=2', 'Sensor=Temperature Sensor-2')                      
      SET @vcAlarmDetail = REPLACE(REPLACE(@vcAlarmDetail, ' degree Celsius' ,'°C'), '|', ';')                      
  END         
 ELSE IF @tiBoxMsgInTypeID = 75 -- Send Driver ID and Status                      
  BEGIN                      
                         
   DECLARE @DriveDuration AS VARCHAR(10)                      
   DECLARE @DRIVERNO INT=NULL                      
   DECLARE @KEYID VARCHAR(30)=NULL                      
   DECLARE @VCDRIVERNAMECMD VARCHAR(30)=NULL                      
   DECLARE @VCKEY VARCHAR(20)=NULL                      
                         
   SELECT @VCDRIVERNAMECMD=DisplayName,@VCKEY=IButtonKeyName,@KEYID=IButtonKey FROM rvlfIButtonMapping M                      
    LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId=M.DriverId                        
   WHERE M.IButtonKey =CAST(SUBSTRING (@vcAlarmDesc,CHARINDEX('Driver ID=',@vcAlarmDesc,1)+10,CHARINDEX(';',@vcAlarmDesc,                      
          CHARINDEX('Driver ID=',@vcAlarmDesc,1)) - (CHARINDEX('Driver ID=',@vcAlarmDesc,1)+10)) as varchar)                            
   SET @DRIVERNO=CAST(SUBSTRING (@vcAlarmDesc,CHARINDEX('Driver Number=',@vcAlarmDesc,1)+14,CHARINDEX(';',@vcAlarmDesc,                      
          CHARINDEX('Driver Number=',@vcAlarmDesc,1)) - (CHARINDEX('Driver Number=',@vcAlarmDesc,1)+14)) as int)                      
                         
   SET @SecondsToConvert = CAST(SUBSTRING (@vcAlarmDesc, CHARINDEX('Drive Duration=',@vcAlarmDesc,1) + 15,                      
   CHARINDEX(';Drive Distance',@vcAlarmDesc) - 15 - CHARINDEX('Drive Duration=',@vcAlarmDesc,1)) AS BIGINT)                      
                       
   SET @DriveDuration = REPLACE((CASE WHEN LEN(RTRIM(CONVERT(char(8),@SecondsToConvert/3600))) = 1 THEN '0' + RTRIM(CONVERT(char(8),@SecondsToConvert/3600)) ELSE RTRIM(CONVERT(char(8),@SecondsToConvert/3600)) END                       
     + ':' + CASE WHEN LEN(CONVERT(char(2), (@SecondsToConvert % 3600) / 60)) = 1 THEN '0' + CONVERT(char(2), (@SecondsToConvert % 3600) / 60) ELSE CONVERT(char(2), (@SecondsToConvert % 3600) / 60) END                       
     + ':' + CASE WHEN LEN(CONVERT(char(2), @SecondsToConvert % 60)) = 1 THEN '0' + CONVERT(char(2), @SecondsToConvert % 60) ELSE CONVERT(char(2), @SecondsToConvert % 60) END), ' ', '')                      
                         
   SET @vcAlarmDetail = REPLACE(@vcAlarmDesc, 'Drive Duration=' + CAST(@SecondsToConvert AS Varchar), 'Drive Duration=' + @DriveDuration)                      
   IF(@VCDRIVERNAMECMD IS NOT NULL)                      
    BEGIN                      
     SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, 'Driver Number=' + CAST(@DRIVERNO AS Varchar), 'Driver Name=' + @VCDRIVERNAMECMD)                      
    END                      
  ELSE                      
    BEGIN                      
     SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, 'Driver Number=' + CAST(@DRIVERNO AS Varchar), 'Driver Name=UnKnown')                      
    END                      
   IF(@KEYID IS NOT NULL)                      
    BEGIN                      
     SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, 'Current Driver ID=' + CAST(@KEYID AS Varchar), 'Driver Key=' + @VCKEY)                      
    END                      
   ELSE                      
    BEGIN                      
     SET @KEYID=CAST(SUBSTRING (@vcAlarmDesc,CHARINDEX('Current Driver ID=',@vcAlarmDesc,1)+18,CHARINDEX(';',@vcAlarmDesc,                      
          CHARINDEX('Current Driver ID=',@vcAlarmDesc,1)) - (CHARINDEX('Current Driver ID=',@vcAlarmDesc,1)+18)) as VARCHAR)                               
     SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, 'Current Driver ID=' + CAST(@KEYID AS Varchar), 'Driver Key=UnKnown')                      
    END                              
  END                      
 ELSE IF @tiBoxMsgInTypeID = 76 -- Driver Identification                      
  BEGIN                      
   DECLARE @VCDRIVERNAME VARCHAR(30)=NULL                      
   IF(@vcAlarmDesc LIKE '%Driver Status=%')                      
    BEGIN                      
     IF(CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('MAPID=',@vcAlarmDesc,1)+6,LEN(@vcAlarmDesc))AS BIGINT)>0)                      
      BEGIN                      
       SELECT @VCDRIVERNAME= DisplayName FROM rvlfDriverMaster WHERE DriverId=CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('MAPID=',@vcAlarmDesc,1)+6,LEN(@vcAlarmDesc))AS BIGINT)                      
      END                      
     ELSE                      
      BEGIN                      
       SELECT @VCDRIVERNAME='Unknown'                      
      END                      
                               
     SET @vcAlarmDetail='Driver - '+@VCDRIVERNAME+' - '+CAST(SUBSTRING (@vcAlarmDesc,CHARINDEX('Driver Status=',@vcAlarmDesc,1)+14,CHARINDEX(';',@vcAlarmDesc,                
          CHARINDEX('Driver Status=',@vcAlarmDesc,1)) - (CHARINDEX('Driver Status=',@vcAlarmDesc,1)+14)) as varchar)                          
    END                      
   IF(@vcAlarmDesc LIKE '%Driver Alarm=%')                      
    BEGIN                      
     IF(CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('MAPID=',@vcAlarmDesc,1)+6,LEN(@vcAlarmDesc))AS BIGINT)>0)                      
      BEGIN                      
       SELECT @VCDRIVERNAME= DisplayName FROM rvlfDriverMaster WHERE DriverId=CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('MAPID=',@vcAlarmDesc,1)+6,LEN(@vcAlarmDesc))AS BIGINT)            
      END                      
     ELSE                      
      BEGIN                      
       SELECT @VCDRIVERNAME='Unknown'                      
      END                      
                               
     SET @vcAlarmDetail=CAST(SUBSTRING (@vcAlarmDesc,CHARINDEX('Driver Alarm=',@vcAlarmDesc,1)+13,CHARINDEX(';',@vcAlarmDesc,                      
          CHARINDEX('Driver Alarm=',@vcAlarmDesc,1)) - (CHARINDEX('Driver Alarm=',@vcAlarmDesc,1)+13)) as varchar)+' by '+@VCDRIVERNAME                          
    END                      
  END                      
 ELSE IF @tiBoxMsgInTypeID = 100 -- RFID Identification                      
  BEGIN                 
   DECLARE @VCKEYUSERNAME VARCHAR(max)=NULL           
    DECLARE @RFID Varchar(50)=null              
   declare @Punch varchar(100)=null                      
     IF(@vcAlarmDesc LIKE '%RF_ID=%')     --6                                                 
    BEGIN                  
    set @RFID=dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'RF_ID=',';')               
    IF(charindex('InOutEnable',@vcAlarmDesc,1)>0) --5              
    BEGIN              
     declare @InOutEnable varchar(2) =dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'InOutEnable:',';')               
     SELECT @VCKEYUSERNAME=IButtonKeyName FROM rvlfIButtonMapping WHERE IButtonKey=@RFID              
    IF @VCKEYUSERNAME IS NULL OR @VCKEYUSERNAME=''                                      
     BEGIN  --2                                                     
      SET @vcAlarmDetail= SUBSTRING(@vcAlarmDesc,CHARINDEX('RF_ID=',@vcAlarmDesc,1),LEN(@vcAlarmDesc))       
      set @vcAlarmDetail =left(@vcAlarmDetail,len(@vcAlarmDetail)-1)              
      set @Punch = (select dbo.rvlf_fn_GetParamValueWithIndex (@vcAlarmDesc,'Punch:',';'))                    
      set @vcAlarmDetail=@vcAlarmDetail + isnull(case when @Punch='UnauthorizedIN' or  @Punch='UnauthorizedOUT' then ' - Unauthorized' end,'')                    
      IF(@InOutEnable ='1' and @InOutEnable is not null) --1                             
      begin         -- SUBSTRING(@vcAlarmDesc,CHARINDEX('RF_ID=',@vcAlarmDesc,1),LEN(@vcAlarmDesc))                    
  SET @vcAlarmDetail = 'RF_ID='+@RFID           
  --REPLACE(SUBSTRING(@vcAlarmDesc,CHARINDEX('RF_ID=',@vcAlarmDesc,0),(CHARINDEX(';',@vcAlarmDesc,CHARINDEX('RF_ID=',@vcAlarmDesc,0))-(CHARINDEX('RF_ID=',@vcAlarmDesc,0)))), ';', '')              
  + ' - ' + SUBSTRING(@vcAlarmDesc,CHARINDEX('Punch:',                  
  @vcAlarmDesc,1)+6, CHARINDEX(';',@vcAlarmDesc, CHARINDEX('Punch:',@vcAlarmDesc,1)) - (CHARINDEX('Punch:',@vcAlarmDesc,1)+6))                                     
   end    --1                       
    END  --2                                                      
    ELSE --3               
     BEGIN                                                            
      SET @vcAlarmDetail='User - '+ @VCKEYUSERNAME +' [RFID]'                                                      
      IF(@InOutEnable='0' and @InOutEnable is not null)                              
      BEGIN --4                             
  SET @vcAlarmDetail = 'User - '+ @VCKEYUSERNAME +' [RFID]'+ ' - ' + SUBSTRING(@vcAlarmDesc,CHARINDEX('Punch:',@vcAlarmDesc,1)+6,                                             
  CHARINDEX(';',@vcAlarmDesc, CHARINDEX('Punch:',@vcAlarmDesc,1)) - (CHARINDEX('Punch:',@vcAlarmDesc,1)+6))                                     
   end  --4                           
    END--3              
END  --5               
ELSE              
begin    --Student punch          
 SELECT @VCKEYUSERNAME= StudentID FROM rvlfStudentMaster WHERE RFID=@RFID               
 select @Punch =' - '+ (select case when SUBSTRING(@vcAlarmDesc,1,10)='Punch:101;' then 'Boarded / Get down at incorrect Location'           
 when SUBSTRING(@vcAlarmDesc,1,10)='Punch:110;' then 'Boarded in incorrect vehicle'                             
 when SUBSTRING(@vcAlarmDesc,1,10)='Punch:111;' then null end)          
               
 SET @vcAlarmDetail = (case when @VCKEYUSERNAME is null then @RFID else @VCKEYUSERNAME end) + ' [RFID]' + isnull(@Punch,'')               
              
end                                               
END--6                
  Else IF(@vcAlarmDesc LIKE '%Finger%')                                                  
    BEGIN                                           
     IF(@vcAlarmDesc LIKE '%Finger Matched;FingerID:%')                                                  
     Begin                                                  
      Declare @vaFingerID varchar(10)=null                                                      
      Declare @VaFingerPrintName varchar(100)=null                                                  
      Select  @vaFingerID = (SUBSTRING(@vcAlarmDesc, CHARINDEX('FingerID:',@vcAlarmDesc,0)+9,                                                  
         (CHARINDEX(';',@vcAlarmDesc,CHARINDEX('FingerID:',@vcAlarmDesc,1)))                                                   
         -(CHARINDEX('FingerID:',@vcAlarmDesc,1)+9)))                 
      Select @VaFingerPrintName = IButtonKeyName from rvlfIButtonMapping where boxid= @intBoxID and IButtonKey = cast(@vaFingerID as int) and keytype =4                                                  
      SET @vcAlarmDetail= 'Finger Matched (' + @VaFingerPrintName + ')'                 End                                                  
     else if(@vcAlarmDesc LIKE '%Finger Not Matched;%')                                                  
     Begin                                       
      SET @vcAlarmDetail= replace(@vcAlarmDesc,';','')                                                  
     End                                                  
     else                                                  
     Begin                                                  
  SET @vcAlarmDetail= 'Finger Matched'                                                  
    End                                                  
    End              
                                                      
  END                      
 ELSE IF @tiBoxMsgInTypeID = 121                      
 BEGIN                      
  Declare @errCode int = CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('Error Code=',@vcAlarmDesc,0)+11,(CHARINDEX(';',@vcAlarmDesc,CHARINDEX('Error Code=',@vcAlarmDesc,0))-(CHARINDEX('Error Code=',@vcAlarmDesc,0)+11))) AS int)                      
  SET @vcAlarmDetail = CASE WHEN @errCode = 1 THEN 'Get Device ID From LPC'                      
       WHEN @errCode = 2 THEN 'Get Destination IP From LPC'                      
       WHEN @errCode = 3 THEN 'Get Destination Port From LPC'                      
       WHEN @errCode = 4 THEN 'Get  Reporting interval From LPC'                      
       WHEN @errCode = 5 THEN 'Get Speed threshold From LPC'                      
       WHEN @errCode = 6 THEN 'Get  leash From LPC'                      
       WHEN @errCode = 7 THEN 'Get APN From LPC'              
       WHEN @errCode = 8 THEN 'Device Reset'                      
       WHEN @errCode = 9 THEN 'Device will Reset due to IP Update fail'                      
       WHEN @errCode = 10 THEN 'Device will Reset due to no response from last one day' 
	    WHEN @errCode = 11 THEN 'Device Reset (WDT)'                      
       WHEN @errCode = 12 THEN 'Device Reset (BOD)'                      
       WHEN @errCode = 13 THEN 'Device Reset (MODEM)'                      
       ELSE 'Device Messages'                      
     END                      
 END                       
 ELSE IF @tiBoxMsgInTypeID = 77 -- Send MDT Message to Server                      
  BEGIN                      
                        
   --DECLARE @MDTUserId AS Varchar(50) = ''                      
   DECLARE @Cancode AS INT                      
   DECLARE @MsgKind AS char(1) = SUBSTRING(@vcAlarmDesc, CHARINDEX('Msg Kind',@vcAlarmDesc) + 9,                       
      (CHARINDEX('Cancode',@vcAlarmDesc) - CHARINDEX('Msg Kind',@vcAlarmDesc) - 10))                      
                       
   IF @MsgKind = '0'           BEGIN                      
                      
    SET @vcAlarmDetail = SUBSTRING(@vcAlarmDesc, CHARINDEX('Message=',@vcAlarmDesc) + 0,                       
         (CHARINDEX('Group ID',@vcAlarmDesc) - CHARINDEX('Message=',@vcAlarmDesc) - 0))                      
    SET @vcAlarmDetail = REPLACE(REPLACE(@vcAlarmDetail, ';', ''), 'Message=', 'Msg=')                      
                          
    --SET @MDTUserId = SUBSTRING(@vcAlarmDesc, CHARINDEX('User ID=',@vcAlarmDesc) + 8,                       
    --     (CHARINDEX('Message',@vcAlarmDesc) - CHARINDEX('User ID=',@vcAlarmDesc) - 9))                      
                      
   END                       
   ELSE IF @MsgKind = '2'                      
   BEGIN                      
    DECLARE @orgId int,@typeid int,@Msg varchar(100),@MsgAns varchar(100),@Q1 varchar(30),@Q2 varchar(30),@Q3 varchar(30),                      
       @A1 varchar(30),@A2 varchar(30),@A3 varchar(30)                      
       SELECT @orgId = OrganizationId FROM rvlfBoxId WHERE BoxId=@intBoxID                      
    SET @Cancode = CONVERT(INT, SUBSTRING(@vcAlarmDesc, CHARINDEX('Cancode=',@vcAlarmDesc) + 8,                       
        (CHARINDEX('User ID',@vcAlarmDesc) - CHARINDEX('Cancode=',@vcAlarmDesc) - 9)))                      
    SELECT @typeid=TypeId,@Msg=(CASE WHEN TypeId = 1 THEN REPLACE(REPLACE(REPLACE(MsgName,'$',''),'@',''),'-','')                      
    ELSE REPLACE(REPLACE(REPLACE(MsgName,'$',' '),'@',' '),'-',' ') END) FROM rvlfMDTFormMessages              
    WHERE OrganizationId=@orgId AND FormMsgId=@Cancode                      
                          
    SET @vcAlarmDetail = REPLACE(SUBSTRING(@vcAlarmDesc, CHARINDEX('Message=',@vcAlarmDesc) + 0,            
    (CHARINDEX('Group ID',@vcAlarmDesc) - CHARINDEX('Message=',@vcAlarmDesc) - 0)),'Message=','')                      
                          
    SELECT @MsgAns= REPLACE((CASE WHEN @typeid = 2 THEN REPLACE(@vcAlarmDetail,'\~',', ') ELSE REPLACE(@vcAlarmDetail,'\~','') END),';','')                      
                          
    IF @typeid = 2                      
    BEGIN                      
     SET @Q1 = LTRIM(RTRIM(SUBSTRING(@Msg,0,30)))                      
     SET @Q2 = LTRIM(RTRIM(SUBSTRING(@Msg,31,30)))                      
     SET @Q3 = LTRIM(RTRIM(SUBSTRING(@Msg,61,30)))                      
     SET @A1 = (SELECT ISNULL(FieldValue,'') FROM dbo.rvlf_StringSplitter(@MsgAns,',') WHERE Sno=1)                      
     SET @A2 = (SELECT ISNULL(FieldValue,'') FROM dbo.rvlf_StringSplitter(@MsgAns,',') WHERE Sno=2)                      
     SET @A3 = (SELECT ISNULL(FieldValue,'') FROM dbo.rvlf_StringSplitter(@MsgAns,',') WHERE Sno=3)                      
    END                      
                          
                          
    SELECT @vcAlarmDetail=(SELECT ISNULL(MDTUserName,'-') FROM rvlfMDTUserTable                       
    WHERE MDTUserId=(SUBSTRING(@vcAlarmDesc, CHARINDEX('User ID=',@vcAlarmDesc) + 8,                      
    (CHARINDEX('Message',@vcAlarmDesc) - CHARINDEX('User ID=',@vcAlarmDesc) - 9))))+' > '+                      
    (CASE WHEN @typeid = 1 THEN @Msg +' : ' + @MsgAns                       
    ELSE                       
    (CASE WHEN LEN(@Q1) > 0 THEN @Q1 +' : ' + @A1  ELSE '' END)+                       
    (CASE WHEN LEN(@Q2) > 0 THEN ' | ' + @Q2 +' : ' + @A2  ELSE '' END)+                      
    (CASE WHEN LEN(@Q3) > 0 THEN ' | ' + @Q3 +' : ' + @A3  ELSE '' END)                      
    END) FROM rvlfMDTFormMessages WHERE OrganizationId=@orgId AND FormMsgId=@Cancode                      
                          
    --SET @Cancode = CONVERT(INT, SUBSTRING(@vcAlarmDesc, CHARINDEX('Cancode=',@vcAlarmDesc) + 8,                       
    --     (CHARINDEX('User ID',@vcAlarmDesc) - CHARINDEX('Cancode=',@vcAlarmDesc) - 9)))                      
    --SET @vcAlarmDetail = REPLACE(SUBSTRING(@vcAlarmDesc, CHARINDEX('Message=',@vcAlarmDesc) + 0,                       
    --     (CHARINDEX('Group ID',@vcAlarmDesc) - CHARINDEX('Message=',@vcAlarmDesc) - 0)),'Message=','')                      
    --SELECT @vcAlarmDetail=REPLACE(REPLACE(REPLACE(MsgName,'$',''),'@',''),'-','')+' : '+REPLACE(@vcAlarmDetail,'\~','')+' <br /> User : '+                      
    --(SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId=(SUBSTRING(@vcAlarmDesc, CHARINDEX('User ID=',@vcAlarmDesc) + 8,                      
    --(CHARINDEX('Message',@vcAlarmDesc) - CHARINDEX('User ID=',@vcAlarmDesc) - 9))))                      
    --FROM rvlfMDTFormMessages WHERE OrganizationId IN                      
    --(SELECT OrganizationId FROM rvlfBoxId WHERE BoxId=@intBoxID) AND FormMsgId=@Cancode                      
   END                            
   ELSE                  
   BEGIN                      
                      
    SET @Cancode = CONVERT(INT, SUBSTRING(@vcAlarmDesc, CHARINDEX('Cancode=',@vcAlarmDesc) + 8,                       
         (CHARINDEX('User ID',@vcAlarmDesc) - CHARINDEX('Cancode=',@vcAlarmDesc) - 9)))                      
                               
    SELECT @vcAlarmDetail = MsgName FROM rvlfPrecannedMessages WHERE PrecannedMsgId = @Cancode AND IsServerMsg = 0                      
    SET @vcAlarmDetail = 'Msg=' + @vcAlarmDetail                       
                          
    --SET @MDTUserId = SUBSTRING(@vcAlarmDesc, CHARINDEX('User ID=',@vcAlarmDesc) + 8,                     
    --     (CHARINDEX('Group ID',@vcAlarmDesc) - CHARINDEX('User ID=',@vcAlarmDesc) - 9))                      
                      
   END                 
                               
   --IF EXISTS (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUserId AND BoxId = @intBoxID)             
   --BEGIN                      
                        
   -- SET @MDTUserId = (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUserId AND BoxId = @intBoxID)                      
                        
      --END                      
                         
   --SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, 'Driver Msg', 'Msg from ' + @MDTUserId)                      
                         
  END                      
 ELSE IF @tiBoxMsgInTypeID = 78 -- External Sensor Status                      
  BEGIN                      
   SET @vcAlarmDetail = REPLACE(SUBSTRING(@vcAlarmDesc, CHARINDEX('ExSensorNo',@vcAlarmDesc) + 13,                       
      (LEN(@vcAlarmDesc) - CHARINDEX('ExSensorNo',@vcAlarmDesc))), ';', '')                      
   SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, ' degree Celsius' ,'°C')                       
      SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, ' mV' ,'lit.')                       
  END                      
 ELSE IF @tiBoxMsgInTypeID = 79 -- BioEntry                      
  BEGIN                      
   SET @vcAlarmDetail = 'BioEntry ' + SUBSTRING(@vcAlarmDesc, CHARINDEX('User Id',@vcAlarmDesc),                       
      (LEN(@vcAlarmDesc) - CHARINDEX('User Id',@vcAlarmDesc)))                      
                         
   DECLARE @UserId AS BIGINT = 0                      
   SET @UserId = CONVERT(BIGINT, REPLACE(SUBSTRING(@vcAlarmDetail, CHARINDEX('User Id',@vcAlarmDetail)+8,                       
      (LEN(@vcAlarmDetail)- CHARINDEX('User Id',@vcAlarmDetail))), ';', ''))                      
                         
   IF EXISTS(SELECT u.UserId FROM rvlfBiometricUsers u                      
       INNER JOIN rvlfVehicleAssignment va ON va.BoxId = @intBoxID                      
       INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId                      
       WHERE u.UserId = @UserId AND v.OrganizationId = 35)                      
   BEGIN                      
    SELECT @vcAlarmDetail = UserName FROM rvlfBiometricUsers WHERE UserId = @UserId                      
    SET @vcAlarmDetail = 'BioEntry User Name=' + @vcAlarmDetail                      
   END                      
  END                      
 ELSE IF @tiBoxMsgInTypeID = 80 -- Card Reader                      
 BEGIN                      
  SET @vcAlarmDetail = SUBSTRING(@vcAlarmDesc, CHARINDEX('Card ID',@vcAlarmDesc),                       
     (LEN(@vcAlarmDesc) - CHARINDEX('Card ID',@vcAlarmDesc) + 1))                      
 END                      
 ELSE IF @tiBoxMsgInTypeID = 89 -- Vehicle Fuel Fill                   
 BEGIN                      
  SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                      
                        
  IF CHARINDEX('Vehicle Fuel Fill=', @vcAlarmDesc) > 0                      
  BEGIN
   SET @vcAlarmDetail = SUBSTRING(@vcAlarmDesc, CHARINDEX('Vehicle Fuel Fill=',@vcAlarmDesc), (LEN(@vcAlarmDesc) - CHARINDEX('Vehicle Fuel Fill=',@vcAlarmDesc)) + 1)                      
   SET @vcAlarmDetail = CASE WHEN CHARINDEX(';',@vcAlarmDetail) <> 0 THEN @vcAlarmDetail ELSE @vcAlarmDetail + ';' END                      
   SET @vcAlarmDetail = SUBSTRING(@vcAlarmDetail, CHARINDEX('Vehicle Fuel Fill=',@vcAlarmDetail), (CHARINDEX(';', @vcAlarmDetail) - CHARINDEX('Vehicle Fuel Fill=',@vcAlarmDetail)))                      
   SET @vcAlarmDetail = REPLACE(@vcAlarmDetail,'litres','ml')
  END                      
 END                      
 ELSE IF @tiBoxMsgInTypeID = 90 -- Alarm - Vehicle Fuel Drain                      
 BEGIN                      
  SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                      
                        
  IF CHARINDEX('Actual Fuel Drained', @vcAlarmDesc) > 0                      
  BEGIN                      
                      
      SELECT @vcAlarmDetail = 'Actual Fuel Drained=' + (SUBSTRING(@vcAlarmDesc, CHARINDEX('Actual Fuel Drained',@vcAlarmDesc) + 20,                       
      (CHARINDEX(' litres',@vcAlarmDesc) - CHARINDEX('Actual Fuel Drained',@vcAlarmDesc)) - 20)) + ' litres'                      
  END                      
 END                      
 ELSE IF @tiBoxMsgInTypeID = 94 -- Send Voice Call Info                      
 BEGIN                      
                        
  SELECT @vcAlarmDetail = SUBSTRING(@vcAlarmDesc, CHARINDEX('Call Direction',@vcAlarmDesc),                       
      (CHARINDEX('Remote Number',@vcAlarmDesc) - CHARINDEX('Call Direction',@vcAlarmDesc)))                      
  SELECT @vcAlarmDetail = REPLACE(REPLACE(REPLACE(@vcAlarmDetail, '$$', ':'), 'Call Direction', 'Call'),                      
          'Call Duration', 'Duration')                      
                       
 END              
 ELSE IF @tiBoxMsgInTypeID = 98 -- MTD User Login Status to Server                      
 BEGIN                      
                        
  DECLARE @MDTUsrId AS Varchar(50) = SUBSTRING(@vcAlarmDesc, CHARINDEX('User ID=',@vcAlarmDesc) + 8,                       
           (CHARINDEX(';;',@vcAlarmDesc) - CHARINDEX('User ID=',@vcAlarmDesc) - 8))                      
                                 
  IF EXISTS (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUsrId AND UserId IN (SELECT UserId FROM rvlfMDTBoxMessageTable WHERE BoxId = @intBoxID))                      
  BEGIN                      
                        
   SET @MDTUsrId = (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUsrId AND UserId IN (SELECT UserId FROM rvlfMDTBoxMessageTable WHERE BoxId = @intBoxID))        
                        
  END                      
                                 
  SET @vcAlarmDetail = @MDTUsrId + ' logged ' + SUBSTRING(@vcAlarmDesc, CHARINDEX('Login Status=',@vcAlarmDesc) + 13,                       
           (CHARINDEX(';',@vcAlarmDesc) - CHARINDEX('Login Status=',@vcAlarmDesc) - 13))                      
                       
 END                      
 ELSE IF @tiBoxMsgInTypeID = 100 -- RFID Message                      
 BEGIN                      
                               
  SET @vcAlarmDetail = REPLACE(@vcAlarmDesc, ';', '')                       
                     
 END                      
 ELSE IF @tiBoxMsgInTypeID IN (37, 38, 39, 42, 45, 46, 47, 48, 49, 50)                      
  BEGIN                      
   --SET @FuelLevelPercentage =(( CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                      
   --   THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                      
   --   LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int) * 33)-600)/24.1                      
    SET @FuelLevelPercentage =CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0         
      THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                      
      LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int)                      
   SET @FuelLevelPercentage = CASE WHEN @FuelLevelPercentage <=0 THEN 0 ELSE @FuelLevelPercentage END                      
   SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = ISNULL(CapacityUnits,'gals') FROM rvlfVehicle v INNER JOIN                      
    rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID                      
                         
   SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                      
   SELECT @vcAlarmDetail = @vcAlarmDetail                       
    + ' ('+ cast(@FuelLevelPercentage as varchar(3))+ '% - '+                       
    cast(cast(((@FuelLevelPercentage / 100.00) * @tankCapacity)as int) as varchar(5)) +' '+ @vcFuelUnits +')'                  
     --CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                      
     -- THEN ' (' +  REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                      
     -- LEN(@vcAlarmDesc)), ';', '%)') ELSE '' END                      
  END                      
 --ELSE IF @tiBoxMsgInTypeID = 54                      
 -- BEGIN                      
 --  --SELECT @vcAlarmDetail = '<table><tr><td>'+ REPLACE(REPLACE(@vcAlarmDesc,'=','<td>:</td><td>'),';','</td></tr><tr><td>' )+'</table>'                      
 -- END                      
 --ELSE IF @tiBoxMsgInTypeID = 51                      
 -- BEGIN                      
 --  SET @vcAlarmDetail = 'Speed viol                      
 -- END                      
 ELSE IF @tiBoxMsgInTypeID = 97 -- Send harsh thresholds                      
  BEGIN                      
   DECLARE @VCHB VARCHAR(10),@VCEB VARCHAR(10),@VCHA VARCHAR(10),@VCEA VARCHAR(10),@VCHC VARCHAR(10),@VCHCA VARCHAR(10)                      
                         
   SET @VCHB= CASE WHEN @vcAlarmDesc LIKE '%HB=%' THEN SUBSTRING(@vcAlarmDesc,CHARINDEX('HB=',@vcAlarmDesc,1)+3,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('HB=',@vcAlarmDesc,1))-(CHARINDEX('HB=',@vcAlarmDesc,1)+3)) ELSE '0' END                      
   SET @VCEB=CASE WHEN @vcAlarmDesc LIKE '%EB=%' THEN SUBSTRING(@vcAlarmDesc,CHARINDEX('EB=',@vcAlarmDesc,1)+3,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('EB=',@vcAlarmDesc,1)) - (CHARINDEX('EB=',@vcAlarmDesc,1)+3)) ELSE '0' END                      
   SET @VCHA=CASE WHEN @vcAlarmDesc LIKE '%HA=%' THEN SUBSTRING(@vcAlarmDesc,CHARINDEX('HA=',@vcAlarmDesc,1)+3,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('HA=',@vcAlarmDesc,1))-(CHARINDEX('HA=',@vcAlarmDesc,1)+3)) ELSE '0' END                      
   SET @VCEA=CASE WHEN @vcAlarmDesc LIKE '%EA=%' THEN SUBSTRING(@vcAlarmDesc,CHARINDEX('EA=',@vcAlarmDesc,1)+3,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('EA=',@vcAlarmDesc,1))-(CHARINDEX('EA=',@vcAlarmDesc,1)+3))ELSE '0' END                      
   SET @VCHC=CASE WHEN @vcAlarmDesc LIKE '%HC=%' THEN SUBSTRING(@vcAlarmDesc,CHARINDEX('HC=',@vcAlarmDesc,1)+3,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('HC=',@vcAlarmDesc,1))-(CHARINDEX('HC=',@vcAlarmDesc,1)+3))ELSE '0' END                      
   SET @VCHCA=CASE WHEN @vcAlarmDesc LIKE '%HC_Angle=%' THEN SUBSTRING(@vcAlarmDesc,CHARINDEX('HC_Angle=',@vcAlarmDesc,1)+9,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('HC_Angle=',@vcAlarmDesc,1))-(CHARINDEX('HC_Angle=',@vcAlarmDesc,1)+9))ELSE '0' END          




  
    
      
        
                       
    SET @vcAlarmDetail='Harsh Braking='+ @VCHB+' Miles;Extreme Braking='+@VCEB+' Miles;Harsh Acceleration='+@VCHA+' Miles;Extreme Acceleration='+@VCEA+' Miles;Harsh Corner='+@VCHC+' Miles;Harsh Corner_Angle='+@VCHCA+';'                                    




 
  END                      
 ELSE IF @tiBoxMsgInTypeID = 23 -- Battery Status messages                      
  BEGIN                      
   DECLARE @tintBatteyId tinyint=null                      
   DECLARE @vcBatteryName varchar(50)=null                      
   SET @tintBatteyId = CASE WHEN @vcAlarmDesc LIKE '%Battery Name=%' THEN CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('Battery Name=',@vcAlarmDesc,1)+13,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('Battery Name=',@vcAlarmDesc,1))-                    
   (CHARINDEX('Battery Name=',@vcAlarmDesc,1)+13)) AS TINYINT) ELSE 0 END                      
                         
   IF(@tintBatteyId=1)                      
    BEGIN                      
     SET @vcBatteryName='Main Battery Disconnected'                      
    END            
   ELSE IF(@tintBatteyId=2)                      
    BEGIN                      
     SET @vcBatteryName='Main Battery Connected'                      
    END             
   ELSE IF(@tintBatteyId=3)                      
    BEGIN               
     SET @vcBatteryName='Backup Battery Disconnected'              
    END                      
   ELSE IF(@tintBatteyId=4)                      
    BEGIN                      
     SET @vcBatteryName='Backup Battery Connected'                      
    END                      
   ELSE IF(@tintBatteyId=5)                      
    BEGIN                      
     SET @vcBatteryName='Backup Battery Empty'                      
    END                      
   ELSE                      
    BEGIN                      
     SET @vcBatteryName='Battery Status'                      
    END                      
                         
    SET @vcAlarmDetail=@vcBatteryName                      
  END                      
 ELSE IF @tiBoxMsgInTypeID = 113 -- Speed Band                      
 BEGIN                      
  SET @vcAlarmDetail=SUBSTRING(@vcAlarmDesc,CHARINDEX('Band Name=',@vcAlarmDesc,1)+10,(CHARINDEX(';',@vcAlarmDesc,CHARINDEX('Band Name=',@vcAlarmDesc,1))-(CHARINDEX('Band Name=',@vcAlarmDesc,1)+10)))+' ['+                      
  dbo.rvlf_fn_GetTimeFromSeconds(CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('Duration=',@vcAlarmDesc,1)+9,(CHARINDEX(';',@vcAlarmDesc,CHARINDEX('Duration=',@vcAlarmDesc,1))-(CHARINDEX('Duration=',@vcAlarmDesc,1)+9))) as int))+']'                      
 END                      
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('08;Idling:',@vcAlarmDesc) <> 0  --Sakthi 21-May-2012 for Idling Time                      
 BEGIN                      
  --SELECT @vcAlarmDetail =SUBSTRING(@vcAlarmDesc,4,LEN(@vcAlarmDesc))                      
  --SELECT @vcAlarmDetail = REPLACE(@vcAlarmDetail,':',' : ')                      
  --SELECT @vcAlarmDetail = REPLACE(@vcAlarmDetail,';',' secs </br> ')+' secs'                      
  SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeId=122                      
 END                      
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('09;Engine',@vcAlarmDesc) <> 0  --Sakthi 05-Jun-2012 for Send Vehicle Parameter                      
 BEGIN                      
  SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeId=123                      
 END                      
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('10;Odometer Offset:',@vcAlarmDesc) <> 0  --Sakthi 05-Jun-2012 for Odometer Offset and MAF State                      
 BEGIN                      
  SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeId=124                      
 END                      
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('02;StopId:',@vcAlarmDesc) <> 0  --Sakthi 19-Jan-2012 for Garmin                      
 BEGIN                     
 SELECT @vcAlarmDetail = replace((ISNULL((SELECT top 1 ISNULL((R.RouteName+'-'),'')+l.LandmarkName FROM rvlfLandmark l                             
  inner join rvlfVehicle v on l.OrganizationId=v.OrganizationId inner join rvlfVehicleAssignment va on va.VehicleId=v.VehicleId              left join rvlfRouteMaster R on v.OrganizationId=R.OrgID and r.GRouteId=SUBSTRING(@vcAlarmDesc,CharIndex('RouteId:



'
  
    
      
,@vcAlarmDesc)+8,LEN(@vcAlarmDesc))                            
 where va.BoxId=@intBoxID and                    
  l.LandmarkID=SUBSTRING(@vcAlarmDesc,CharIndex('StopId:',@vcAlarmDesc)+7,(CHARINDEX(';Status',@vcAlarmDesc)-(CHARINDEX('StopId:',@vcAlarmDesc)+7))))+ ' - '+                                              
  SUBSTRING(@vcAlarmDesc,CharIndex(';Status',@vcAlarmDesc)+8,CHARINDEX(';RouteId',@vcAlarmDesc,0)-(CHARINDEX(';Status',@vcAlarmDesc,0)+8)),'Deleted Stop')),' Read Inactive',' Reached')     
  --SELECT @vcAlarmDetail = ISNULL((SELECT l.LandmarkName FROM rvlfLandmark l INNER JOIN rvlfGarminStop gs ON gs.LandmarkId=l.LandmarkID                      
  --INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=gs.VehicleId                      
  --WHERE va.BoxId= @intBoxID AND                      
  --gs.StopId=SUBSTRING(@vcAlarmDesc,CharIndex('StopId:',@vcAlarmDesc)+7,(CHARINDEX(';Status',@vcAlarmDesc)-(CHARINDEX('StopId:',@vcAlarmDesc)+7))))+ ' - '+                      
  --SUBSTRING(@vcAlarmDesc,CharIndex(';Status',@vcAlarmDesc)+8,LEN(@vcAlarmDesc)),'Deleted Stop')                      
 END                      
                     
                     
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('IsRouteCompleted:',@vcAlarmDesc) <> 0  --Sakthi 06-Jan-2014 for Garmin, 19feb2014 route                                
 BEGIN                                   
  if SUBSTRING(@vcAlarmDesc,CHARINDEX(';IsRouteCompleted:',@vcAlarmDesc)+18,1)  ='0'                                
  BEGIN                                  
 SELECT @vcAlarmDetail = ISNULL(RouteName,'NA')+ISNULL(l.LandmarkName,'NA') + ' Delayed.'                        
 from rvlfRouteMaster R inner join rvlfGarminRoute GR on r.GRouteId=GR.RouteId                                
 inner join rvlfLandmark l on GR.LanmarkId=l.LandmarkID WHERE GRouteID =         
 SUBSTRING(@vcAlarmDesc,12,CHARINDEX(';StopId',@vcAlarmDesc)-12)  and                                
 l.LandmarkID=SUBSTRING(@vcAlarmDesc, CHARINDEX('StopId:',@vcAlarmDesc,0)+7,(CHARINDEX(';',@vcAlarmDesc,CHARINDEX('StopId:',@vcAlarmDesc,1)))                                
 -(CHARINDEX('StopId:',@vcAlarmDesc,1)+7))                                 
  END                                
  Else --if SUBSTRING(@vcAlarmDesc,CHARINDEX(';IsRouteCompleted:',@vcAlarmDesc)+18,1)  =1                                
   BEGIN                                
 SELECT @vcAlarmDetail = ISNULL(RouteName,'NA') +                                 
case when SUBSTRING(@vcAlarmDesc,CHARINDEX(';IsRouteCompleted:',@vcAlarmDesc)+18,1)  ='1' then  ' Route Completed.'                                 
 when SUBSTRING(@vcAlarmDesc,CHARINDEX(';IsRouteCompleted:',@vcAlarmDesc)+18,1)  ='2' then  ' Route assign completed by the device.'                                 
 when SUBSTRING(@vcAlarmDesc,CHARINDEX(';IsRouteCompleted:',@vcAlarmDesc)+18,1)  ='3' then  ' Route Deletion completed by the device.' end                                 
 FROM rvlfRouteMaster WHERE GRouteID =                                        
 SUBSTRING(@vcAlarmDesc,12,CHARINDEX(';StopId',@vcAlarmDesc)-12)                               
  END                                
 END                      
                  
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('; Fuel Consumption',@vcAlarmDesc) <> 0  --Sakthi 24-Feb-2012 for OBD                      
 BEGIN                      
  SELECT @vcAlarmDetail ='Mileage : '+                      
  CAST(CAST(CAST(SUBSTRING(@vcAlarmDesc,12,CHARINDEX('; Fuel Consumption',@vcAlarmDesc,0)-12) AS decimal(10,2))/1000 AS DECIMAL(10,2)) AS VARCHAR)+' Kmpl and Fuel '+                      
  CAST(CAST(CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('; Fuel Consumption',@vcAlarmDesc,0)+19,LEN(@vcAlarmDesc)-(CHARINDEX('; Fuel Consumption',@vcAlarmDesc,0)+18)) AS decimal(10,2))/1000 AS DECIMAL(10,2)) AS VARCHAR)+' lit'                      
 END                      
 ELSE IF  @tiBoxMsgInTypeID=114 AND CharIndex('06;No of DTC',@vcAlarmDesc) <> 0                      
 BEGIN                      
  SET @vcAlarmDetail= CASE WHEN CAST(SUBSTRING(@vcAlarmDesc,20,1) AS INT)=0 THEN 'No DTC Codes'                      
       ELSE 'DTC Codes' END                      
 END                      
                     
 ELSE IF  @tiBoxMsgInTypeID=114 AND SUBSTRING(@vcAlarmDesc, CHARINDEX('GeozoneInOutWithDuration:',@vcAlarmDesc)+25,1) = '1'  -- Ranjith Geozone InOut with Duration 15-Mar-2013                                  
 Begin                                            
 DECLARE @vcGeozoneName varchar(50)=null                                             
 SELECT @vcGeozoneName = g.GeozoneName                           
 FROM rvlfOrganizationGeozone g INNER JOIN rvlfVehicle v                                             
     ON g.OrganizationId=v.OrganizationId INNER JOIN rvlfVehicleAssignment va ON                                             
     v.VehicleId = va.VehicleId               
     INNER JOIN rvlfVehicleGeozone vg ON vg.VehicleID = v.VehicleID AND                                             
        vg.GeozoneNo = g.GeozoneId                                            
     WHERE BoxId = @intBoxID and GeozoneId = --CAST(@vcAlarmDesc as bigint)                                            
     (CAST( SUBSTRING(@vcAlarmDesc, CHARINDEX('GeozoneID=',@vcAlarmDesc,0)+10,                                            
     (CHARINDEX(';',@vcAlarmDesc,CHARINDEX('GeozoneID=',@vcAlarmDesc,1)))                                             
-(CHARINDEX('GeozoneID=',@vcAlarmDesc,1)+10)) as bigint))                                         
                                             
--  SET @vcAlarmDetail='Geozone='+ isnull(@vcGeozoneName,'Unknown') + ' Out (Duration:' + Replace(SUBSTRING(@vcAlarmDesc, CHARINDEX(';Duration', @vcAlarmDesc)+10,LEN(@vcAlarmDesc)),':',':') + ')'                                         
  SET @vcAlarmDetail= isnull(@vcGeozoneName,'Unknown Geozone') + ' - Out (Duration:' + Replace(SUBSTRING(@vcAlarmDesc, CHARINDEX(';Duration', @vcAlarmDesc)+10,LEN(@vcAlarmDesc)),':',':') + ')'                  
 End
                  
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('34;RouteID=',@vcAlarmDesc) <> 0                                                              
 BEGIN                                 
 Declare @RouteID bigint=0,@StopID bigint=0                  
 Declare @RouteName Varchar(150)=null,@StopName Varchar(150)=null,@RouteAlertMsg varchar(3)=null                  
 set @RouteID=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'RouteID=',';'))                  
 set @RouteName = isnull((select RouteName from rvlfRouteMaster where RouteID=@RouteID),'Invalid Route')                  
 set @StopID=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'StopID=',';'))                  
 set @StopName = isnull((select GeozoneName from rvlfOrganizationGeozone where GeozoneId=@StopID and OrganizationId = (select OrganizationId from rvlfBoxId where BoxId=@intBoxID)),'Invalid Stop')                 
 set @RouteAlertMsg=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'AlertMsg=',';'))                  
 SET @vcAlarmDetail= (case when @RouteAlertMsg=001 then @RouteName +' Route started.'                  
       when @RouteAlertMsg=010 then @RouteName +' Route-'+@StopName+ ' Stop Arrival.'                  
       when @RouteAlertMsg=011 then @RouteName +' Route-'+@StopName+ ' Stop Departure.'                  
       when @RouteAlertMsg=100 then @RouteName +' Route-'+@StopName+ ' Stop Completion.'                  
       when @RouteAlertMsg=101 then @RouteName +' Route-'+@StopName+ ' Stop Start Delay.'                  
       when @RouteAlertMsg=110 then @RouteName +' Route-'+@StopName+ ' Stop Delay.'                  
       when @RouteAlertMsg=111 then @RouteName +' Route Delay.' else 'Unkown Route Details' end)           
 set @StopID=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'NxtStopID=',';'))                  
 set @StopName = isnull((select GeozoneName from rvlfOrganizationGeozone where GeozoneId=@StopID and OrganizationId = (select OrganizationId from rvlfBoxId where BoxId=@intBoxID)),'Invalid Stop')        
         
 set @vcAlarmDetail = @vcAlarmDetail + ';NxtStop-' + @StopName --+ ';Duration(Mints):'+ dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'Duration(Mints)=',';') +';Distance(KM):'+ dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'Distance=',';')        
                 
 END  --34;RouteID=114;StopID=64;NxtStopID=65;Duration(Mints)=0;Distance=1024;AlertMsg=111                
          
 ELSE IF @tiBoxMsgInTypeID = 114 and CHARINDEX('38;FuelTankLength',@vcAlarmDesc,0) <> 0  
 BEGIN 
	set @vcAlarmDetail = 'Send Ultrasonic Fuel Sensing Parameters'  
 END
                   
ELSE IF @tiBoxMsgInTypeID = 161                              
BEGIN                              
 SELECT @vcAlarmDetail='Sudden Temperature Fall (Variance : ' + SUBSTRING( @vcAlarmDesc,CHARINDEX('Variance=',@vcAlarmDesc,0)+9, (CHARINDEX(';',@vcAlarmDesc,CHARINDEX('Variance=',@vcAlarmDesc,0))-(CHARINDEX('Variance=',@vcAlarmDesc,0)+9))) +'°C)'        



END                  

 ELSE IF @tiBoxMsgInTypeID=152                                        
BEGIN                                   
 SELECT @vcAlarmDetail='Restricted Geozone ' +ISNULL(og.GeozoneName,'')+' IN' FROM rvlfOrganizationGeozone og INNER JOIN rvlfBoxId b ON b.OrganizationId=og.OrganizationId                                        
WHERE og.GeozoneId=SUBSTRING(@vcAlarmDesc,CHARINDEX('GeozoneID=',@vcAlarmDesc,0)+10,(CHARINDEX(';Odometer=',@vcAlarmDesc,0)-                                        
 (CHARINDEX('GeozoneID=',@vcAlarmDesc,0)+10))) AND og.OrganizationId=6                                        
END                     
                     
   --Route Alerts 13-Apr-15        
 --ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('34;RouteID:',@vcAlarmDesc) <> 0                                                    
 --BEGIN                       
 --Declare @RouteID bigint=0,@StopID bigint=0        
 --Declare @RouteName Varchar(150)=null,@StopName Varchar(150)=null,@RouteAlertMsg varchar(3)=null        
 --set @RouteID=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'RouteID:',';'))        
 --set @RouteName = (select RouteName from rvlfRouteMaster where RouteID=@RouteID)        
 --set @StopID=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'StopID:',';'))        
 --set @StopName = (select LandmarkName from rvlfLandmark where LandmarkID=@StopID)        
 --set @RouteAlertMsg=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'AlertMsg:',';'))        
 --SET @vcAlarmDetail= (case when @RouteAlertMsg=001 then @RouteName +' Route started.'        
 --      when @RouteAlertMsg=010 then @RouteName +' Route'+@StopName+ ' Stop Arrival.'        
 --      when @RouteAlertMsg=011 then @RouteName +' Route'+@StopName+ ' Stop Departure.'        
 --      when @RouteAlertMsg=100 then @RouteName +' Route'+@StopName+ ' Stop Completion.'        
 --      when @RouteAlertMsg=101 then @RouteName +' Route'+@StopName+ ' Stop Start Delay.'        
 --      when @RouteAlertMsg=110 then @RouteName +' Route'+@StopName+ ' Stop Delay.'        
 --      when @RouteAlertMsg=111 then @RouteName +' Route Delay.' else 'Unkown Route Details' end)        
 --END                  
                     
 ELSE                      
 BEGIN                      
                        
  SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                      
  IF  @tiBoxMsgInTypeID=109 OR @tiBoxMsgInTypeID=110 OR @tiBoxMsgInTypeID=125 OR @tiBoxMsgInTypeID=126                      
  BEGIN                      
    SET @vcAlarmDetail = REPLACE(@vcAlarmDetail,'Non Alarm-','')                      
  END                      
  IF EXISTS (SELECT * FROM rvlfPackageOperations r                      
     INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId                      
     INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId                      
     INNER JOIN rvlfVehicle v ON g.OrganizationId = v.OrganizationId                       
     INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId                      
       WHERE p.IsActive = 1 AND va.BoxId = @intBoxID AND r.OperationID = 95)                      
       AND                      
       --Commented on 30-Jul-10 for Testing GetBoxStatus                      
       @tiBoxMsgInTypeID NOT IN (19,20,21,22,35,40,55,54,56,53,1,12,10) --or @intBoxID = 999985 --or @intBoxID = 999983      
       --@tiBoxMsgInTypeID NOT IN (19,20,21,35,40,55,54,56,53) --or @intBoxID = 999985                      
       --End                      
   BEGIN                      
    --SET @FuelLevelPercentage =(( CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                      
    --  THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                      
    --  LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int) * 33)-600)/24.1                      
                          
    IF CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                      
    BEGIN                      
     SET @FuelLevelPercentage =CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                      
       THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                      
       LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int)                      
     SET @FuelLevelPercentage = CASE WHEN @FuelLevelPercentage <=0 THEN 0 ELSE @FuelLevelPercentage END                      
     SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = ISNULL(CapacityUnits,'gals') FROM rvlfVehicle v INNER JOIN                      
      rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID                      
                           
     SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                      
     SELECT @vcAlarmDetail = @vcAlarmDetail                       
     +                       
      CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                      
       THEN ' (Fuel Level = '                       
       + cast(@FuelLevelPercentage as varchar(3))+ '% - '+                       
      cast(cast(((@FuelLevelPercentage / 100.00) * @tankCapacity)as int) as varchar(5)) +' '+ @vcFuelUnits +')'                      
     END                      
    END                      
   END                      
 END                       

 --Temperature Sensor Enabling
 SET @vcAlarmDetail =	REPLACE(REPLACE(REPLACE(REPLACE(@vcAlarmDetail, 'Temperature Sensor-1', 'Temperature-1')
												, 'Temperature Sensor-2', 'Temperature-2')
										, 'Temperature Sensor-3', 'Temperature-3')
								, 'Temperature Sensor-4', 'Temperature-4')                       
                       
 IF @tiBoxMsgInTypeID NOT IN (4,18,42,51,78,89,90)                      
 BEGIN                      
                       
  DECLARE @t1 AS Varchar(10)                      
  DECLARE @t2 AS Varchar(10)                                                        
  DECLARE @t3 AS Varchar(10)                       
  DECLARE @t4 AS Varchar(10)                       
  DECLARE @fuel AS Varchar(10)                      
  DECLARE @Temp1 as bit                      
  DECLARE @Temp2 as Bit                                                           
  DECLARE @Temp3 as bit = 1                      
  DECLARE @Temp4 as Bit = 1                          
  DECLARE @vcAlarmTemp As Varchar(1000)                      
                        
  SET @vcAlarmTemp = @vcAlarmDesc                      
                          
    --Enable the temparature sensor                      
     DECLARE @tblTempDetails TABLE(Temp INT,Temp2 INT, Temp3 INT, Temp4 INT)                      
     INSERT into @tblTempDetails (Temp,Temp2,Temp3,Temp4)                      
     SELECT Temp1 = CASE WHEN PO.OperationID IN(179) and PO.ModuleID = 26 THEN 1 ELSE 0 END,                      
			Temp2 = CASE WHEN PO.OperationID IN(180) and PO.ModuleID = 26 THEN 1 ELSE 0 END,
			Temp3 = CASE WHEN PO.OperationID IN(396) and PO.ModuleID IN (26) THEN 1 ELSE 0 END,
			Temp4 = CASE WHEN PO.OperationID IN(397) and PO.ModuleID IN (26) THEN 1 ELSE 0 END
     FROM rvlfVehicleAssignment va                       
     Inner JOIN  rvlfBoxId b ON  b.BoxId = va.BoxId                      
    INner join rvlfOrganization o ON o.OrganizationId = b.OrganizationId                      
     INNER JOIn rvlfOrganizationPackage p ON p.OrganizationID =o.OrganizationId                      
     INNER JOIn rvlfPackageOperations po ON po.PackageId = p.PackageId                      
     WHERE po.ModuleID =26 and p.IsActive =1   AND b.BoxId IN (@intBoxID) AND @intBoxID NOT IN (4483,4482,999222)      
     OR (@intBoxID IN (999986,165,166,167,168,40,283,242,667,646,647,648,685,686,687,2149,2150,2151,4183,4184,4185,4186,4187) or @intBoxID between 2115 and 2146)                        
     AND PO.OperationID IN (179,180,231,234,396,397)  GROUP BY po.OperationID,po.ModuleID                      

     SELECT @Temp1 = MAX(Temp), @Temp2 = MAX(Temp2), @Temp3 = MAX(Temp3), @Temp4 = MAX(Temp4) from @tblTempDetails                                                        
                        
       -- IF EXISTS(SELECT va.BoxId FROM rvlfVehicleAssignment va                      
       --INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId                      
       --WHERE ((va.BoxId = @intBoxID AND v.OrganizationId = 6) OR (@intBoxId=652 AND @dtOriginDateTime > CAST('2012-02-14 00:00:00.000' AS datetime))                      
       --OR @intBoxID IN (165,166,167,168,40,283,242,667,646,647,648,685,686,687,2149,2150,2151)) or @intBoxID between 2115 and 2146 AND @intBoxID <> 999222)                      
 IF (@Temp1 = 1 OR  @Temp1 = 0)                      
  BEGIN                      
                          
   -- Check Temperature Sensor 1 & 2                      
   IF CHARINDEX('Temperature Sensor-1 Value',@vcAlarmDesc, 1) <> 0                       
   --IF CHARINDEX('Temperature Sensor-1 Value',@vcAlarmDesc, 1) <> NULL                      
   BEGIN                      
    IF(@Temp1 =1)                      
    BEGIN                      
     IF SUBSTRING(@vcAlarmDesc, CHARINDEX('Temperature Sensor-1 Value',@vcAlarmDesc)+27, 12) = 'Disconnected'                      
     BEGIN                      
        
    SET @t1 = 'PD'                      
                  END                      
     ELSE                      
     BEGIN                      
                           
    SET @t1 = SUBSTRING(@vcAlarmDesc, CHARINDEX('Temperature Sensor-1 Value',@vcAlarmDesc)+27,                       
        (CHARINDEX(' degree Celsius',@vcAlarmDesc) - CHARINDEX('Temperature Sensor-1 Value',@vcAlarmDesc))-27)                      
                         
     END                      
   END                          
     IF CHARINDEX('Temperature Sensor-2 Value',@vcAlarmDesc, 1) <> 0 AND @Temp2 = 1                      
     --IF CHARINDEX('Temperature Sensor-2 Value',@vcAlarmDesc, 1) <> NULL                      
     BEGIN                      
      SET @vcAlarmTemp = SUBSTRING(@vcAlarmDesc, CHARINDEX('Temperature Sensor-2 Value',@vcAlarmDesc),                       
        (LEN(@vcAlarmDesc) - CHARINDEX('Temperature Sensor-2 Value',@vcAlarmDesc)))                      
     END                      
   END                      
                         
      IF (@intBoxID NOT IN (165,166,167,168,40,999983,667,646,647,648,2149,2150,2151,4187,4045,4046,4063,4235) AND @Temp2 = 1)                      
      BEGIN                      
    IF CHARINDEX('Temperature Sensor-2 Value',@vcAlarmTemp, 1) <> 0                      
    --IF CHARINDEX('Temperature Sensor-2 Value',@vcAlarmTemp, 1) <> NULL                      
    BEGIN                      
                          
  IF SUBSTRING(@vcAlarmTemp, CHARINDEX('Temperature Sensor-2 Value',@vcAlarmTemp)+27, 13) = 'Disconnected'                      
      BEGIN                      
       
     SET @t2 = 'PD'                      
       
      END                      
      ELSE                      
      BEGIN                      
                            
     SET @t2 = SUBSTRING(@vcAlarmTemp, CHARINDEX('Temperature Sensor-2 Value',@vcAlarmTemp)+27,                       
         (CHARINDEX(' degree Celsius',@vcAlarmTemp) - CHARINDEX('Temperature Sensor-2 Value',@vcAlarmTemp))-27)          
                               
      END                      
                          
    END                      
   END                      
   --Temperature 3 and 4 22-Nov-2014                      
   IF CHARINDEX('Temperature Sensor-3 Value',@vcAlarmDesc, 1) <> 0                                                         
   BEGIN                                                 
  IF(@intBoxID IN (5247,5248/*,999888*/) AND @Temp3 =1)                                                        
  BEGIN                                                        
    IF SUBSTRING(@vcAlarmDesc, CHARINDEX('Temperature Sensor-3 Value',@vcAlarmDesc)+27, 12) = 'Disconnected'                                                        
    BEGIN                                                        
     SET @t3 = 'PD'                                                        
    END                                                        
    ELSE                                               
    BEGIN                                                      
     SET @t3 = SUBSTRING(@vcAlarmDesc, CHARINDEX('Temperature Sensor-3 Value',@vcAlarmDesc)+27,                                                         
     (CHARINDEX(' degree Celsius',@vcAlarmDesc,CHARINDEX('Temperature Sensor-3 Value',@vcAlarmDesc)) -                       
     CHARINDEX('Temperature Sensor-3 Value',@vcAlarmDesc))-27)                                                        
    END	                      
	IF(@tiBoxMsgInTypeID NOT IN (1))
	BEGIN
		SET @t1=null
		SET	@t2=null
		SET	@t3=null
		SET @t4=null
	END                                                       
  END                                                                                     
   END                        
   IF CHARINDEX('Temperature Sensor-4 Value',@vcAlarmDesc, 1) <> 0                                                         
   BEGIN                                                 
  IF(@intBoxID IN (0) AND @Temp4 =1)			--No boxid is configured currently 27-Oct-15                                                        
  BEGIN                                                        
    IF SUBSTRING(@vcAlarmDesc, CHARINDEX('Temperature Sensor-4 Value',@vcAlarmDesc)+27, 12) = 'Disconnected'                                                        
    BEGIN                                                        
     SET @t4 = 'PD'                                                        
    END                                                        
    ELSE                                               
    BEGIN                                                      
     SET @t4 = SUBSTRING(@vcAlarmDesc, CHARINDEX('Temperature Sensor-4 Value',@vcAlarmDesc)+27,                                            
     (CHARINDEX(' degree Celsius',@vcAlarmDesc,CHARINDEX('Temperature Sensor-4 Value',@vcAlarmDesc)) -                       
     CHARINDEX('Temperature Sensor-4 Value',@vcAlarmDesc))-27)                             
    END                                                        
  END                                                                                     
   END                         
                                                           
   IF (@t1 LIKE '%-126%')                                                        
    SET @t1='PD'                                                        
   IF (@t2 LIKE '%-126%')                                                        
    SET @t2='PD'                           
    IF (@t3 LIKE '%-126%')                             
    SET @t1='PD'                                                        
   IF (@t4 LIKE '%-126%')        
  SET @t2='PD'                         
   -- Append Temperature Sensor 1 & 2 and Fuel values along with the message if present                        
   SET @vcAlarmDetail = @vcAlarmDetail + (CASE                       
  WHEN (@t1 IS NOT NULL) AND (@t2 IS NOT NULL) AND (@t3 IS NOT NULL) AND (@t4 IS NOT NULL)  --AND (@intBoxID IN (999989)) 
		THEN ' (T1: ' + @t1 + '°C, T2: ' + @t2 + '°C, T3: ' +  @t3 + '°C, T4: ' + @t4 + '°C)' 
  WHEN (@t1 IS NOT NULL AND @t2 IS NOT NULL AND @t3 IS NOT NULL ) THEN ' (T1: ' + @t1 + '°C, T2: ' + @t2 + '°C, T3: ' + @t3 + '°C)'                       
  WHEN (@t1 IS NOT NULL) AND (@t2 IS NOT NULL) THEN ' (T1: ' + @t1 + '°C, T2: ' + @t2 + '°C)'                         
  WHEN (@t1 IS NOT NULL) THEN ' (T1: ' + @t1 + '°C)'      
  WHEN (@t2 IS NOT NULL) THEN ' (T2: ' + @t2 + '°C)'                                                        
  WHEN (@t3 IS NOT NULL) THEN ' (T3: ' + @t3 + '°C)'                           
  WHEN (@t4 IS NOT NULL) THEN ' (T4: ' + @t4 + '°C)'                           
	ELSE '' END)                                                        
SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, 'PD°C', 'PD')                      
                                    
   END                      
                         
  IF EXISTS(SELECT va.BoxId FROM rvlfVehicleAssignment va                      
       INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId                      
       WHERE va.BoxId = @intBoxID AND (v.OrganizationId IN (47, 6) OR @intBoxID = 35) AND @intBoxID <> 999222)                      
  BEGIN                  
   -- Check for Fuel                      
   IF CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0 AND CHARINDEX('Ignition',@vcAlarmDetail, 1) = 0                      
   BEGIN                         
    SET @vcAlarmTemp = SUBSTRING(@vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc), (LEN(@vcAlarmDesc) - CHARINDEX('Fuel%=',@vcAlarmDesc)) + 1)                      
    SET @vcAlarmTemp = CASE WHEN CHARINDEX(';',@vcAlarmTemp) <> 0 THEN @vcAlarmTemp ELSE @vcAlarmTemp + ';' END                      
    SET @fuel = SUBSTRING(@vcAlarmTemp, CHARINDEX('Fuel%=',@vcAlarmTemp) + 6, (CHARINDEX(';', @vcAlarmTemp) - CHARINDEX('Fuel%=',@vcAlarmTemp)) - 6)                                                
   END
                         
   IF (@fuel IS NOT NULL and @tiBoxMsgInTypeID not in (42,130,131,134,135,136,145,152,182,183,184,185))                      
   BEGIN                          
		--DECLARE @fuelInLit AS Varchar(20)                      
		--Get fuel tank capacity to calcuate fuel percentage                      
		--SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = ISNULL(CapacityUnits,'gals') FROM rvlfVehicle v INNER JOIN                      
		--  rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID                      
		--SET @fuelInLit = (CASE WHEN (@fuel = 'Transition' OR @fuel = '0') THEN '0 lit.'                       
		--	  ELSE CAST(ROUND(CAST(((@fuel / 100.00) * @tankCapacity) AS DECIMAL), 0, 0) AS Varchar(10)) + ' lit.' END)                      
			  --ELSE CAST(ROUND(CAST(((@fuel / 100.00) * (CASE WHEN @intBoxID IN (189, 35, 190, 999982) THEN 225 ELSE 57 END)) AS DECIMAL), 0, 0) AS Varchar(10)) + ' lit.' END)                      
                                    
		--SET @vcAlarmDetail = (CASE WHEN CHARINDEX(')',@vcAlarmDetail, 1) <> 0                       
		--		THEN REPLACE(@vcAlarmDetail, ')', (', ' + (CASE WHEN @fuel = 'Transition' THEN 'Fuel Transition' ELSE                      
		--				('Fuel: ' + @fuel + '% - ' + @fuelInLit) END) + ')'))                      
		--		ELSE @vcAlarmDetail + ' (' + (CASE WHEN @fuel = 'Transition' THEN 'Fuel Transition' ELSE                      
		--				('Fuel: ' + @fuel + '% - ' + @fuelInLit) END) + ')' END) 
		
		SET @vcAlarmDetail = (CASE	WHEN CHARINDEX(')',@vcAlarmDetail, 1) <> 0 
								THEN REPLACE(@vcAlarmDetail, ')', (', ' + (CASE WHEN @fuel = 'Transition' THEN 'Fuel Transition' 
																				WHEN @fuel = 'FuelProbe' THEN 'Fuel Probe Disconnected/Not-installed' 
																				WHEN @fuel = 'FuelModule' THEN 'Fuel Module Disconnected'
																				ELSE ('Fuel: ' + @fuel + '%') END) + ')'))
								ELSE @vcAlarmDetail + ' (' + (CASE  WHEN @fuel = 'Transition' THEN 'Fuel Transition' 
																	WHEN @fuel = 'FuelProbe' THEN 'Fuel Probe Disconnected/Not-installed' 
																	WHEN @fuel = 'FuelModule' THEN 'Fuel Module Disconnected' 
																	ELSE ('Fuel: ' + @fuel + '%') END) + ')' END)
   END                      
  END      
 END                      
                       
 -- Return the result of the function      
 RETURN @vcAlarmDetail                      
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetAlarmDetails_New]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetAlarmDetails_New]                          
(                          
 @vcAlarmDesc varchar(1000),                          
 @tiBoxMsgInTypeID tinyint,                          
 @intBoxID varchar(15) = null,                          
 @uiMessageInId uniqueidentifier = null,                          
 @dtOriginDateTime DateTime = null,                          
 @Lang nvarchar(20) = null                            
)                          
RETURNS nvarchar(MAX)                          
AS                          
BEGIN                          
 DECLARE @vcAlarmDetail nvarchar(MAX)                              
 DECLARE @tiSensorID tinyint                              
 DECLARE @SecondsToConvert bigint                              
 DECLARE @vcMoxMsgInTypeName  nvarchar(100)                              
 DECLARE @tankCapacity int                               
 DECLARE @FuelLevelPercentage int                              
 DECLARE @vcFuelUnits varchar(10)                           
                           
 SELECT @vcMoxMsgInTypeName = Case when @Lang = 'LanguageArNew' Then isnull(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi' THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc)  else BoxMsgInTypeDesc  END FROM rvlfBoxMsgInType             






     
  WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                              
                           
 IF @tiBoxMsgInTypeID = 11 OR @tiBoxMsgInTypeID = 2 OR @tiBoxMsgInTypeID = 3                          
  OR @tiBoxMsgInTypeID= 13                          
 BEGIN                          
  DECLARE @vcActionOn nvarchar(25)                              
  DECLARE @vcActionOff nvarchar(25)                           
                              
  SET @tiSensorID = CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('=',@vcAlarmDesc)+1,                          
  CHARINDEX(';',@vcAlarmDesc,1)-CHARINDEX('=',@vcAlarmDesc)-1                          
  ) As tinyint)                          
                            
  IF @tiSensorID = 31                           
   BEGIN                          
    SET @vcAlarmDetail = 'Alarm - Tamper'                          
   END                          
  ELSE IF @tiSensorID = 27                          
   BEGIN                          
    SET @vcAlarmDetail = 'Alarm - Fuel drain'                          
                              
    SELECT @vcAlarmDetail = @vcAlarmDetail + ' ' +                           
     CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                          
     THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                          
     LEN(@vcAlarmDesc)), ';', '%') ELSE '' END                           
   END                          
  ELSE IF NOT  EXISTS (SELECT SensorName FROM rvlfBoxSensorsCfg WHERE SensorId = @tiSensorId and BoxID = @intBoxID)                          
   BEGIN                          
    SET @vcAlarmDetail = 'Unknown sensor'                          
   END                          
  ELSE                           
   BEGIN                          
    SELECT @vcAlarmDetail = ISNULL(Case when @Lang = 'LanguageArNew' Then SN.SensorName_Ar WHEN  @Lang='LanguageHindi' THEN SN.SensorName_Hin else  SC.SensorName  end , 'Unknown sensor') ,                           
    @vcActionOn = Case when @Lang = 'LanguageArNew' Then ISNULL(SN.ActionOn_Ar,'') WHEN  @Lang='LanguageHindi' THEN ISNULL(SN.ActionOn_Hin,'')  ELSE isnull(SC.ActionOn,'') END, @vcActionOff = Case when @Lang = 'LanguageArNew' Then ISNULL(SN.ActionOff_Ar,'










  
                 
') WHEN  @Lang='LanguageHindi' THEN ISNULL(SN.ActionOff_Hin,'') else isnull(SC.ActionOff,'') END                              
    FROM rvlfBoxSensorsCfg SC                            
    INNER JOIN rvlfsensor SN on SN.sensorID = SC.SensorID                            
    WHERE SC.SensorId = @tiSensorId and BoxID = @intBoxID                           
    SET @vcAlarmDetail = @vcAlarmDetail                           
    DECLARE @intSensorStateStart int                           
               
    SET @intSensorStateStart = CHARINDEX('SENSOR_STATUS=', @vcAlarmDesc) + 14                          
    SET @vcAlarmDetail = @vcAlarmDetail + ' '+                           
     CASE WHEN (SUBSTRING(@vcAlarmDesc, @intSensorStateStart, 2)) = 'ON' THEN          
      @vcActionOn                          
     ELSE                            
      @vcActionOff                           
     END                          
    IF RIGHT(@vcAlarmDetail,1) = ';'                          
    BEGIN                          
     SET @vcAlarmDetail = SUBSTRING(@vcAlarmDetail,1,LEN(@vcAlarmDetail)-1)                          
    END                                
                              
    SET @vcAlarmDetail = @vcAlarmDetail+CASE WHEN @tiBoxMsgInTypeID= 13 THEN ' - Bad Sensor' ELSE '' END                           
    If EXISTS(select BoxId from rvlfBoxId where BoxId IN (@intBoxID) AND @dtOriginDateTime >= '04/27/2012' AND (organizationid =139 OR organizationid = 23))                          
    BEGIN                          
    SET @SecondsToConvert =                           
    (CASE WHEN @vcAlarmDesc  like '%SENSOR_NUM=2;%' and @vcAlarmDesc LIKE '%SENSOR_DURATION=%' THEN                          
    CONVERT(VARCHAR,ISNULL((CASE WHEN @vcAlarmDesc LIKE '%SENSOR_DURATION=%' THEN CAST( SUBSTRING (@vcAlarmDesc,CHARINDEX('SENSOR_DURATION=',@vcAlarmDesc,1)+16,CHARINDEX(';',@vcAlarmDesc,                                        
    CHARINDEX('SENSOR_DURATION=',@vcAlarmDesc,1)) - (CHARINDEX('SENSOR_DURATION=',@vcAlarmDesc,1)+16)) as bigint) END ),0)) END)                          
    SET @vcAlarmDetail = @vcAlarmDetail + ' ' +                          
    CASE WHEN @SecondsToConvert = 0                          
    THEN '' ELSE  CASE WHEN @vcAlarmDesc LIKE '%SENSOR_NUM=2;%' and @vcAlarmDesc LIKE '%SENSOR_DURATION=%' THEN '(Durations: ' + dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert * 60) +')'  ELSE '' END END                          
    END 
	ELSE 
	BEGIN
		 SET @SecondsToConvert =  (CASE WHEN @tiBoxMsgInTypeID = 3 and @vcAlarmDesc LIKE '%SENSOR_DURATION=%' THEN                          
		 CONVERT(VARCHAR,ISNULL((CASE WHEN @vcAlarmDesc LIKE '%SENSOR_DURATION=%' THEN CAST( SUBSTRING (@vcAlarmDesc,CHARINDEX('SENSOR_DURATION=',@vcAlarmDesc,1)+16,CHARINDEX(';',@vcAlarmDesc,                                        
		 CHARINDEX('SENSOR_DURATION=',@vcAlarmDesc,1)) - (CHARINDEX('SENSOR_DURATION=',@vcAlarmDesc,1)+16)) as bigint) END ),0)) END)                          
		 SET @vcAlarmDetail = @vcAlarmDetail + ' ' + CASE WHEN ISNULL(@SecondsToConvert,0) = 0                          
		 THEN '' ELSE '(Durations: ' + dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert * 60) +')' END
	END                         
  END                          
 END                          
 ELSE IF @tiBoxMsgInTypeID = 9                           
 BEGIN                          
  SET @SecondsToConvert = CAST(SUBSTRING (@vcAlarmDesc, CHARINDEX(':',@vcAlarmDesc,1)+1,                          
  CHARINDEX(';',@vcAlarmDesc)-1 -CHARINDEX(':',@vcAlarmDesc,1)) AS bigint)                          
  SET @vcAlarmDetail = @vcMoxMsgInTypeName + ' '+ CASE WHEN @SecondsToConvert = 0                          
  THEN Case when @Lang = 'LanguageArNew' Then N'(/#' WHEN @Lang='LanguageHindi' THEN N'6	A	0	B	' else 'started' END ELSE Case                   
  when @Lang = 'LanguageArNew' Then N'%F*GI ' WHEN @Lang='LanguageHindi' THEN N'		$	' else 'end ' end + dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert) END                           
 END                          
 
 ELSE IF @tiBoxMsgInTypeID = 14 OR @tiBoxMsgInTypeID = 15 OR @tiBoxMsgInTypeID = 51 OR                      
  @tiBoxMsgInTypeID = 16 OR @tiBoxMsgInTypeID = 17 OR @tiBoxMsgInTypeID = 24                          
 BEGIN                          
	SET @SecondsToConvert = CAST(SUBSTRING (@vcAlarmDesc, CHARINDEX(':',@vcAlarmDesc,1)+1,CHARINDEX(';',@vcAlarmDesc)-1 -CHARINDEX(':',@vcAlarmDesc,1)) AS bigint)                          
	SET @vcAlarmDetail = @vcMoxMsgInTypeName + ' ' + dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert) 
 END
 
 ELSE IF @tiBoxMsgInTypeID = 96 
 BEGIN
	SET @vcAlarmDetail = @vcMoxMsgInTypeName 
	SET @vcAlarmDetail = @vcAlarmDetail + ' (Speed: ' + CASE	WHEN CHARINDEX('SensorInfo1=',@vcAlarmDesc, 1) <> 0  
																THEN CONVERT(varchar,CAST(ROUND((CAST(dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'SensorInfo1=',';') AS NUMERIC(18,2)) * 1.609344),0) AS INT)) 
														END + ' kmph,' 
	SET @vcAlarmDetail = @vcAlarmDetail + ' Maximum Degrees Turned: ' + CASE WHEN CHARINDEX('SensorInfo2=',@vcAlarmDesc, 1) <> 0                          
																			 THEN dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'SensorInfo2=',';') END + '°)' 
 END
                           
 ELSE IF @tiBoxMsgInTypeID = 5 OR @tiBoxMsgInTypeID = 6                          
 BEGIN                          
  IF @uiMessageInId IS NOT NULL                          
   BEGIN  
    SELECT @vcAlarmDetail = g.GeozoneName FROM rvlfOrganizationGeozone g INNER JOIN rvlfVehicle v                           
     ON g.OrganizationId=v.OrganizationId INNER JOIN rvlfVehicleAssignment va ON                     
     v.VehicleId = va.VehicleId                           
     --INNER JOIN rvlfVehicleGeozone vg ON vg.VehicleID = v.VehicleID AND vg.GeozoneNo = g.GeozoneId                          
     WHERE BoxId = @intBoxID and g.GeozoneId = --CAST(@vcAlarmDesc as bigint)                          
     (CAST( SUBSTRING(@vcAlarmDesc,                          
      CHARINDEX('=',@vcAlarmDesc,1)+1,(CHARINDEX(';',@vcAlarmDesc,1)                          
      - CHARINDEX('=',@vcAlarmDesc,1))-1) as bigint))                          
    SET @vcAlarmDetail = ISNULL(@vcAlarmDetail,'Geozone Deleted') + ' '+                           
CASE WHEN @tiBoxMsgInTypeID = 5 THEN ' - In' ELSE ' - Out' END                          
   END                          
  ELSE                          
   BEGIN                          
    SELECT @vcAlarmDetail = g.GeozoneName FROM rvlfOrganizationGeozone g INNER JOIN rvlfVehicle v                           
    ON g.OrganizationId=v.OrganizationId INNER JOIN rvlfVehicleAssignment va ON                           
      v.VehicleID = va.VehicleID                          
      --INNER JOIN rvlfVehicleGeozone vg ON vg.VehicleID = v.VehicleID AND vg.GeozoneNo = g.GeozoneId                          
     WHERE BoxId = @intBoxID and g.GeozoneId = --CAST(@vcAlarmDesc as bigint)                         
     (CAST( SUBSTRING(@vcAlarmDesc,                          
      CHARINDEX('=',@vcAlarmDesc,1)+1,(CHARINDEX(';',@vcAlarmDesc,1)                   
      - CHARINDEX('=',@vcAlarmDesc,1))-1) as bigint))                        
     --(CAST( @vcAlarmDesc as bigint))                           
    SET @vcAlarmDetail = ISNULL(@vcAlarmDetail,'Geozone Deleted') + ' '+                           
     CASE WHEN @tiBoxMsgInTypeID = 5 THEN ' - In' ELSE ' - Out' END                          
   END                          
 END                          
 ELSE IF @tiBoxMsgInTypeID = 28                          
 BEGIN                          
  DECLARE @bigOrganizationID bigint                          
  SELECT @bigOrganizationID = v.OrganizationId  FROM rvlfVehicle v                          
   INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId and va.BoxId = @intBoxID                          
  SET @vcAlarmDetail = (SELECT g.GeozoneName from rvlfOrganizationGeozone g WHERE g.GeozoneId IN                           
   (select * from dbo.rvlf_fn_ConvertArrayToTable(@vcAlarmDesc,','))                         
   AND g.OrganizationID = @bigOrganizationID FOR XML AUTO)                          
  IF @vcAlarmDetail IS NULL                          
   BEGIN                          
    SET @vcAlarmDetail = ''                          
   END                          
  ELSE                          
   BEGIN                          
    SET @vcAlarmDetail = '<GeozoneList>'+@vcAlarmdetail+'</GeozoneList>'                          
   END                          
 END         
 
       
 ELSE IF @tiBoxMsgInTypeID=114 AND @vcAlarmDesc like '153;%'--@tiBoxMsgInTypeID = 153 --GetAdvancedGeozoneIDs                                                  
 begin                                                   
 declare @tbl table (f1 varchar(max),f2 int identity(1,1))                                                  
 declare @tbl1 table (Geozone varchar(max),Timelimit varchar(max),Restricted varchar(max))                            
 declare @Geoid varchar (max)                                                  
 declare @timelimit varchar (max)                                                  
 declare @Restricted varchar (max)                                                  
 --DECLARE @bigOrganizationID bigint                      
    SELECT @bigOrganizationID = v.OrganizationId  FROM rvlfVehicle v                                                        
    INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId and va.BoxId = @intBoxID                                                 
 insert into @tbl                                                  
 select * from dbo.rvlf_fn_ConvertArrayToTable(@vcAlarmDesc,';')                                                  
 insert into @tbl1                                                  
 select * from @tbl a                                                  
 PIVOT                                                  
 (                                                  
     max([f1])                                                  
 FOR [f2] IN ([1], [2], [3])                                                  
 )AS [pivot]                                                  
 select @Geoid=Geozone,@timelimit=Timelimit,@Restricted=Restricted from @tbl1                                                    
 --select * from @tbl1                                                   
 delete from @tbl1                             
 insert into @tbl1                                                  
 SELECT g.GeozoneName,a.Timelimit,a.Rest from rvlfOrganizationGeozone g                                                    
 inner join (select g.FieldValue as geoid,t.FieldValue as Timelimit,r.FieldValue as Rest from                                                   
 (select * from dbo.rvlf_fn_ConvertArrayToTableWithIdentity(@Geoid,'|')) g inner join                                                   
 (select * from dbo.rvlf_fn_ConvertArrayToTableWithIdentity(@timelimit,'|')) t on t.[identity]= g.[identity]                                                  
 inner join (select * from dbo.rvlf_fn_ConvertArrayToTableWithIdentity(@Restricted,'|')) R on g.[identity]=r.[identity]) as a                                            
 on g.GeozoneId=a.geoid                          
 where g.OrganizationID = @bigOrganizationID --FOR XML AUTO                                                  
 set @vcAlarmDetail=(select Geozone,dbo.rvlf_fn_GetTimeFromSeconds((cast(Timelimit as bigint) * 60)) as Timelimit,Restricted from @tbl1 FOR XML AUTO)                                          
 IF @vcAlarmDetail IS NULL                                                        
 BEGIN                                       
     SET @vcAlarmDetail = 'Send Advanced GeozoneIDs'                                                        
    END                                                        
  ELSE                                                  
    BEGIN                                                        
  SET @vcAlarmDetail = '<GeozoneList>'+@vcAlarmdetail+'</GeozoneList>'                                                        
    END                                                    
 END        
                  
 ELSE IF @tiBoxMsgInTypeID = 19                          
  BEGIN                          
   DECLARE @intIPReason int                           
   SET @intIPReason  = CAST(SUBSTRING(@vcAlarmDesc, CHARINDEX('=',@vcAlarmDesc,1)+1,CHARINDEX(';',@vcAlarmDesc,1)-(CHARINDEX('=',@vcAlarmDesc,1)+1) ) as int)                           
   SET @vcAlarmDetail = 'IP Update - '+                          
    CASE WHEN @intIPReason = 1 THEN 'Power Up' WHEN @intIPReason = 2 THEN 'Failed'                          
      WHEN @intIPReason = 3 THEN 'Sleep' WHEN @intIPReason = 4 THEN 'Attach ERROR'                          
      WHEN @intIPReason = 5 THEN 'PPP TERMINATE' WHEN @intIPReason = 6 THEN 'Long PPP Negotiation'                           
      WHEN @intIPReason = 7 THEN 'PPP Negotiated To' WHEN @intIPReason = 8 THEN 'No Diag'                           
      WHEN @intIPReason = 9 THEN 'Force Reset' WHEN @intIPReason = 10 THEN 'Std Msg Failed'                           
      WHEN @intIPReason = 11 THEN 'Mdm Reset Fail' WHEN @intIPReason = 12 THEN 'Wake Up'                           
      WHEN @intIPReason = 13 THEN 'Register To' WHEN @intIPReason = 14 THEN 'Attach To'                           
      WHEN @intIPReason = 15 THEN 'AT failed' WHEN @intIPReason = 16 THEN 'Dial To'                           
      WHEN @intIPReason = 17 THEN 'Dial failed' WHEN @intIPReason = 18 THEN 'Errors > 10'                           
      WHEN @intIPReason = 19 THEN 'Can''t attached'                          
      ELSE 'Unknown' END    END                          
 ELSE IF @tiBoxMsgInTypeID = 42                          
   BEGIN                          
    SELECT @vcAlarmDetail = Case when @Lang = 'LanguageArNew' Then isnull(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi' THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc) else BoxMsgInTypeDesc END 
	FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                         
                              
    SET @FuelLevelPercentage = CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                          
										 THEN dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'Fuel%=',';') END as int)
										 --REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int)

    SET @FuelLevelPercentage = CASE WHEN @FuelLevelPercentage <=0 THEN 0 ELSE @FuelLevelPercentage END                          
   
    SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = CASE CapacityUnits WHEN 1 THEN 'litres' WHEN 2 THEN 'gals' ELSE 'litres' END
	FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID                      
   
    SELECT @vcAlarmDetail = @vcAlarmDetail + ' (Actual Fuel Drained - ' +	--+ ' ('+ cast(@FuelLevelPercentage as varchar(3))+ '% - '+               
							cast(cast(((@FuelLevelPercentage / 100.00) * @tankCapacity)as int) as varchar(5)) +' '+ @vcFuelUnits +')'                          

     --CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                          
     -- THEN ' (' +  REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                          
     -- LEN(@vcAlarmDesc)), ';', '%)') ELSE '' END                          
   END                        
 ELSE IF @tiBoxMsgInTypeID = 41                          
   BEGIN                          
    SELECT @vcAlarmDetail = Case when @Lang = 'LanguageArNew' Then isnull(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi' THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc) else BoxMsgInTypeDesc END FROM rvlfBoxMsgInType                
  
	WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                        
   -- SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                          
                              
    --SELECT @vcAlarmDetail = @vcAlarmDetail + ' ' +                           
    -- CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                          
    -- THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                          
    -- LEN(@vcAlarmDesc)), ';', '%') ELSE '' END                           
   END                         
 ELSE IF @tiBoxMsgInTypeID = 73                          
   BEGIN                          
   SELECT @vcAlarmDetail = Case when @Lang = 'LanguageArNew' Then isnull(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi' THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc) else BoxMsgInTypeDesc END FROM rvlfBoxMsgInType                 











 


 
   WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                        
   -- SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                          
                              
    DECLARE @vcCustomProperty VARCHAR(1000) = @vcAlarmDesc                          
    SET @vcCustomProperty = REPLACE(@vcCustomProperty, '$$', ':')                          
                          
    DECLARE @vcGenParams varchar(max)                          
    DECLARE @RI AS VARCHAR(8)                          
    DECLARE @ReportingInterval AS VARCHAR(35)                          
    SET @RI = SUBSTRING (@vcCustomProperty, CHARINDEX('=',@vcCustomProperty,1)+1,                          
        CHARINDEX(';',@vcCustomProperty)-1 -CHARINDEX('=',@vcCustomProperty,1))                          
                                           
                SET @ReportingInterval = CASE WHEN @RI = '00:00:30' THEN 'Reporting Interval=30sec'                          
     WHEN @RI = '00:01:00' THEN 'Reporting Interval=1min'                          
     WHEN @RI = '00:02:00' THEN 'Reporting Interval=2min'                          
     WHEN @RI = '00:05:00' THEN 'Reporting Interval=5min'                          
     WHEN @RI = '00:10:00' THEN 'Reporting Interval=10min'                          
     WHEN @RI = '00:15:00' THEN 'Reporting Interval=15min'                          
     WHEN @RI = '00:30:00' THEN 'Reporting Interval=30min'                          
     WHEN @RI = '01:00:00' THEN 'Reporting Interval=1hr'                           
     WHEN @RI = '02:00:00' THEN 'Reporting Interval=2hrs' ELSE '' END                           
                          
    SELECT @vcGenParams = ISNULL(@vcGenParams + ';', '') +                           
      CASE WHEN CHARINDEX('Gen Param No',FieldValue) <> 0 THEN                  
      REPLACE(REPLACE(REPLACE(FieldValue, 'Gen Param No='+SUBSTRING(FieldValue, CHARINDEX('Gen Param No',FieldValue)+ 13,                           
      (CHARINDEX('Gen Param Val',FieldValue) - (CHARINDEX('Gen Param No',FieldValue) + 13)))+'',                           
      dbo.rvlf_fn_GetGeneratorParameterName(SUBSTRING(FieldValue, CHARINDEX('Gen Param No',FieldValue)+ 13,                           
      (CHARINDEX('Gen Param Val',FieldValue) - (CHARINDEX('Gen Param No',FieldValue) + 13) - 1)))), 'Gen Param Val',''),                          
      'Reporting Interval='+@RI+';','') ELSE '' END                          
    FROM [dbo].[rvlf_fn_ConvertArrayToTable] (@vcCustomProperty, '|')                          
                          
    SET @vcAlarmDetail = @ReportingInterval + ';' + @vcGenParams                           
   END                          
 ELSE IF @tiBoxMsgInTypeID = 74                          
  BEGIN                          
   --SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                          
                             
   --SET @vcAlarmDetail = @vcAlarmDetail --+ '-'        
--SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, ' degree Celsius' ,'°C')                           
   --SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, ' mV' ,'lit.')                           
                             
   SET @vcAlarmDetail = @vcAlarmDesc                          
                             
   SET @vcAlarmDetail = REPLACE(REPLACE(REPLACE(@vcAlarmDetail, 'ExSensorNo=0', 'Sensor=Temperature Sensor-1'), 'ExSensorNo=1', 'Sensor=Fuel Guage Sensor'), 'ExSensorNo=2', 'Sensor=Temperature Sensor-2')                          
   SET @vcAlarmDetail = REPLACE(REPLACE(@vcAlarmDetail, ' degree Celsius' ,'°C'), '|', ';')                          
  END                          
 ELSE IF @tiBoxMsgInTypeID = 75 -- Send Driver ID and Status                          
  BEGIN                      
                             
   DECLARE @DriveDuration AS VARCHAR(10)                          
   DECLARE @DRIVERNO INT=NULL                          
   DECLARE @KEYID VARCHAR(30)=NULL                          
   DECLARE @VCDRIVERNAMECMD VARCHAR(30)=NULL                          
   DECLARE @VCKEY VARCHAR(20)=NULL                          
                             
   SELECT @VCDRIVERNAMECMD=DisplayName,@VCKEY=IButtonKeyName,@KEYID=IButtonKey FROM rvlfIButtonMapping M                          
    LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId=M.DriverId                            
   WHERE M.IButtonKey =CAST(SUBSTRING (@vcAlarmDesc,CHARINDEX('Driver ID=',@vcAlarmDesc,1)+10,CHARINDEX(';',@vcAlarmDesc,                          
          CHARINDEX('Driver ID=',@vcAlarmDesc,1)) - (CHARINDEX('Driver ID=',@vcAlarmDesc,1)+10)) as varchar)                       
   SET @DRIVERNO=CAST(SUBSTRING (@vcAlarmDesc,CHARINDEX('Driver Number=',@vcAlarmDesc,1)+14,CHARINDEX(';',@vcAlarmDesc,                          
          CHARINDEX('Driver Number=',@vcAlarmDesc,1)) - (CHARINDEX('Driver Number=',@vcAlarmDesc,1)+14)) as int)                          
                             
   SET @SecondsToConvert = CAST(SUBSTRING (@vcAlarmDesc, CHARINDEX('Drive Duration=',@vcAlarmDesc,1) + 15,                          
   CHARINDEX(';Drive Distance',@vcAlarmDesc) - 15 - CHARINDEX('Drive Duration=',@vcAlarmDesc,1)) AS BIGINT)                          
                           
   SET @DriveDuration = REPLACE((CASE WHEN LEN(RTRIM(CONVERT(char(8),@SecondsToConvert/3600))) = 1 THEN '0' + RTRIM(CONVERT(char(8),@SecondsToConvert/3600)) ELSE RTRIM(CONVERT(char(8),@SecondsToConvert/3600)) END                           
     + ':' + CASE WHEN LEN(CONVERT(char(2), (@SecondsToConvert % 3600) / 60)) = 1 THEN '0' + CONVERT(char(2), (@SecondsToConvert % 3600) / 60) ELSE CONVERT(char(2), (@SecondsToConvert % 3600) / 60) END                           
     + ':' + CASE WHEN LEN(CONVERT(char(2), @SecondsToConvert % 60)) = 1 THEN '0' + CONVERT(char(2), @SecondsToConvert % 60) ELSE CONVERT(char(2), @SecondsToConvert % 60) END), ' ', '')                          
                             
   SET @vcAlarmDetail = REPLACE(@vcAlarmDesc, 'Drive Duration=' + CAST(@SecondsToConvert AS Varchar), 'Drive Duration=' + @DriveDuration)                          
   IF(@VCDRIVERNAMECMD IS NOT NULL)                          
    BEGIN                          
     SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, 'Driver Number=' + CAST(@DRIVERNO AS Varchar), 'Driver Name=' + @VCDRIVERNAMECMD)                          
    END                          
   ELSE                          
    BEGIN                          
     SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, 'Driver Number=' + CAST(@DRIVERNO AS Varchar), 'Driver Name=UnKnown')                          
    END                          
   IF(@KEYID IS NOT NULL)                          
    BEGIN     
     SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, 'Current Driver ID=' + CAST(@KEYID AS Varchar), 'Driver Key=' + @VCKEY)    
END          
  ELSE                     
    BEGIN                          
     SET @KEYID=CAST(SUBSTRING (@vcAlarmDesc,CHARINDEX('Current Driver ID=',@vcAlarmDesc,1)+18,CHARINDEX(';',@vcAlarmDesc,                          
          CHARINDEX('Current Driver ID=',@vcAlarmDesc,1)) - (CHARINDEX('Current Driver ID=',@vcAlarmDesc,1)+18)) as VARCHAR)                                   
     SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, 'Current Driver ID=' + CAST(@KEYID AS Varchar), 'Driver Key=UnKnown')              
    END                                  
  END                          
 ELSE IF @tiBoxMsgInTypeID = 76 -- Driver Identification                          
  BEGIN                          
   DECLARE @VCDRIVERNAME VARCHAR(30)=NULL              
   IF(@vcAlarmDesc LIKE '%Driver Status=%')                          
    BEGIN                          
     IF(CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('MAPID=',@vcAlarmDesc,1)+6,LEN(@vcAlarmDesc))AS BIGINT)>0)                          
      BEGIN                          
       SELECT @VCDRIVERNAME= DisplayName FROM rvlfDriverMaster WHERE DriverId=CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('MAPID=',@vcAlarmDesc,1)+6,LEN(@vcAlarmDesc))AS BIGINT)                          
      END                      
     ELSE IF(CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('MAPID=',@vcAlarmDesc,1)+6,LEN(@vcAlarmDesc))AS BIGINT) = 0 AND                       
  LEN(CAST(SUBSTRING (@vcAlarmDesc,CHARINDEX('Driver ID=',@vcAlarmDesc,1)+10,CHARINDEX(';',@vcAlarmDesc,                          
  CHARINDEX('Driver ID=',@vcAlarmDesc,1)) - (CHARINDEX('Driver ID=',@vcAlarmDesc,1)+10)) as varchar)) > 0)                      
     BEGIN                      
   SELECT @VCDRIVERNAME = DM.DisplayName FROM rvlfDriverMaster DM INNER JOIN rvlfIButtonMapping BM ON BM.DriverID=DM.DriverId                      
   WHERE Bm.IButtonKey=CAST(SUBSTRING (@vcAlarmDesc,CHARINDEX('Driver ID=',@vcAlarmDesc,1)+10,CHARINDEX(';',@vcAlarmDesc,                          
   CHARINDEX('Driver ID=',@vcAlarmDesc,1)) - (CHARINDEX('Driver ID=',@vcAlarmDesc,1)+10)) as varchar)                      
  END                      
     ELSE                          
      BEGIN                          
       SELECT @VCDRIVERNAME='Unknown'                          
      END                          
                                   
     SET @vcAlarmDetail='Driver - '+ISNULL(@VCDRIVERNAME,'Unknown')+' - '+CAST(SUBSTRING (@vcAlarmDesc,CHARINDEX('Driver Status=',@vcAlarmDesc,1)+14,CHARINDEX(';',@vcAlarmDesc,                          
          CHARINDEX('Driver Status=',@vcAlarmDesc,1)) - (CHARINDEX('Driver Status=',@vcAlarmDesc,1)+14)) as varchar)                END                          
   IF(@vcAlarmDesc LIKE '%Driver Alarm=%')                          
    BEGIN                          
     IF(CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('MAPID=',@vcAlarmDesc,1)+6,LEN(@vcAlarmDesc))AS BIGINT)>0)             
      BEGIN                          
       SELECT @VCDRIVERNAME= DisplayName FROM rvlfDriverMaster WHERE DriverId=CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('MAPID=',@vcAlarmDesc,1)+6,LEN(@vcAlarmDesc))AS BIGINT)                          
      END                          
     ELSE                          
      BEGIN                          
       SELECT @VCDRIVERNAME='Unknown'                          
      END                          
                                   
     SET @vcAlarmDetail=CAST(SUBSTRING (@vcAlarmDesc,CHARINDEX('Driver Alarm=',@vcAlarmDesc,1)+13,CHARINDEX(';',@vcAlarmDesc,                          
          CHARINDEX('Driver Alarm=',@vcAlarmDesc,1)) - (CHARINDEX('Driver Alarm=',@vcAlarmDesc,1)+13)) as varchar)+' by '+@VCDRIVERNAME                              
    END                          
  END                          
 ELSE IF @tiBoxMsgInTypeID = 100 -- RFID Identification                          
  BEGIN                          
   DECLARE @VCKEYUSERNAME VARCHAR(max)=NULL                 
    DECLARE @RFID Varchar(50)=null                
   declare @Punch varchar(100)=null                       
     IF(@vcAlarmDesc LIKE '%RF_ID=%')     --6                                                   
    BEGIN                    
    set @RFID=dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'RF_ID=',';')                 
    IF(charindex('InOutEnable',@vcAlarmDesc,1)>0) --5                
    BEGIN                
     declare @InOutEnable varchar(2) =dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'InOutEnable:',';')                 
     SELECT @VCKEYUSERNAME=ISNULL(DM.DriverName,IButtonKeyName) FROM rvlfIButtonMapping BP         
     LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId=BP.DriverId WHERE BP.IButtonKey=@RFID      
	 SELECT @VCKEYUSERNAME= StudentID FROM rvlfStudentMaster WHERE RFID=@RFID       
	           
    IF @VCKEYUSERNAME IS NULL OR @VCKEYUSERNAME=''                                        
     BEGIN  --2                                                            
       SET @vcAlarmDetail= 'RF_ID='+(select dbo.rvlf_fn_GetParamValueWithIndex (@vcAlarmDesc,'RF_ID=',';')) -- removed odometer display
	  set @vcAlarmDetail =left(@vcAlarmDetail,len(@vcAlarmDetail))                
      set @Punch = (select dbo.rvlf_fn_GetParamValueWithIndex (@vcAlarmDesc,'Punch:',';'))                      
      set @vcAlarmDetail=@vcAlarmDetail + isnull(case when @Punch='UnauthorizedIN' or  @Punch='UnauthorizedOUT' then ' - Unauthorized' end,'')                      
      IF(@InOutEnable ='1' and @InOutEnable is not null) --1                               
      begin         -- SUBSTRING(@vcAlarmDesc,CHARINDEX('RF_ID=',@vcAlarmDesc,1),LEN(@vcAlarmDesc))                      
  SET @vcAlarmDetail = 'RF_ID='+@RFID                
  --REPLACE(SUBSTRING(@vcAlarmDesc,CHARINDEX('RF_ID=',@vcAlarmDesc,0),(CHARINDEX(';',@vcAlarmDesc,CHARINDEX('RF_ID=',@vcAlarmDesc,0))-(CHARINDEX('RF_ID=',@vcAlarmDesc,0)))), ';', '')                
  + ' - ' + SUBSTRING(@vcAlarmDesc,CHARINDEX('Punch:',                    
  @vcAlarmDesc,1)+6, CHARINDEX(';',@vcAlarmDesc, CHARINDEX('Punch:',@vcAlarmDesc,1)) - (CHARINDEX('Punch:',@vcAlarmDesc,1)+6))                                       
   end    --1                         
    END  --2                                                        
    ELSE --3                 
     BEGIN                                                              
      SET @vcAlarmDetail='User - '+ @VCKEYUSERNAME +' [RFID]'                                                        
      IF(@InOutEnable='1' and @InOutEnable is not null)                                
      BEGIN --4                    
  SET @vcAlarmDetail = 'User - '+ @VCKEYUSERNAME +' [RFID]'+ ' - ' + SUBSTRING(@vcAlarmDesc,CHARINDEX('Punch:',@vcAlarmDesc,1)+6,                                               
  CHARINDEX(';',@vcAlarmDesc, CHARINDEX('Punch:',@vcAlarmDesc,1)) - (CHARINDEX('Punch:',@vcAlarmDesc,1)+6))                                       
   end  --4                             
    END--3                
END  --5                 
ELSE                
begin    --Student punch            
 SELECT @VCKEYUSERNAME= StudentID FROM rvlfStudentMaster WHERE RFID=@RFID                 
 select @Punch =' - '+ (select case when SUBSTRING(@vcAlarmDesc,1,10)='Punch:101;' then 'Boarded / Get down at incorrect Location'             
 when SUBSTRING(@vcAlarmDesc,1,10)='Punch:110;' then 'Boarded in incorrect vehicle'                               
 when SUBSTRING(@vcAlarmDesc,1,10)='Punch:111;' then null end)            
                 
 SET @vcAlarmDetail = (case when @VCKEYUSERNAME is null then @RFID else @VCKEYUSERNAME end) + ' [RFID]' + isnull(@Punch,'')                 
                
end                 
END--6                
                    
                         
  END                  
                           
 ELSE IF @tiBoxMsgInTypeID = 121                          
 BEGIN                          
  Declare @errCode int = CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('Error Code=',@vcAlarmDesc,0)+11,(CHARINDEX(';',@vcAlarmDesc,CHARINDEX('Error Code=',@vcAlarmDesc,0))-(CHARINDEX('Error Code=',@vcAlarmDesc,0)+11))) AS int)                          
  SET @vcAlarmDetail = CASE WHEN @errCode = 1 THEN 'Get Device ID From LPC'                          
       WHEN @errCode = 2 THEN 'Get Destination IP From LPC'                          
       WHEN @errCode = 3 THEN 'Get Destination Port From LPC'                          
       WHEN @errCode = 4 THEN 'Get  Reporting interval From LPC'                          
       WHEN @errCode = 5 THEN 'Get Speed threshold From LPC'                          
       WHEN @errCode = 6 THEN 'Get  leash From LPC'                          
       WHEN @errCode = 7 THEN 'Get APN From LPC'                          
       WHEN @errCode = 8 THEN 'Device Reset'                          
       WHEN @errCode = 9 THEN 'Device will Reset due to IP Update fail'   	                          	
	 WHEN @errCode = 10 THEN 'Device will Reset due to no response from last one day'                      
       WHEN @errCode = 11 THEN 'Device Reset (WDT)'                      
       WHEN @errCode = 12 THEN 'Device Reset (BOD)'   
       WHEN @errCode = 13 THEN 'Device Reset (MODEM)'   
       ELSE 'Device Messages'                          
     END                          
 END                           
 ELSE IF @tiBoxMsgInTypeID = 77 -- Send MDT Message to Server                          
  BEGIN                          
                            
   --DECLARE @MDTUserId AS Varchar(50) = ''                          
   DECLARE @Cancode AS INT                          
   DECLARE @MsgKind AS char(1) = SUBSTRING(@vcAlarmDesc, CHARINDEX('Msg Kind',@vcAlarmDesc) + 9,                           
      (CHARINDEX('Cancode',@vcAlarmDesc) - CHARINDEX('Msg Kind',@vcAlarmDesc) - 10))    
                           
   IF @MsgKind = '0'                          
   BEGIN                          
 
    SET @vcAlarmDetail = SUBSTRING(@vcAlarmDesc, CHARINDEX('Message=',@vcAlarmDesc) + 0,               
         (CHARINDEX('Group ID',@vcAlarmDesc) - CHARINDEX('Message=',@vcAlarmDesc) - 0))                          
    SET @vcAlarmDetail = REPLACE(REPLACE(@vcAlarmDetail, ';', ''), 'Message=', 'Msg=')                          
                              
    --SET @MDTUserId = SUBSTRING(@vcAlarmDesc, CHARINDEX('User ID=',@vcAlarmDesc) + 8,                           
    --     (CHARINDEX('Message',@vcAlarmDesc) - CHARINDEX('User ID=',@vcAlarmDesc) - 9))                          
                          
   END                           
   ELSE IF @MsgKind = '2'                          
   BEGIN                          
    DECLARE @orgId int,@typeid int,@Msg varchar(100),@MsgAns varchar(100),@Q1 varchar(30),@Q2 varchar(30),@Q3 varchar(30),                          
       @A1 varchar(30),@A2 varchar(30),@A3 varchar(30)                          
       SELECT @orgId = OrganizationId FROM rvlfBoxId WHERE BoxId=@intBoxID                          
    SET @Cancode = CONVERT(INT, SUBSTRING(@vcAlarmDesc, CHARINDEX('Cancode=',@vcAlarmDesc) + 8,                           
        (CHARINDEX('User ID',@vcAlarmDesc) - CHARINDEX('Cancode=',@vcAlarmDesc) - 9)))                          
    SELECT @typeid=TypeId,@Msg=(CASE WHEN TypeId = 1 THEN REPLACE(REPLACE(REPLACE(MsgName,'$',''),'@',''),'-','')                          
    ELSE REPLACE(REPLACE(REPLACE(MsgName,'$',' '),'@',' '),'-',' ') END) FROM rvlfMDTFormMessages            
    WHERE OrganizationId=@orgId AND FormMsgId=@Cancode                          
                              
    SET @vcAlarmDetail = REPLACE(SUBSTRING(@vcAlarmDesc, CHARINDEX('Message=',@vcAlarmDesc) + 0,                           
    (CHARINDEX('Group ID',@vcAlarmDesc) - CHARINDEX('Message=',@vcAlarmDesc) - 0)),'Message=','')                          
                              
    SELECT @MsgAns= REPLACE((CASE WHEN @typeid = 2 THEN REPLACE(@vcAlarmDetail,'\~',', ') ELSE REPLACE(@vcAlarmDetail,'\~','') END),';','')                          
                              
    IF @typeid = 2                          
    BEGIN                          
     SET @Q1 = LTRIM(RTRIM(SUBSTRING(@Msg,0,30)))                          
     SET @Q2 = LTRIM(RTRIM(SUBSTRING(@Msg,31,30)))                          
     SET @Q3 = LTRIM(RTRIM(SUBSTRING(@Msg,61,30)))                          
     SET @A1 = (SELECT ISNULL(FieldValue,'') FROM dbo.rvlf_StringSplitter(@MsgAns,',') WHERE Sno=1)                          
     SET @A2 = (SELECT ISNULL(FieldValue,'') FROM dbo.rvlf_StringSplitter(@MsgAns,',') WHERE Sno=2)                          
     SET @A3 = (SELECT ISNULL(FieldValue,'') FROM dbo.rvlf_StringSplitter(@MsgAns,',') WHERE Sno=3)                          
    END                          
                              
                              
    SELECT @vcAlarmDetail=(SELECT ISNULL(MDTUserName,'-') FROM rvlfMDTUserTable                           
    WHERE MDTUserId=(SUBSTRING(@vcAlarmDesc, CHARINDEX('User ID=',@vcAlarmDesc) + 8,                          
    (CHARINDEX('Message',@vcAlarmDesc) - CHARINDEX('User ID=',@vcAlarmDesc) - 9))))+' > '+                          
    (CASE WHEN @typeid = 1 THEN @Msg +' : ' + @MsgAns                           
    ELSE              
    (CASE WHEN LEN(@Q1) > 0 THEN @Q1 +' : ' + @A1  ELSE '' END)+                           
    (CASE WHEN LEN(@Q2) > 0 THEN ' | ' + @Q2 +' : ' + @A2  ELSE '' END)+                          
    (CASE WHEN LEN(@Q3) > 0 THEN ' | ' + @Q3 +' : ' + @A3  ELSE '' END)                          
    END) FROM rvlfMDTFormMessages WHERE OrganizationId=@orgId AND FormMsgId=@Cancode                          
                          
    --SET @Cancode = CONVERT(INT, SUBSTRING(@vcAlarmDesc, CHARINDEX('Cancode=',@vcAlarmDesc) + 8,                           
    --     (CHARINDEX('User ID',@vcAlarmDesc) - CHARINDEX('Cancode=',@vcAlarmDesc) - 9)))                          
    --SET @vcAlarmDetail = REPLACE(SUBSTRING(@vcAlarmDesc, CHARINDEX('Message=',@vcAlarmDesc) + 0,                           
    --     (CHARINDEX('Group ID',@vcAlarmDesc) - CHARINDEX('Message=',@vcAlarmDesc) - 0)),'Message=','')                          
    --SELECT @vcAlarmDetail=REPLACE(REPLACE(REPLACE(MsgName,'$',''),'@',''),'-','')+' : '+REPLACE(@vcAlarmDetail,'\~','')+' <br /> User : '+                          
    --(SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId=(SUBSTRING(@vcAlarmDesc, CHARINDEX('User ID=',@vcAlarmDesc) + 8,                          
    --(CHARINDEX('Message',@vcAlarmDesc) - CHARINDEX('User ID=',@vcAlarmDesc) - 9))))                          
    --FROM rvlfMDTFormMessages WHERE OrganizationId IN                          
    --(SELECT OrganizationId FROM rvlfBoxId WHERE BoxId=@intBoxID) AND FormMsgId=@Cancode                          
   END                                
   ELSE                           
   BEGIN                          
                          
    SET @Cancode = CONVERT(INT, SUBSTRING(@vcAlarmDesc, CHARINDEX('Cancode=',@vcAlarmDesc) + 8,                           
         (CHARINDEX('User ID',@vcAlarmDesc) - CHARINDEX('Cancode=',@vcAlarmDesc) - 9)))                          
                                   
    SELECT @vcAlarmDetail = MsgName FROM rvlfPrecannedMessages WHERE PrecannedMsgId = @Cancode AND IsServerMsg = 0                  
    SET @vcAlarmDetail = 'Msg=' + @vcAlarmDetail                           
                              
    --SET @MDTUserId = SUBSTRING(@vcAlarmDesc, CHARINDEX('User ID=',@vcAlarmDesc) + 8,                           
    --     (CHARINDEX('Group ID',@vcAlarmDesc) - CHARINDEX('User ID=',@vcAlarmDesc) - 9))                          
                          
   END                          
                                   
   --IF EXISTS (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUserId AND BoxId = @intBoxID)                          
   --BEGIN                          
                            
   -- SET @MDTUserId = (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUserId AND BoxId = @intBoxID)                          
                            
      --END                          
                             
   --SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, 'Driver Msg', 'Msg from ' + @MDTUserId)                          
                             
  END                          
 ELSE IF @tiBoxMsgInTypeID = 78 -- External Sensor Status                          
  BEGIN                         
   SET @vcAlarmDetail = REPLACE(SUBSTRING(@vcAlarmDesc, CHARINDEX('ExSensorNo',@vcAlarmDesc) + 13,                           
      (LEN(@vcAlarmDesc) - CHARINDEX('ExSensorNo',@vcAlarmDesc))), ';', '')                          
   SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, ' degree Celsius' ,'°C')                           
      SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, ' mV' ,'lit.')                           
  END                          
 ELSE IF @tiBoxMsgInTypeID = 79 -- BioEntry                          
  BEGIN                          
   SET @vcAlarmDetail = 'BioEntry ' + SUBSTRING(@vcAlarmDesc, CHARINDEX('User Id',@vcAlarmDesc),                           
      (LEN(@vcAlarmDesc) - CHARINDEX('User Id',@vcAlarmDesc)))                          
                             
   DECLARE @UserId AS BIGINT = 0                          
   SET @UserId = CONVERT(BIGINT, REPLACE(SUBSTRING(@vcAlarmDetail, CHARINDEX('User Id',@vcAlarmDetail)+8,        
      (LEN(@vcAlarmDetail)- CHARINDEX('User Id',@vcAlarmDetail))), ';', ''))                          
                             
  -- IF EXISTS(SELECT u.UserId FROM rvlfBiometricUsers u                          
  --     INNER JOIN rvlfVehicleAssignment va ON va.BoxId = @intBoxID              
  --INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId           
  --     WHERE u.UserId = @UserId AND v.OrganizationId = 35)                 
  -- BEGIN                  
  --  SELECT @vcAlarmDetail = UserName FROM rvlfBiometricUsers WHERE UserId = @UserId                          
  --  SET @vcAlarmDetail = 'BioEntry User Name=' + @vcAlarmDetail                          
  -- END                          
  END                          
 ELSE IF @tiBoxMsgInTypeID = 80 -- Card Reader                          
 BEGIN                          
  SET @vcAlarmDetail = SUBSTRING(@vcAlarmDesc, CHARINDEX('Card ID',@vcAlarmDesc),                           
     (LEN(@vcAlarmDesc) - CHARINDEX('Card ID',@vcAlarmDesc) + 1))                          
 END                          
 ELSE IF @tiBoxMsgInTypeID = 89 -- Vehicle Fuel Fill                          
 BEGIN                          
 SELECT @vcAlarmDetail = Case when @Lang = 'LanguageArNew' Then isnull(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi'                   
 THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc) else BoxMsgInTypeDesc  END FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                        
 -- SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                          
                            
  IF CHARINDEX('Vehicle Fuel Fill=', @vcAlarmDesc) > 0                          
  BEGIN                          
                            
   SET @vcAlarmDetail = SUBSTRING(@vcAlarmDesc, CHARINDEX('Vehicle Fuel Fill=',@vcAlarmDesc), (LEN(@vcAlarmDesc) - CHARINDEX('Vehicle Fuel Fill=',@vcAlarmDesc)) + 1)             
   SET @vcAlarmDetail = CASE WHEN CHARINDEX(';',@vcAlarmDetail) <> 0 THEN @vcAlarmDetail ELSE @vcAlarmDetail + ';' END                          
   SET @vcAlarmDetail =  SUBSTRING(@vcAlarmDetail, CHARINDEX('Vehicle Fuel Fill=',@vcAlarmDetail), (CHARINDEX(';', @vcAlarmDetail) - CHARINDEX('Vehicle Fuel Fill=',@vcAlarmDetail)))                          
   SET @vcAlarmDetail = REPLACE(@vcAlarmDetail,'litres','ml')                            
  END                          
 END                          
 ELSE IF @tiBoxMsgInTypeID = 90 -- Alarm - Vehicle Fuel Drain                          
 BEGIN                          
	SELECT @vcAlarmDetail = Case when @Lang = 'LanguageArNew' Then isnull(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi' THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc) else BoxMsgInTypeDesc END 
	FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                          
	--SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                          
                            
 IF CHARINDEX('Actual Fuel Drained', @vcAlarmDesc) > 0                          
  BEGIN                                                    
      SELECT @vcAlarmDetail = 'Actual Fuel Drained=' + (SUBSTRING(@vcAlarmDesc, CHARINDEX('Actual Fuel Drained',@vcAlarmDesc) + 20,                           
      (CHARINDEX(' litres',@vcAlarmDesc) - CHARINDEX('Actual Fuel Drained',@vcAlarmDesc)) - 20)) + ' litres'                          
  END                          
 END                          
 ELSE IF @tiBoxMsgInTypeID = 94 -- Send Voice Call Info                          
 BEGIN                          
                            
  SELECT @vcAlarmDetail = SUBSTRING(@vcAlarmDesc, CHARINDEX('Call Direction',@vcAlarmDesc),                           
      (CHARINDEX('Remote Number',@vcAlarmDesc) - CHARINDEX('Call Direction',@vcAlarmDesc)))                          
  SELECT @vcAlarmDetail = REPLACE(REPLACE(REPLACE(@vcAlarmDetail, '$$', ':'), 'Call Direction', 'Call'),                          
          'Call Duration', 'Duration')                          
                           
 END                          
 ELSE IF @tiBoxMsgInTypeID = 98 -- MTD User Login Status to Server                          
 BEGIN                
                            
  DECLARE @MDTUsrId AS Varchar(50) = SUBSTRING(@vcAlarmDesc, CHARINDEX('User ID=',@vcAlarmDesc) + 8,                           
           (CHARINDEX(';;',@vcAlarmDesc) - CHARINDEX('User ID=',@vcAlarmDesc) - 8))                          
                                     
  --IF EXISTS (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUsrId AND UserId IN (SELECT UserId FROM rvlfMDTBoxMessageTable WHERE BoxId = @intBoxID))                          
  --BEGIN                          
                            
  -- SET @MDTUsrId = (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUsrId AND UserId IN (SELECT UserId FROM rvlfMDTBoxMessageTable WHERE BoxId = @intBoxID))                          
                            
  --END                          
                       
  SET @vcAlarmDetail = @MDTUsrId + ' logged ' + SUBSTRING(@vcAlarmDesc, CHARINDEX('Login Status=',@vcAlarmDesc) + 13,                           
           (CHARINDEX(';',@vcAlarmDesc) - CHARINDEX('Login Status=',@vcAlarmDesc) - 13))                          
                
 END                          
 ELSE IF @tiBoxMsgInTypeID = 100 -- RFID Message                          
 BEGIN                          
                                   
  SET @vcAlarmDetail = REPLACE(@vcAlarmDesc, ';', '')                           
                           
 END                          
 ELSE IF @tiBoxMsgInTypeID IN (37, 38, 39, 42, 45, 46, 47, 48, 49, 50)                          
  BEGIN                          
   --SET @FuelLevelPercentage =(( CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                          
   --   THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                          
   --   LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int) * 33)-600)/24.1                          
    SET @FuelLevelPercentage =CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                          
      THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                          
      LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int)                          
   SET @FuelLevelPercentage = CASE WHEN @FuelLevelPercentage <=0 THEN 0 ELSE @FuelLevelPercentage END                          
   SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = ISNULL(CapacityUnits,'gals') FROM rvlfVehicle v INNER JOIN                          
    rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID                          
                           
   SELECT @vcAlarmDetail = Case when @Lang = 'LanguageArNew' Then isnull(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi'                   
   THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc) else BoxMsgInTypeDesc END FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                          
 --  SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                          
   SELECT @vcAlarmDetail = @vcAlarmDetail                           
    + ' ('+ cast(@FuelLevelPercentage as varchar(3))+ '% - '+                           
    cast(cast(((@FuelLevelPercentage / 100.00) * @tankCapacity)as int) as varchar(5)) +' '+ @vcFuelUnits +')'                          
     --CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                          
     -- THEN ' (' +  REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                          
     -- LEN(@vcAlarmDesc)), ';', '%)') ELSE '' END                          
  END                          
 --ELSE IF @tiBoxMsgInTypeID = 54                          
 -- BEGIN                          
 --  --SELECT @vcAlarmDetail = '<table><tr><td>'+ REPLACE(REPLACE(@vcAlarmDesc,'=','<td>:</td><td>'),';','</td></tr><tr><td>' )+'</table>'      
 -- END                          
 --ELSE IF @tiBoxMsgInTypeID = 51               
 -- BEGIN                          
 --  SET @vcAlarmDetail = 'Speed viol                          
 -- END                          
 ELSE IF @tiBoxMsgInTypeID = 97 -- Send harsh thresholds                          
  BEGIN                          
   DECLARE @VCHB VARCHAR(10),@VCEB VARCHAR(10),@VCHA VARCHAR(10),@VCEA VARCHAR(10),@VCHC VARCHAR(10),@VCHCA VARCHAR(10)                          
                             
   SET @VCHB= CASE WHEN @vcAlarmDesc LIKE '%HB=%' THEN SUBSTRING(@vcAlarmDesc,CHARINDEX('HB=',@vcAlarmDesc,1)+3,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('HB=',@vcAlarmDesc,1))-(CHARINDEX('HB=',@vcAlarmDesc,1)+3)) ELSE '0' END                          
   SET @VCEB=CASE WHEN @vcAlarmDesc LIKE '%EB=%' THEN SUBSTRING(@vcAlarmDesc,CHARINDEX('EB=',@vcAlarmDesc,1)+3,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('EB=',@vcAlarmDesc,1)) - (CHARINDEX('EB=',@vcAlarmDesc,1)+3)) ELSE '0' END                          
   SET @VCHA=CASE WHEN @vcAlarmDesc LIKE '%HA=%' THEN SUBSTRING(@vcAlarmDesc,CHARINDEX('HA=',@vcAlarmDesc,1)+3,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('HA=',@vcAlarmDesc,1))-(CHARINDEX('HA=',@vcAlarmDesc,1)+3)) ELSE '0' END                          
   SET @VCEA=CASE WHEN @vcAlarmDesc LIKE '%EA=%' THEN SUBSTRING(@vcAlarmDesc,CHARINDEX('EA=',@vcAlarmDesc,1)+3,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('EA=',@vcAlarmDesc,1))-(CHARINDEX('EA=',@vcAlarmDesc,1)+3))ELSE '0' END                          
   SET @VCHC=CASE WHEN @vcAlarmDesc LIKE '%HC=%' THEN SUBSTRING(@vcAlarmDesc,CHARINDEX('HC=',@vcAlarmDesc,1)+3,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('HC=',@vcAlarmDesc,1))-(CHARINDEX('HC=',@vcAlarmDesc,1)+3))ELSE '0' END                          
   SET @VCHCA=CASE WHEN @vcAlarmDesc LIKE '%HC_Angle=%' THEN SUBSTRING(@vcAlarmDesc,CHARINDEX('HC_Angle=',@vcAlarmDesc,1)+9,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('HC_Angle=',@vcAlarmDesc,1))-(CHARINDEX('HC_Angle=',@vcAlarmDesc,1)+9))ELSE '0' END          


                           
    SET @vcAlarmDetail='Harsh Braking='+ @VCHB+' Miles;Extreme Braking='+@VCEB+' Miles;Harsh Acceleration='+@VCHA+' Miles;Extreme Acceleration='+@VCEA+' Miles;Harsh Corner='+@VCHC+' Miles;Harsh Corner_Angle='+@VCHCA+';'                                    

  
  END                          
 ELSE IF @tiBoxMsgInTypeID = 23 -- Battery Status messages                          
  BEGIN                          
   DECLARE @tintBatteyId tinyint=null                          
   DECLARE @vcBatteryName varchar(50)=null                          
   SET @tintBatteyId = CASE WHEN @vcAlarmDesc LIKE '%Battery Name=%' THEN CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('Battery Name=',@vcAlarmDesc,1)+13,CHARINDEX(';',@vcAlarmDesc,CHARINDEX('Battery Name=',@vcAlarmDesc,1))-(CHARINDEX('Battery Name=',           


       
   @vcAlarmDesc,1)+13)) AS TINYINT) ELSE 0 END                          
                             
   IF(@tintBatteyId=1)                          
    BEGIN       
     SET @vcBatteryName='Main Battery Disconnected'                          
    END                          
   ELSE IF(@tintBatteyId=2)                          
    BEGIN                          
     SET @vcBatteryName='Main Battery Connected'                          
    END                          
   ELSE IF(@tintBatteyId=3)                          
    BEGIN                          
     SET @vcBatteryName='Backup Battery Disconnected'                          
    END                          
   ELSE IF(@tintBatteyId=4)                          
    BEGIN                          
     SET @vcBatteryName='Backup Battery Connected'                          
    END                          
   ELSE IF(@tintBatteyId=5) 
    BEGIN            
     SET @vcBatteryName='Backup Battery Empty'                          
    END                          
ELSE              
    BEGIN                    
     SET @vcBatteryName='Battery Status'                          
    END                          
                             
    SET @vcAlarmDetail=@vcBatteryName                          
  END                          
 ELSE IF @tiBoxMsgInTypeID = 113 -- Speed Band                          
 BEGIN                          
  SET @vcAlarmDetail=SUBSTRING(@vcAlarmDesc,CHARINDEX('Band Name=',@vcAlarmDesc,1)+10,(CHARINDEX(';',@vcAlarmDesc,CHARINDEX('Band Name=',@vcAlarmDesc,1))-(CHARINDEX('Band Name=',@vcAlarmDesc,1)+10)))+' ['+                          
  dbo.rvlf_fn_GetTimeFromSeconds(CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('Duration=',@vcAlarmDesc,1)+9,(CHARINDEX(';',@vcAlarmDesc,CHARINDEX('Duration=',@vcAlarmDesc,1))-(CHARINDEX('Duration=',@vcAlarmDesc,1)+9))) as int))+']'                          
 END                          
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('08;Idling:',@vcAlarmDesc) <> 0  --Sakthi 21-May-2012 for Idling Time                          
 BEGIN                          
  --SELECT @vcAlarmDetail =SUBSTRING(@vcAlarmDesc,4,LEN(@vcAlarmDesc))                          
  --SELECT @vcAlarmDetail = REPLACE(@vcAlarmDetail,':',' : ')                          
  --SELECT @vcAlarmDetail = REPLACE(@vcAlarmDetail,';',' secs </br> ')+' secs'                          
  SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeId=122                          
 END                          
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('09;Engine',@vcAlarmDesc) <> 0  --Sakthi 05-Jun-2012 for Send Vehicle Parameter                          
 BEGIN                          
  SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeId=123                          
 END                          
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('10;Odometer Offset:',@vcAlarmDesc) <> 0  --Sakthi 05-Jun-2012 for Odometer Offset and MAF State                          
 BEGIN                          
  SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeId=124                          
 END 
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('13;Battery',@vcAlarmDesc) <> 0  --17-aug 13;Battery Low:18; Battery Ok:22                          
 BEGIN                          
  SELECT @vcAlarmDetail = REPLACE(@vcAlarmDesc,'13;Battery','Battery')                            
 END                          
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('StopId:',@vcAlarmDesc) <> 0  --Sakthi 19-Jan-2012 for Garmin                          
 BEGIN                          
  SELECT @vcAlarmDetail = ISNULL((SELECT l.LandmarkName FROM rvlfLandmark l INNER JOIN rvlfGarminStop gs ON gs.LandmarkId=l.LandmarkID                          
  INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=gs.VehicleId                          
  WHERE va.BoxId= @intBoxID AND                          
  gs.StopId=SUBSTRING(@vcAlarmDesc,CharIndex('StopId:',@vcAlarmDesc)+7,(CHARINDEX(';Status',@vcAlarmDesc)-(CHARINDEX('StopId:',@vcAlarmDesc)+7))))+ ' - '+                          
  SUBSTRING(@vcAlarmDesc,CharIndex(';Status',@vcAlarmDesc)+8,LEN(@vcAlarmDesc)),'Deleted Stop')   
     
 END                          
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('; Fuel Consumption',@vcAlarmDesc) <> 0  --Sakthi 24-Feb-2012 for OBD                          
 BEGIN                          
  SELECT @vcAlarmDetail ='Distance : '+dbo.rvlf_fn_GetParamValueWithIndex (@vcAlarmDesc+';','Distance Travelled:',';')+' Km; Fuel : '          
  +CAST(CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex (@vcAlarmDesc+';','Fuel Consumption:',';') AS decimal(10,2))/1000 AS DECIMAL(10,2)) AS VARCHAR)+' lit, Mileage : '        
  +CAST(CAST(CAST( dbo.rvlf_fn_GetParamValueWithIndex (@vcAlarmDesc+';','Mileage:',';') AS decimal(10,2))/1000 AS DECIMAL(10,2)) AS VARCHAR)+' Kmpl and Mileage in (L/100Km) : '  +        
  +(CASE WHEN CAST(dbo.rvlf_fn_GetParamValueWithIndex (@vcAlarmDesc+';','Mileage:',';') AS INT) > 0 THEN        
  CAST(CAST(100000.00 / CAST(dbo.rvlf_fn_GetParamValueWithIndex (@vcAlarmDesc+';','Mileage:',';') AS decimal(10,2)) AS DECIMAL(10,2)) AS VARCHAR)        
 ELSE '0.00' END)        
          
 --'Distance : '+SUBSTRING(@vcAlarmDesc,CHARINDEX('; Distance Travelled',@vcAlarmDesc,0)+21,(LEN(@vcAlarmDesc)-(CHARINDEX('; Distance Travelled',@vcAlarmDesc,0)+19)))+' Km,                       
  --Fuel '+CAST(CAST(CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('; Fuel Consumption',@vcAlarmDesc,0)+19,((CHARINDEX('; Distance',@vcAlarmDesc,0)-1)-
  --(CHARINDEX('; Fuel Consumption',@vcAlarmDesc,0)+18))) AS decimal(10,2))/1000 AS DECIMAL(10,2)) AS VARCHAR)+' lit      
 --and                       
  --Mileage : '+CAST(CAST(CAST(SUBSTRING(@vcAlarmDesc,12,CHARINDEX('; Fuel Consumption',@vcAlarmDesc,0)-12) AS decimal(10,2))/1000 AS DECIMAL(10,2)) AS VARCHAR)+' Kmpl'                      
                     
  --'Mileage : '+                          
  --CAST(CAST(CAST(SUBSTRING(@vcAlarmDesc,12,CHARINDEX('; Fuel Consumption',@vcAlarmDesc,0)-12) AS decimal(10,2))/1000 AS DECIMAL(10,2)) AS VARCHAR)+' Kmpl and Fuel '+                          
  --CAST(CAST(CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('; Fuel Consumption',@vcAlarmDesc,0)+19,LEN(@vcAlarmDesc)-(CHARINDEX('; Fuel Consumption',@vcAlarmDesc,0)+18)) AS decimal(10,2))/1000 AS DECIMAL(10,2)) AS VARCHAR)+' lit'                          
 END                          
 ELSE IF  @tiBoxMsgInTypeID=114 AND CharIndex('06;No of DTC',@vcAlarmDesc) <> 0                          
 BEGIN                          
  SET @vcAlarmDetail= CASE WHEN CAST(SUBSTRING(@vcAlarmDesc,20,1) AS INT)=0 THEN 'No DTC Codes'                          
       ELSE 'DTC Codes' END                          
 END                       
  ELSE IF  @tiBoxMsgInTypeID=114 AND CHARINDEX('GeozoneInOutWithDuration:',@vcAlarmDesc) <>0 and 
   SUBSTRING(@vcAlarmDesc, CHARINDEX('GeozoneInOutWithDuration:',@vcAlarmDesc)+25,1) = '1'  -- Ranjith Geozone InOut with Duration 15-Mar-2013                
 Begin                      
 DECLARE @vcGeozoneName varchar(50)=null                       
 SELECT @vcGeozoneName = g.GeozoneName                        
 FROM rvlfOrganizationGeozone g INNER JOIN rvlfVehicle v                       
     ON g.OrganizationId=v.OrganizationId INNER JOIN rvlfVehicleAssignment va ON                       
     v.VehicleId = va.VehicleId                       
    -- INNER JOIN rvlfVehicleGeozone vg ON vg.VehicleID = v.VehicleID AND                       
      --  vg.GeozoneNo = g.GeozoneId                      
     WHERE BoxId = @intBoxID and GeozoneId = --CAST(@vcAlarmDesc as bigint)                      
     (CAST( SUBSTRING(@vcAlarmDesc, CHARINDEX('GeozoneID=',@vcAlarmDesc,0)+10,                      
     (CHARINDEX(';',@vcAlarmDesc,CHARINDEX('GeozoneID=',@vcAlarmDesc,1)))                       
     -(CHARINDEX('GeozoneID=',@vcAlarmDesc,1)+10)) as bigint))                      
                       
  --SET @vcAlarmDetail='Geozone='+ isnull(@vcGeozoneName,'Unknown') + ' Out (Duration:' + Replace(SUBSTRING(@vcAlarmDesc, CHARINDEX(';Duration', @vcAlarmDesc)+10,LEN(@vcAlarmDesc)),':',':') + ')'                      
   -- SET @vcAlarmDetail= isnull(@vcGeozoneName,'Unknown Geozone') + ' - Out (Duration:' + Replace(SUBSTRING(@vcAlarmDesc, CHARINDEX(';Duration', @vcAlarmDesc)+10,LEN(@vcAlarmDesc)),':',':') + ')'                        
  SET @vcAlarmDetail=   isnull(@vcGeozoneName,'Unknown') + ' Out (Duration:' + 
	   dbo.rvlf_fn_getparamvaluewithindex(replace(@vcAlarmDesc,';Duration:',';Duration='),'Duration=',';') + ')'
 End                      
 ELSE IF  @tiBoxMsgInTypeID=114 AND SUBSTRING(@vcAlarmDesc, CHARINDEX('IButtonCommand:', @vcAlarmDesc)+15,1) = '1'  -- Ranjith Send IButton Param                      
 Begin        
                       
  SET @vcAlarmDetail='Send iButton Param'                      
                           
 End                   
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('34;RouteID=',@vcAlarmDesc) <> 0   
 BEGIN                                
 Declare @RouteID bigint=0,@StopID bigint=0                    
 Declare @RouteName Varchar(150)=null,@StopName Varchar(150)=null,@RouteAlertMsg varchar(3)=null                    
 set @RouteID=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'RouteID=',';'))                    
 set @RouteName = isnull((select RouteName from rvlfRouteMaster where RouteID=@RouteID),'Invalid Route')                    
 set @StopID=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'StopID=',';'))                    
 set @StopName = isnull((select GeozoneName from rvlfOrganizationGeozone where GeozoneId=@StopID and OrganizationId = (select OrganizationId from rvlfBoxId where BoxId=@intBoxID)),'Invalid Stop')                   
 set @RouteAlertMsg=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'AlertMsg=',';'))                    
 SET @vcAlarmDetail= (case when @RouteAlertMsg=001 then @RouteName +' Route started.'                    
       when @RouteAlertMsg=010 then @RouteName +' Route-'+@StopName+ ' Stop Arrival.'                    
       when @RouteAlertMsg=011 then @RouteName +' Route-'+@StopName+ ' Stop Departure.'                    
       when @RouteAlertMsg=100 then @RouteName +' Route-'+@StopName+ ' Stop Completion.'                    
       when @RouteAlertMsg=101 then @RouteName +' Route-'+@StopName+ ' Stop Start Delay.'                    
       when @RouteAlertMsg=110 then @RouteName +' Route-'+@StopName+ ' Stop Delay.'                    
       when @RouteAlertMsg=111 then @RouteName +' Route Delay.' else 'Unkown Route Details' end)             
 set @StopID=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'NxtStopID=',';'))                    
 set @StopName = isnull((select GeozoneName from rvlfOrganizationGeozone where GeozoneId=@StopID and OrganizationId = (select OrganizationId from rvlfBoxId where BoxId=@intBoxID)),'Invalid Stop')          
           
 set @vcAlarmDetail = @vcAlarmDetail + ';NxtStop-' + @StopName    
     
 -- + ';Duration(Mints):'+ dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'Duration(Mints)=',';') +';Distance(km)'+ dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'Distance=',';')          
                   
 END  --34;RouteID=114;StopID=64;NxtStopID=65;Duration(Mints)=0;Distance=1024;AlertMsg=111  
 
 ELSE IF @tiBoxMsgInTypeID = 114 and CHARINDEX('38;FuelTankLength',@vcAlarmDesc,0) <> 0  
 BEGIN 
	set @vcAlarmDetail = 'Send Ultrasonic Fuel Sensing Parameters'  
 END
        
ELSE IF @tiBoxMsgInTypeID = 161                                
BEGIN                                
 SELECT @vcAlarmDetail='Sudden Temperature Fall (Variance : ' + SUBSTRING( @vcAlarmDesc,CHARINDEX('Variance=',@vcAlarmDesc,0)+9, (CHARINDEX(';',@vcAlarmDesc,CHARINDEX('Variance=',@vcAlarmDesc,0))-(CHARINDEX('Variance=',@vcAlarmDesc,0)+9))) +'°C)'        


            
                        
END               
 ELSE IF @tiBoxMsgInTypeID=152                                      
BEGIN                                 
 SELECT @vcAlarmDetail='Restricted Geozone ' +ISNULL(og.GeozoneName,'')+' IN' FROM rvlfOrganizationGeozone og INNER JOIN rvlfBoxId b ON b.OrganizationId=og.OrganizationId                                      
WHERE og.GeozoneId=SUBSTRING(@vcAlarmDesc,CHARINDEX('GeozoneID=',@vcAlarmDesc,0)+10,(CHARINDEX(';Odometer=',@vcAlarmDesc,0)-                                      
 (CHARINDEX('GeozoneID=',@vcAlarmDesc,0)+10))) AND og.OrganizationId=6                                      
END                         
--Route Alerts 13-Apr-15          
 --ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('34;RouteID:',@vcAlarmDesc) <> 0                                                      
 --BEGIN                         
 --Declare @RouteID bigint=0,@StopID bigint=0          
 --Declare @RouteName Varchar(150)=null,@StopName Varchar(150)=null,@RouteAlertMsg varchar(3)=null          
 --set @RouteID=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'RouteID:',';'))          
 --set @RouteName = (select RouteName from rvlfRouteMaster where RouteID=@RouteID) 
 --set @StopID=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'StopID:',';'))          
 --set @StopName = (select LandmarkName from rvlfLandmark where LandmarkID=@StopID)          
 --set @RouteAlertMsg=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'AlertMsg:',';'))          
 --SET @vcAlarmDetail= (case when @RouteAlertMsg=001 then @RouteName +' Route started.'          
 --      when @RouteAlertMsg=010 then @RouteName +' Route'+@StopName+ ' Stop Arrival.'          
 --      when @RouteAlertMsg=011 then @RouteName +' Route'+@StopName+ ' Stop Departure.'          
 --      when @RouteAlertMsg=100 then @RouteName +' Route'+@StopName+ ' Stop Completion.'          
 --      when @RouteAlertMsg=101 then @RouteName +' Route'+@StopName+ ' Stop Start Delay.'          
 --      when @RouteAlertMsg=110 then @RouteName +' Route'+@StopName+ ' Stop Delay.'          
 --      when @RouteAlertMsg=111 then @RouteName +' Route Delay.' else 'Unkown Route Details' end)          
 --END          
           
 ELSE IF  @tiBoxMsgInTypeID=114 AND @vcAlarmDesc like '%PacketType:%'  -- Ranjith Send Camera Header packet Type                      
 Begin                      
  Declare @VcPacketType bigint = SUBSTRING(@vcAlarmDesc, CHARINDEX('PacketType:',@vcAlarmDesc,0)+11,len(@vcAlarmDesc) -(CHARINDEX('PacketType:',@vcAlarmDesc,1)+10))                      
  SET @vcAlarmDetail = (                      
  Case When @VcPacketType = 1 then  ' (Ignition ON)'  When @VcPacketType = 2 then ' (Ignition OFF)'                      
  When @VcPacketType = 3 then  ' (Door Close)'  When @VcPacketType = 4 then ' (Trunk Open)'                      
  When @VcPacketType = 5 then ' (Panic)' When @VcPacketType = 6 then ' (Speed Alert)'                      
  When @VcPacketType = 7 then ' (Idling)' When @VcPacketType = 8 then ' (Ext.Idling)'           
  When @VcPacketType = 9 then ' (Harsh/Extreme Braking)' When @VcPacketType = 10 then ' (Geofence)'                      
  When @VcPacketType = 11 then ' (Geozone IN)' When @VcPacketType = 12 then ' (GPS ANT Open)'                      
  When @VcPacketType = 13 then ' (Igntion ON - Periodic Click)' When @VcPacketType = 14 then ' (Igntion OFF - Periodic Click)'                      
  When @VcPacketType = 15 then ' (RFID)'                      
  else ' (N/A)'                      
  end)                            
 End       
 ELSE                          
 BEGIN                          
                            
    SELECT @vcAlarmDetail = Case when @Lang = 'LanguageArNew' Then isnull(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi' THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc) else BoxMsgInTypeDesc END FROM rvlfBoxMsgInType                




	 
   
    WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                        
  --SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                          
  IF  @tiBoxMsgInTypeID=109 OR @tiBoxMsgInTypeID=110 OR @tiBoxMsgInTypeID=125 OR @tiBoxMsgInTypeID=126                          
  BEGIN                          
    SET @vcAlarmDetail = REPLACE(@vcAlarmDetail,'Non Alarm-','')                          
  END                          
  IF EXISTS (SELECT * FROM rvlfPackageOperations r                          
     INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId                          
     INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId                          
     INNER JOIN rvlfVehicle v ON g.OrganizationId = v.OrganizationId                           
     INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId                    
       WHERE p.IsActive = 1 AND va.BoxId = @intBoxID AND r.OperationID = 95)                          
       AND                          
       --Commented on 30-Jul-10 for Testing GetBoxStatus                          
       @tiBoxMsgInTypeID NOT IN (19,20,21,22,35,40,55,54,56,53,1,12,10) --or @intBoxID = 999985 --or @intBoxID = 999983                  
       --@tiBoxMsgInTypeID NOT IN (19,20,21,35,40,55,54,56,53) --or @intBoxID = 999985                          
--End                          
   BEGIN                          
    --SET @FuelLevelPercentage =(( CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                          
    --  THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                          
    --  LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int) * 33)-600)/24.1                          
                              
    IF CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                          
    BEGIN               
     SET @FuelLevelPercentage =CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                          
       THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,                          
       LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int)                          
     SET @FuelLevelPercentage = CASE WHEN @FuelLevelPercentage <=0 THEN 0 ELSE @FuelLevelPercentage END                          
     SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = ISNULL(CapacityUnits,'gals') FROM rvlfVehicle v INNER JOIN                          
      rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID                          
                               
      SELECT @vcAlarmDetail = Case when @Lang = 'LanguageArNew' Then isnull(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi'                   
                        
      THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc) else BoxMsgInTypeDesc END FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                         
     --SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                          
     SELECT @vcAlarmDetail = @vcAlarmDetail                           
     +                           
      CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                          
       THEN ' (Fuel Level = '              
       + cast(@FuelLevelPercentage as varchar(3))+ '% - '+                           
      cast(cast(((@FuelLevelPercentage / 100.00) * @tankCapacity)as int) as varchar(5)) +' '+ @vcFuelUnits +')'                          
     END        
    END                          
   END                          
 END                           
                           
  SET @vcAlarmDetail =	REPLACE(REPLACE(REPLACE(REPLACE(@vcAlarmDetail, 'Temperature Sensor-1', 'Temperature-1')
												, 'Temperature Sensor-2', 'Temperature-2')
										, 'Temperature Sensor-3', 'Temperature-3')
								, 'Temperature Sensor-4', 'Temperature-4') 
                           
 IF @tiBoxMsgInTypeID NOT IN (4,18,42,51,78,89,90)                      
 BEGIN                          
                           
  DECLARE @t1 AS Varchar(10)                          
  DECLARE @t2 AS Varchar(10)  
  DECLARE @t3 AS Varchar(10)
  DECLARE @t4 AS Varchar(10)
  DECLARE @fuel AS Varchar(10)                          
  DECLARE @Temp1 as Bit
  DECLARE @Temp2 as Bit
  DECLARE @Temp3 as Bit
  DECLARE @Temp4 as Bit
  DECLARE @vcAlarmTemp As Varchar(1000)                          
                            
  SET @vcAlarmTemp = @vcAlarmDesc                          
                      
    --Enable the temparature sensor                          
     DECLARE @tblDriverDetails TABLE(Temp INT,Temp2 INT, Temp3 INT, Temp4 INT)         
     INSERT into @tblDriverDetails (Temp,Temp2,Temp3,Temp4)         
                            
     SELECT Temp1 = CASE WHEN PO.OperationID IN(179,231) and PO.ModuleID IN (26,35) THEN 1 ELSE 0 END,              
			Temp2 = CASE WHEN PO.OperationID IN(180,234) and PO.ModuleID IN (26,35) THEN 1 ELSE 0 END,
			Temp3 = CASE WHEN PO.OperationID IN(396) and PO.ModuleID IN (26) THEN 1 ELSE 0 END,
			Temp4 = CASE WHEN PO.OperationID IN(397) and PO.ModuleID IN (26) THEN 1 ELSE 0 END
	 FROM rvlfVehicleAssignment va                           
     INNER JOIN rvlfBoxId b ON  b.BoxId = va.BoxId                          
     INNER JOIN rvlfOrganization o ON o.OrganizationId = b.OrganizationId                          
     INNER JOIN rvlfOrganizationPackage p ON p.OrganizationID =o.OrganizationId                          
     INNER JOIN rvlfPackageOperations po ON po.PackageId = p.PackageId                          
     WHERE po.ModuleID IN(26,35) and p.IsActive =1 AND b.BoxId IN (@intBoxID)         
     -- Device which should not display temp info are listed in NOT IN (Anbarasu.E)
     AND @intBoxID NOT IN (
		--Internal	[6]
		2684,999910,999911,999981,999985,999987,999988,999996,		--999980,999888 commented on 12-Jan-2016
		--Admirals Trading LLC[40]
		144,148,149,150,154,155,156,157,158,159,162,163,164,233,4205,4321,
		--Sinha Marketing[75]
		98,218,230,
		--Zulkom FZCO[119]
		487,682,2148,4171,4413,4414,4415,
		--Prestige Trading Establishment[126]
		678,679,680,681,
		--Black Tulip Flowers[170]
		4195,4196,4197,4198,4199,4200,4201,4202,4203,4204,
		--Bharat Refrigerations Pvt Ltd[209]
		4182,4237,
		--Kelvin Cold Chain Logistics Pvt Ltd[210]
		4303,
		--Emirates Private School[217]		
		4283,4284,4285,4286,4287,4288,4289,4290,4291,4292,4293,4294,4295,4296,4297,4298,4299,4300,4301,
		--HOV General Trading devices[244] (24-Aug-2015 - Anbarasu.E)
		4378,4379,4380,4381,4382,4383,4384,4385,4386,4387,4388)
     --AND @intBoxID in(4483,4482,999222)        
     --OR (@intBoxID IN (999986,165,166,167,168,40,283,242,667,646,647,648,685,686,687,2149,4177,4183,4184,4185,4186,4187             
     --) or @intBoxID between 2115 and 2146)                            
     AND PO.OperationID IN (179,180,231,234,396,397)  GROUP BY po.OperationID,po.ModuleID        
             
	 SELECT @Temp1= MAX(Temp), @Temp2 = MAX(Temp2), @Temp3= MAX(Temp3), @Temp4 = MAX(Temp4) FROM @tblDriverDetails                       
                            
       -- IF EXISTS(SELECT va.BoxId FROM rvlfVehicleAssignment va                          
       --INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId                          
       --WHERE ((va.BoxId = @intBoxID AND v.OrganizationId = 6) OR (@intBoxId=652 AND @dtOriginDateTime > CAST('2012-02-14 00:00:00.000' AS datetime))                          
       --OR @intBoxID IN (165,166,167,168,40,283,242,667,646,647,648,685,686,687,2149,2150,2151)) or @intBoxID between 2115 and 2146 AND @intBoxID <> 999222)                          
 IF (@Temp1 = 1 OR  @Temp1 = 0)                  
	BEGIN
		-- Check Temperature Sensor 1,2,3 & 4
		IF CHARINDEX('Temperature Sensor-1 Value',@vcAlarmDesc, 1) <> 0                       
			--IF CHARINDEX('Temperature Sensor-1 Value',@vcAlarmDesc, 1) <> NULL                      
		BEGIN                      
			IF(@Temp1 = 1)                      
			BEGIN                      
				IF SUBSTRING(@vcAlarmDesc, CHARINDEX('Temperature Sensor-1 Value',@vcAlarmDesc)+27, 12) = 'Disconnected'                      
				BEGIN                           
					SET @t1 = 'PD'	                           
				END                      
				ELSE                      
				BEGIN                                                 
					SET @t1 = SUBSTRING(@vcAlarmDesc, CHARINDEX('Temperature Sensor-1 Value',@vcAlarmDesc)+27,                       
					(CHARINDEX(' degree Celsius',@vcAlarmDesc) - CHARINDEX('Temperature Sensor-1 Value',@vcAlarmDesc))-27)                      
				END                      
			END
		END                                               
		--Temp2
		--IF (@intBoxID NOT IN (165,166,167,168,40,999983,667,646,647,648,2149,2150,2151,4187,4045,4046,4063,4235) AND @Temp2 = 1)
		--BEGIN                 
		--	IF CHARINDEX('Temperature Sensor-2 Value',@vcAlarmTemp, 1) <> 0                    
		--	BEGIN
		--		SET @vcAlarmTemp = SUBSTRING(@vcAlarmDesc, CHARINDEX('Temperature Sensor-2 Value',@vcAlarmDesc),                       
		--		(LEN(@vcAlarmDesc) - CHARINDEX('Temperature Sensor-2 Value',@vcAlarmDesc)))
				
		--		IF SUBSTRING(@vcAlarmTemp, CHARINDEX('Temperature Sensor-2 Value',@vcAlarmTemp)+27, 12) = 'Disconnected'                      
		--		BEGIN 
		--			SET @t2 = 'PD'                                                  
		--		END                      
		--		ELSE                      
		--		BEGIN                                                  
		--			SET @t2 = SUBSTRING(@vcAlarmTemp, CHARINDEX('Temperature Sensor-2 Value',@vcAlarmTemp)+27,          
		--			(CHARINDEX(' degree Celsius',@vcAlarmTemp) - CHARINDEX('Temperature Sensor-2 Value',@vcAlarmTemp))-27)                                                     
		--		END                       
		--	END                      
		--END
		--Temp3
		--IF (@intBoxID IN (5247,5248 /*,999888*/) AND @Temp3 = 1)
		--BEGIN                      
		--	IF CHARINDEX('Temperature Sensor-3 Value',@vcAlarmTemp, 1) <> 0                      
		--	BEGIN
		--		SET @vcAlarmTemp = SUBSTRING(@vcAlarmDesc, CHARINDEX('Temperature Sensor-3 Value',@vcAlarmDesc),                       
		--		(LEN(@vcAlarmDesc) - CHARINDEX('Temperature Sensor-3 Value',@vcAlarmDesc)))
		--		IF SUBSTRING(@vcAlarmTemp, CHARINDEX('Temperature Sensor-3 Value',@vcAlarmTemp)+27, 12) = 'Disconnected'                      
		--		BEGIN                                                  
		--			SET @t3 = 'PD'                                                  
		--		END                      
		--		ELSE                      
		--		BEGIN                                                  
		--			SET @t3 = SUBSTRING(@vcAlarmTemp, CHARINDEX('Temperature Sensor-3 Value',@vcAlarmTemp)+27,          
		--			(CHARINDEX(' degree Celsius',@vcAlarmTemp) - CHARINDEX('Temperature Sensor-3 Value',@vcAlarmTemp))-27)                                                     
		--		END
		--	END                      
		--	IF(@tiBoxMsgInTypeID NOT IN (1))
		--	BEGIN
		--		SET @t1=null
		--		SET	@t2=null
		--		SET	@t3=null
		--		SET @t4=null
		--	END
		--END 
		--Temp4
		--IF(@intBoxID IN (0) AND @Temp4 =1)			--No boxid is configured currently 27-Oct-15                                                        
		--BEGIN                      
		--	IF CHARINDEX('Temperature Sensor-4 Value',@vcAlarmTemp, 1) <> 0                      
		--	BEGIN
		--		SET @vcAlarmTemp = SUBSTRING(@vcAlarmDesc, CHARINDEX('Temperature Sensor-4 Value',@vcAlarmDesc),                       
		--		(LEN(@vcAlarmDesc) - CHARINDEX('Temperature Sensor-4 Value',@vcAlarmDesc)))                                                
		--		IF SUBSTRING(@vcAlarmTemp, CHARINDEX('Temperature Sensor-4 Value',@vcAlarmTemp)+27, 12) = 'Disconnected'                      
		--		BEGIN                                                  
		--			SET @t4 = 'PD'                                                  
		--		END                      
		--		ELSE                      
		--		BEGIN                                                  
		--			SET @t4 = SUBSTRING(@vcAlarmTemp, CHARINDEX('Temperature Sensor-4 Value',@vcAlarmTemp)+27,          
		--			(CHARINDEX(' degree Celsius',@vcAlarmTemp) - CHARINDEX('Temperature Sensor-4 Value',@vcAlarmTemp))-27)                                                     
		--		END   
		--	END                      
		--END                         
		IF (@t1 LIKE '%-126%')     
			SET @t1='PD'                      
		IF (@t2 LIKE '%-126%')                      
			SET @t2='PD' 
		IF (@t3 LIKE '%-126%')                      
			SET @t1='PD'                      
		IF (@t4 LIKE '%-126%')                      
			SET @t2='PD'    
		-- Append Temperature Sensor 1 & 2 and Fuel values along with the message if present                      
		SET @vcAlarmDetail = @vcAlarmDetail +
			(CASE	WHEN (@t1 IS NOT NULL AND @t2 IS NOT NULL AND @t3 IS NOT NULL AND @t4 IS NOT NULL) THEN ' (T1: ' + @t1 + '°C, T2: ' + @t2 + '°C, T3: ' + @t3 + '°C, T4: ' + @t4 + '°C)'
					WHEN (@t1 IS NOT NULL AND @t2 IS NOT NULL AND @t3 IS NOT NULL ) THEN ' (T1: ' + @t1 + '°C, T2: ' + @t2 + '°C, T3: ' + @t3 + '°C)'                       
					WHEN (@t1 IS NOT NULL AND @t2 IS NOT NULL) THEN ' (T1: ' + @t1 + '°C, T2: ' + @t2 + '°C)'                       
					WHEN (@t1 IS NOT NULL) THEN ' (T1: ' + @t1 + '°C)'                      
					WHEN (@t2 IS NOT NULL) THEN ' (T2: ' + @t2 + '°C)'   
					WHEN (@t3 IS NOT NULL) THEN ' (T3: ' + @t3 + '°C)'                      
					WHEN (@t4 IS NOT NULL) THEN ' (T4: ' + @t4 + '°C)'   ELSE '' END)                      
		SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, 'PD°C', 'PD')                                        
   END        
                             
  --IF EXISTS(SELECT va.BoxId FROM rvlfVehicleAssignment va                          
  --     INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId                          
  --     WHERE va.BoxId = @intBoxID AND (v.OrganizationId IN (47, 6) OR @intBoxID = 35) AND @intBoxID <> 999222)                          
  --BEGIN                          
  -- -- Check for Fuel                          
  -- IF CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0 AND CHARINDEX('Ignition',@vcAlarmDetail, 1) = 0                          
  -- BEGIN                          
                             
  --  SET @vcAlarmTemp = SUBSTRING(@vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc), (LEN(@vcAlarmDesc) - CHARINDEX('Fuel%=',@vcAlarmDesc)) + 1)                          
  --  SET @vcAlarmTemp = CASE WHEN CHARINDEX(';',@vcAlarmTemp) <> 0 THEN @vcAlarmTemp ELSE @vcAlarmTemp + ';' END                          
  --  SET @fuel = SUBSTRING(@vcAlarmTemp, CHARINDEX('Fuel%=',@vcAlarmTemp) + 6, (CHARINDEX(';', @vcAlarmTemp) - CHARINDEX('Fuel%=',@vcAlarmTemp)) - 6)                          
                              
  -- END                          
                             
  -- IF (@fuel IS NOT NULL and @tiBoxMsgInTypeID not in (42,130,131,134,135,136,145,152,182,183,184,185))         
  -- BEGIN                          
                              
		----DECLARE @fuelInLit AS Varchar(20)                          
		------Get fuel tank capacity to calcuate fuel percentage                          
		----SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = ISNULL(CapacityUnits,'gals') FROM rvlfVehicle v INNER JOIN                          
		----  rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID                          
		----SET @fuelInLit = (CASE WHEN (@fuel = 'Transition' OR @fuel = '0') THEN '0 lit.'                           
		----      ELSE CAST(ROUND(CAST(((@fuel / 100.00) * @tankCapacity) AS DECIMAL), 0, 0) AS Varchar(10)) + ' lit.' END)                          
		----      --ELSE CAST(ROUND(CAST(((@fuel / 100.00) * (CASE WHEN @intBoxID IN (189, 35, 190, 999982) THEN 225 ELSE 57 END)) AS DECIMAL), 0, 0) AS Varchar(10)) + ' lit.' END)                          
                         
		----SET @vcAlarmDetail = (CASE WHEN CHARINDEX(')',@vcAlarmDetail, 1) <> 0                           
		----        THEN REPLACE(@vcAlarmDetail, ')', (', ' + (CASE WHEN @fuel = 'Transition' THEN 'Fuel Transition' ELSE                          
		----                ('Fuel: ' + @fuel + '% - ' + @fuelInLit) END) + ')'))                          
		----        ELSE @vcAlarmDetail + ' (' + (CASE WHEN @fuel = 'Transition' THEN 'Fuel Transition' ELSE                          
		----                ('Fuel: ' + @fuel + '% - ' + @fuelInLit) END) + ')' END) 
		
		--SET @vcAlarmDetail = (CASE	WHEN CHARINDEX(')',@vcAlarmDetail, 1) <> 0 
		--						THEN REPLACE(@vcAlarmDetail, ')', (', ' + (CASE WHEN @fuel = 'Transition' THEN 'Fuel Transition' 
		--																		WHEN @fuel = 'FuelProbe' THEN 'Fuel Probe Disconnected/Not-installed' 
		--																		WHEN @fuel = 'FuelModule' THEN 'Fuel Module Disconnected' 																					
		--																		ELSE ('Fuel: ' + @fuel + '%') END) + ')'))
		--						ELSE @vcAlarmDetail + ' (' + (CASE  WHEN @fuel = 'Transition' THEN 'Fuel Transition' 
		--															WHEN @fuel = 'FuelProbe' THEN 'Fuel Probe Disconnected/Not-installed' 
		--															WHEN @fuel = 'FuelModule' THEN 'Fuel Module Disconnected' 
		--															ELSE ('Fuel: ' + @fuel + '%') END) + ')' END)                         
                             
  --    END                          
  --END                          
 END                          
                           
 -- Return the result of the function                          
 RETURN @vcAlarmDetail                          
END 



GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetAlarmDetails_Optimzd]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetAlarmDetails_Optimzd] 
(                          
 @vcAlarmDesc varchar(1000),                          
 @tiBoxMsgInTypeID tinyint,                          
 @intBoxID varchar(15) = null,                          
 @uiMessageInId uniqueidentifier = null,                          
 @dtOriginDateTime DateTime = null,                          
 @Lang nvarchar(20) = null                            
)                          
RETURNS nvarchar(MAX)                          
AS                          
BEGIN                          
 DECLARE @vcAlarmDetail nvarchar(MAX)                              
 DECLARE @tiSensorID tinyint                              
 DECLARE @SecondsToConvert bigint                              
 DECLARE @vcBoxMsgInTypeName  nvarchar(100)                              
 DECLARE @tankCapacity int                               
 DECLARE @FuelLevelPercentage int                              
 DECLARE @vcFuelUnits varchar(10)                           
 DECLARE @GeozoneName varchar(150)
 DECLARE @bigOrganizationID bigint
 -------------------------------------------------------------------------------------------------------------------------------------- 
 --Get BoxMsg desc
 SELECT @vcBoxMsgInTypeName = Case when @Lang = 'LanguageArNew' Then isnull(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi' 
 THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc)  else BoxMsgInTypeDesc  END FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID

Select @vcBoxMsgInTypeName = replace(@vcBoxMsgInTypeName,'Speed with Duration','Speed Violated for')

        
----Get Geozone Name     
--if @vcAlarmDesc like '%GeozoneId:%'
--begin
--select @GeozoneName=ISNULL(GeozoneName,'Deleted') FROM rvlfOrganizationGeozone OG inner join rvlfboxid B on OG.Organizationid=B.Organizationid
--where OG.geozoneid=dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'GeozoneId:',';') and  b.BoxId = @intBoxID
--end
--if @vcAlarmDesc like '%GeozoneId=%'
--begin
--select @GeozoneName=ISNULL(GeozoneName,'Deleted') FROM rvlfOrganizationGeozone OG inner join rvlfboxid B on OG.Organizationid=B.Organizationid
--where OG.geozoneid=dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'GeozoneId=',';') and  b.BoxId = @intBoxID
--end
--Get Organization id
 SELECT @bigOrganizationID = b.OrganizationId  FROM rvlfBoxId b where b.BoxId = @intBoxID
 -------------------------------------------------------------------------------------------------------------------------------------- 
 IF @tiBoxMsgInTypeID in(11,2,3)                          
 BEGIN                          
  DECLARE @vcActionOn nvarchar(25)                              
  DECLARE @vcActionOff nvarchar(25)                           
                              
  SET @tiSensorID = 0                             
  IF @tiSensorID = 31                                                     
    SET @vcAlarmDetail = 'Alarm - Tamper'    
  ELSE IF @tiSensorID = 27                          
   BEGIN                          
    SET @vcAlarmDetail = 'Alarm - Fuel drain'                                                        
    SELECT @vcAlarmDetail = @vcAlarmDetail + ' ' +                           
     CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0                          
     THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,LEN(@vcAlarmDesc)), ';', '%') ELSE '' END                           
   END                          
  ELSE IF NOT EXISTS (SELECT SensorName FROM rvlfBoxSensorsCfg WHERE SensorId = @tiSensorId and BoxID = @intBoxID)                          
   SET @vcAlarmDetail = 'Unknown sensor'   
  ELSE                           
   BEGIN                          
    SELECT @vcAlarmDetail = ISNULL(Case when @Lang = 'LanguageArNew' Then SN.SensorName_Ar WHEN  @Lang='LanguageHindi' 
	THEN SN.SensorName_Hin else  SC.SensorName  end , 'Unknown sensor'),             
    @vcActionOn = Case when @Lang = 'LanguageArNew' Then ISNULL(SN.ActionOn_Ar,'') WHEN  @Lang='LanguageHindi' THEN ISNULL(SN.ActionOn_Hin,'') 
	 ELSE isnull(SC.ActionOn,'') END,
    @vcActionOff = Case when @Lang = 'LanguageArNew' Then ISNULL(SN.ActionOff_Ar,'')
	 WHEN  @Lang='LanguageHindi' THEN ISNULL(SN.ActionOff_Hin,'') else isnull(SC.ActionOff,'') END                              
    FROM rvlfBoxSensorsCfg SC                            
    INNER JOIN rvlfsensor SN on SN.sensorID = SC.SensorID                            
    WHERE SC.SensorId = @tiSensorId and BoxID = @intBoxID                           
   -- SET @vcAlarmDetail = @vcAlarmDetail                           
    DECLARE @intSensorStateStart int                 
    SET @intSensorStateStart = CHARINDEX('SENSOR_STATUS=', @vcAlarmDesc) + 14                          
    SET @vcAlarmDetail = @vcAlarmDetail + ' '+                           
     CASE WHEN (SUBSTRING(@vcAlarmDesc, @intSensorStateStart, 2)) = 'ON' THEN          
      @vcActionOn                          
     ELSE                            
      @vcActionOff                           
     END                           
    IF RIGHT(@vcAlarmDetail,1) = ';'                          
    BEGIN                          
     SET @vcAlarmDetail = SUBSTRING(@vcAlarmDetail,1,LEN(@vcAlarmDetail)-1)                          
    END                                
                              
    SET @vcAlarmDetail = @vcAlarmDetail+CASE WHEN @tiBoxMsgInTypeID= 13 THEN ' - Bad Sensor' ELSE '' END 	                          
    If EXISTS(select BoxId from rvlfBoxId where BoxId IN (@intBoxID) AND @dtOriginDateTime >= '04/27/2012' AND (organizationid =139 OR organizationid = 23))           BEGIN                          
    SET @SecondsToConvert =                           
    (CASE WHEN @vcAlarmDesc  like '%SENSOR_NUM=2;%' and @vcAlarmDesc LIKE '%SENSOR_DURATION=%' THEN                          
 	isnull(dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'SENSOR_DURATION=',';'),'0')
	END)                          
    SET @vcAlarmDetail = @vcAlarmDetail + ' ' +                          
    CASE WHEN @SecondsToConvert = 0                          
    THEN '' ELSE  CASE WHEN @vcAlarmDesc LIKE '%SENSOR_NUM=2;%' and @vcAlarmDesc LIKE '%SENSOR_DURATION=%' THEN '(Durations: ' + dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert * 60) +')'  ELSE '' END END                          
    END 
	ELSE 
	BEGIN
		 SET @SecondsToConvert =  (CASE WHEN @tiBoxMsgInTypeID = 3 and @vcAlarmDesc LIKE '%SENSOR_DURATION=%' THEN                          
		 isnull(dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'SENSOR_DURATION=',';'),'0')
		  END)                          
		 SET @vcAlarmDetail = @vcAlarmDetail + ' ' + CASE WHEN ISNULL(@SecondsToConvert,0) = 0                          
		 THEN '' ELSE '(Durations: ' + dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert * 60) +')' END
	END                         
  END                          
 END
 ---------------------------------------------------------------------------------------------------------------------------------                         
 --ELSE IF @tiBoxMsgInTypeID = 4  and @vcAlarmDesc LIKE '%IsAlarm=1;AlarmMsg=%'                       
 --BEGIN    
 -- SET @vcAlarmDetail ='Alarm : '+ dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'AlarmMsg=',';')
 -- END
     
 -------------------------------------------------------------------------------------------------------------------------------                         
 ELSE IF @tiBoxMsgInTypeID = 9                           
 BEGIN                          
  SET @SecondsToConvert = CAST(SUBSTRING (@vcAlarmDesc, CHARINDEX(':',@vcAlarmDesc,1)+1,                          
  CHARINDEX(';',@vcAlarmDesc)-1 -CHARINDEX(':',@vcAlarmDesc,1)) AS bigint)                          
  SET @vcAlarmDetail = @vcBoxMsgInTypeName + ' '+ CASE WHEN @SecondsToConvert = 0                       
  THEN Case when @Lang = 'LanguageArNew' Then N'(/#' WHEN @Lang='LanguageHindi' THEN N'6	A	0	B	' else 'started' END ELSE Case                   
  when @Lang = 'LanguageArNew' Then N'%F*GI ' WHEN @Lang='LanguageHindi' THEN N'		$	' else 'end ' end + dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert) END       
 END 
 -------------------------------------------------------------------------------------------------------------------------------------                 
 ELSE IF @tiBoxMsgInTypeID = 15                           
 BEGIN              
 SET @vcAlarmDetail=  @vcAlarmDesc          
 end
 -------------------------------------------------------------------------------------------------------------------------------------                 
 -------------------------------------------------------------------------------------------------------------------------------------                 
 ELSE IF @tiBoxMsgInTypeID = 19                          
  BEGIN                          
   DECLARE @intIPReason int                           
   SET @intIPReason  = CAST(SUBSTRING(@vcAlarmDesc, CHARINDEX('=',@vcAlarmDesc,1)+1,CHARINDEX(';',@vcAlarmDesc,1)-(CHARINDEX('=',@vcAlarmDesc,1)+1) ) as int)                           
   SET @vcAlarmDetail = 'IP Update - '+                          
    CASE WHEN @intIPReason = 1 THEN 'Power Up' WHEN @intIPReason = 2 THEN 'Failed'                          
      WHEN @intIPReason = 3 THEN 'Sleep' WHEN @intIPReason = 4 THEN 'Attach ERROR'                          
      WHEN @intIPReason = 5 THEN 'PPP TERMINATE' WHEN @intIPReason = 6 THEN 'Long PPP Negotiation'                           
      WHEN @intIPReason = 7 THEN 'PPP Negotiated To' WHEN @intIPReason = 8 THEN 'No Diag'                           
      WHEN @intIPReason = 9 THEN 'Force Reset' WHEN @intIPReason = 10 THEN 'Std Msg Failed'                           
      WHEN @intIPReason = 11 THEN 'Mdm Reset Fail' WHEN @intIPReason = 12 THEN 'Wake Up'                           
      WHEN @intIPReason = 13 THEN 'Register To' WHEN @intIPReason = 14 THEN 'Attach To'                           
      WHEN @intIPReason = 15 THEN 'AT failed' WHEN @intIPReason = 16 THEN 'Dial To'                           
      WHEN @intIPReason = 17 THEN 'Dial failed' WHEN @intIPReason = 18 THEN 'Errors > 10'                           
      WHEN @intIPReason = 19 THEN 'Can''t attached'                          
      ELSE 'Unknown' END    
	  END  

   ----------------------------------------------------------------------------------------------------------------------------   
 ELSE IF @tiBoxMsgInTypeID = 23 -- Battery Status messages                          
  BEGIN                          
   DECLARE @tintBatteyId tinyint=null                          
   DECLARE @vcBatteryName varchar(50)=null                          
   SET @tintBatteyId = CASE WHEN @vcAlarmDesc LIKE '%Battery Name=%' THEN 
   CAST(dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'Battery Name=',';') AS TINYINT) ELSE 0 END                          
                      
		SET @vcBatteryName= case when @tintBatteyId=1 then 	'Main Battery Disconnected' 
		when @tintBatteyId=2 then 'Main Battery Connected'		         
		when @tintBatteyId=3 then 'Backup Battery Disconnected'
		when @tintBatteyId=4 then 'Backup Battery Connected'
		when @tintBatteyId=5 then 'Backup Battery Empty' 
		else 'Battery Status' end                     
                             
    SET @vcAlarmDetail=@vcBatteryName                          
  END      
                     
 -------------------------------------------------------------------------------------------------------------------------------------                       
 ELSE IF @tiBoxMsgInTypeID = 41                          
   BEGIN          
   SET @vcAlarmDetail = @vcBoxMsgInTypeName                         
   END   
 -------------------------------------------------------------------------------------------------------------------------------------                       
 ELSE IF @tiBoxMsgInTypeID = 73                          
   BEGIN                                                      
    DECLARE @vcCustomProperty VARCHAR(1000) = @vcAlarmDesc                                                        
    DECLARE @vcGenParams varchar(max)                          
    DECLARE @RI AS VARCHAR(8)  
    DECLARE @ReportingInterval AS VARCHAR(35)                          
	SET @vcCustomProperty = REPLACE(@vcCustomProperty, '$$', ':')
    SET @RI = SUBSTRING (@vcCustomProperty, CHARINDEX('=',@vcCustomProperty,1)+1,                          
        CHARINDEX(';',@vcCustomProperty)-1 -CHARINDEX('=',@vcCustomProperty,1))                    
    SET @ReportingInterval = CASE WHEN @RI = '00:00:30' THEN 'Reporting Interval=30sec'                          
     WHEN @RI = '00:01:00' THEN 'Reporting Interval=1min'                          
     WHEN @RI = '00:02:00' THEN 'Reporting Interval=2min'                          
     WHEN @RI = '00:05:00' THEN 'Reporting Interval=5min'                          
     WHEN @RI = '00:10:00' THEN 'Reporting Interval=10min'                          
     WHEN @RI = '00:15:00' THEN 'Reporting Interval=15min'                          
     WHEN @RI = '00:30:00' THEN 'Reporting Interval=30min'                          
     WHEN @RI = '01:00:00' THEN 'Reporting Interval=1hr'                           
     WHEN @RI = '02:00:00' THEN 'Reporting Interval=2hrs' ELSE '' END                           
                          
    SELECT @vcGenParams = ISNULL(@vcGenParams + ';', '') +                           
      CASE WHEN CHARINDEX('Gen Param No',FieldValue) <> 0 THEN                  
      REPLACE(REPLACE(REPLACE(FieldValue, 'Gen Param No='+dbo.rvlf_fn_GetParamValueWithIndex(FieldValue,'Gen Param No',';')+'',                           
      dbo.rvlf_fn_GetGeneratorParameterName(dbo.rvlf_fn_GetParamValueWithIndex(FieldValue,'Gen Param No',';'))), 'Gen Param Val',''),   
      'Reporting Interval='+@RI+';','') ELSE '' END                          
    FROM [dbo].[rvlf_fn_ConvertArrayToTable] (@vcCustomProperty, '|')                        
                          
    SET @vcAlarmDetail = @ReportingInterval + ';' + @vcGenParams                           
   END     
 ----------------------------------------------------------------------------------------------------------------------------                        
 ELSE IF @tiBoxMsgInTypeID = 74                          
  BEGIN                              
  -- SET @vcAlarmDetail = @vcAlarmDesc   
   SET @vcAlarmDetail = REPLACE(REPLACE(REPLACE(@vcAlarmDesc, 'ExSensorNo=0', 'Sensor=Temperature Sensor-1'), 'ExSensorNo=1', 'Sensor=Fuel Guage Sensor'), 'ExSensorNo=2', 'Sensor=Temperature Sensor-2')                          
   SET @vcAlarmDetail = REPLACE(REPLACE(@vcAlarmDetail, ' degree Celsius' ,'°C'), '|', ';')                          
  END        
  ----------------------------------------------------------------------------------------------------------------------------                           
 ELSE IF @tiBoxMsgInTypeID = 78 -- External Sensor Status                          
  BEGIN                         
   SET @vcAlarmDetail = REPLACE(SUBSTRING(@vcAlarmDesc, CHARINDEX('ExSensorNo',@vcAlarmDesc) + 13,                           
      (LEN(@vcAlarmDesc) - CHARINDEX('ExSensorNo',@vcAlarmDesc))), ';', '')                          
   SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, ' degree Celsius' ,'°C')           
      SET @vcAlarmDetail = REPLACE(@vcAlarmDetail, ' mV' ,'lit.')                           
  END                            
 ----------------------------------------------------------------------------------------------------------------------------   
 -- ELSE IF @tiBoxMsgInTypeID = 98 -- MTD User Login Status to Server    
 --BEGIN 
 -- DECLARE @MDTUsrId AS Varchar(50) = SUBSTRING(@vcAlarmDesc, CHARINDEX('User ID=',@vcAlarmDesc) + 8,                           
 --          (CHARINDEX(';;',@vcAlarmDesc) - CHARINDEX('User ID=',@vcAlarmDesc) - 8))                                      
 -- IF EXISTS (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUsrId AND UserId IN (SELECT UserId FROM rvlfMDTBoxMessageTable 
 -- WHERE BoxId = @intBoxID))      
 -- BEGIN                                 
 --  SET @MDTUsrId = (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUsrId AND UserId IN (SELECT UserId FROM rvlfMDTBoxMessageTable 
 --  WHERE BoxId = @intBoxID))                             
 -- END                          
 -- SET @vcAlarmDetail = @MDTUsrId + ' logged ' + SUBSTRING(@vcAlarmDesc, CHARINDEX('Login Status=',@vcAlarmDesc) + 13,                           
 --          (CHARINDEX(';',@vcAlarmDesc) - CHARINDEX('Login Status=',@vcAlarmDesc) - 13))                       
 --END                       
   --------------------------------------------------------------------------------------------------------------------------
 ELSE IF @tiBoxMsgInTypeID=114 AND CharIndex('13;Battery',@vcAlarmDesc) <> 0  --17-aug 13;Battery Low:18; Battery Ok:22                          
 BEGIN                          
  SELECT @vcAlarmDetail = REPLACE(@vcAlarmDesc,'13;Battery','Battery')                            
 END 
 ELSE IF  @tiBoxMsgInTypeID=114 AND CharIndex('06;No of DTC',@vcAlarmDesc) <> 0                
 BEGIN                          
  SET @vcAlarmDetail= CASE WHEN CAST(SUBSTRING(@vcAlarmDesc,20,1) AS INT)=0 THEN 'No DTC Codes' ELSE 'DTC Codes' END                          
 END  
 ELSE IF  @tiBoxMsgInTypeID=114 AND @vcAlarmDesc like '%PacketType:%'  -- Ranjith Send Camera Header packet Type                      
 Begin                      
  Declare @VcPacketType bigint = dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'PacketType:',';')                      
  SET @vcAlarmDetail = (                      
  Case When @VcPacketType = 1 then  ' (Ignition ON)'  When @VcPacketType = 2 then ' (Ignition OFF)'                      
  When @VcPacketType = 3 then  ' (Door Close)'  When @VcPacketType = 4 then ' (Trunk Open)'                      
  When @VcPacketType = 5 then ' (Panic)' When @VcPacketType = 6 then ' (Speed Alert)'                      
  When @VcPacketType = 7 then ' (Idling)' When @VcPacketType = 8 then ' (Ext.Idling)'           
  When @VcPacketType = 9 then ' (Harsh/Extreme Braking)' When @VcPacketType = 10 then ' (Geofence)'                      
  When @VcPacketType = 11 then ' (Geozone IN)' When @VcPacketType = 12 then ' (GPS ANT Open)'                      
  When @VcPacketType = 13 then ' (Igntion ON - Periodic Click)' When @VcPacketType = 14 then ' (Igntion OFF - Periodic Click)'                      
  When @VcPacketType = 15 then ' (RFID)'                      
  else ' (N/A)'                      
  end)                            
 END
 ----------------------------------------------------------------------------------------------------------------------------           
   ELSE  IF  @tiBoxMsgInTypeID=109 OR @tiBoxMsgInTypeID=110 OR @tiBoxMsgInTypeID=125 OR @tiBoxMsgInTypeID=126                          
  BEGIN                          
    SET @vcAlarmDetail = REPLACE(@vcAlarmDetail,'Non Alarm-','')                          
  END  
  ----------------------------------------------------------------------------------------------------------------------------                        
 ELSE IF @tiBoxMsgInTypeID = 121                          
 BEGIN                          
  Declare @errCode int = CAST(dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'Error Code=',';') AS int)                          
  SET @vcAlarmDetail = CASE WHEN @errCode = 1 THEN 'Get Device ID From LPC'                          
       WHEN @errCode = 2 THEN 'Get Destination IP From LPC'                          
 WHEN @errCode = 3 THEN 'Get Destination Port From LPC'                          
       WHEN @errCode = 4 THEN 'Get  Reporting interval From LPC'                          
       WHEN @errCode = 5 THEN 'Get Speed threshold From LPC'                          
       WHEN @errCode = 6 THEN 'Get  leash From LPC'                          
       WHEN @errCode = 7 THEN 'Get APN From LPC'                        
       WHEN @errCode = 8 THEN 'Device Reset'                          
       WHEN @errCode = 9 THEN 'Device will Reset due to IP Update fail'   	                          	
	 WHEN @errCode = 10 THEN 'Device will Reset due to no response from last one day'                      
       WHEN @errCode = 11 THEN 'Device Reset (WDT)'                      
       WHEN @errCode = 12 THEN 'Device Reset (BOD)'   
       WHEN @errCode = 13 THEN 'Device Reset (MODEM)'   
       ELSE 'Device Messages'                          
     END                          
 END   
 ELSE 
 BEGIN          
   SET @vcAlarmDetail = @vcBoxMsgInTypeName                         
 END                           
 -- Return the result of the function                          
 RETURN @vcAlarmDetail        
END 


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetAlarmDetailsForTrips]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetAlarmDetailsForTrips]  
(  
 @vcAlarmDesc varchar(250),  
 @tiBoxMsgInTypeID tinyint,  
 @intBoxID int = null,  
 @uiMessageInId uniqueidentifier = null,  
 @dtOriginDateTime DateTime = null,  
 @bitCanShowFuelLevel bit = null  
)  
RETURNS varchar(MAX)  
AS  
BEGIN  
 DECLARE @vcAlarmDetail varchar(MAX)  
 DECLARE @tiSensorID tinyint  
 DECLARE @SecondsToConvert int  
 DECLARE @vcMoxMsgInTypeName varchar(100)  
 DECLARE @tankCapacity int   
 DECLARE @FuelLevelPercentage int  
 DECLARE @vcFuelUnits varchar(10)  
   
 SELECT @vcMoxMsgInTypeName = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID  
    
 IF @tiBoxMsgInTypeID = 11 OR @tiBoxMsgInTypeID = 2 OR @tiBoxMsgInTypeID = 3  
  OR @tiBoxMsgInTypeID= 13  
 BEGIN  
  DECLARE @vcActionOn varchar(15)  
  DECLARE @vcActionOff varchar(15)  
      
  SET @tiSensorID = CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('=',@vcAlarmDesc)+1,  
  CHARINDEX(';',@vcAlarmDesc,1)-CHARINDEX('=',@vcAlarmDesc)-1  
  ) As tinyint)  
    
  IF @tiSensorID = 31   
   BEGIN  
    SET @vcAlarmDetail = 'Alarm - Tamper'  
   END  
  ELSE IF @tiSensorID = 27  
   BEGIN  
    SET @vcAlarmDetail = 'Alarm - Fuel drain'  
      
    SELECT @vcAlarmDetail = @vcAlarmDetail + ' ' +   
     CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0  
     THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,  
     LEN(@vcAlarmDesc)), ';', '%') ELSE '' END   
   END  
  ELSE IF NOT  EXISTS (SELECT SensorName FROM rvlfBoxSensorsCfg WHERE SensorId = @tiSensorId and BoxID = @intBoxID)  
   BEGIN  
    SET @vcAlarmDetail = 'Unknown sensor'  
   END  
  ELSE   
   BEGIN  
    SELECT @vcAlarmDetail = ISNULL(SensorName, 'Unknown sensor') ,   
     @vcActionOn = ISNULL(ActionOn,''), @vcActionOff = ISNULL(ActionOff,'')  
     FROM rvlfBoxSensorsCfg WHERE SensorId = @tiSensorId and BoxID = @intBoxID  
    SET @vcAlarmDetail = @vcAlarmDetail   
    DECLARE @intSensorStateStart int   
  
    SET @intSensorStateStart = CHARINDEX('=',@vcAlarmDesc,LEN('SENSOR_NUM=')+1)  
    DECLARE @intSensorStateEnd int   
    SET @intSensorStateEnd = CHARINDEX(';',@vcAlarmDesc,15)  
    SET @vcAlarmDetail = @vcAlarmDetail + ' '+   
     CASE WHEN (SUBSTRING(@vcAlarmDesc,@intSensorStateStart+1, @intSensorStateEnd - @intSensorStateStart-1)) = 'ON' THEN   
      @vcActionOn  
     ELSE    
      @vcActionOff   
     END  
    IF RIGHT(@vcAlarmDetail,1) = ';'  
    BEGIN  
     SET @vcAlarmDetail = SUBSTRING(@vcAlarmDetail,1,LEN(@vcAlarmDetail)-1)  
    END  
    SET @vcAlarmDetail = @vcAlarmDetail+CASE WHEN @tiBoxMsgInTypeID= 13 THEN ' - Bad Sensor' ELSE '' END  
  END  
 END  
 ELSE IF @tiBoxMsgInTypeID = 9   
 BEGIN  
  SET @SecondsToConvert = CAST(SUBSTRING (@vcAlarmDesc, CHARINDEX(':',@vcAlarmDesc,1)+1,  
   CHARINDEX(';',@vcAlarmDesc)-1 -CHARINDEX(':',@vcAlarmDesc,1)) AS int)  
  SET @vcAlarmDetail = @vcMoxMsgInTypeName + ' '+ CASE WHEN @SecondsToConvert = 0  
  THEN 'started' ELSE 'end ' + dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert) END  
 END  
 ELSE IF @tiBoxMsgInTypeID = 14 OR @tiBoxMsgInTypeID = 15 OR   
  @tiBoxMsgInTypeID = 16 OR @tiBoxMsgInTypeID = 17 OR @tiBoxMsgInTypeID = 24  
 BEGIN  
  SET @SecondsToConvert = CAST(SUBSTRING (@vcAlarmDesc, CHARINDEX(':',@vcAlarmDesc,1)+1,  
   CHARINDEX(';',@vcAlarmDesc)-1 -CHARINDEX(':',@vcAlarmDesc,1)) AS int)  
  SET @vcAlarmDetail = @vcMoxMsgInTypeName + ' '+   
   dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert)  
 END  
  
 ELSE IF @tiBoxMsgInTypeID = 5 OR @tiBoxMsgInTypeID = 6  
 BEGIN  
  IF @uiMessageInId IS NOT NULL  
   BEGIN  
    SELECT @vcAlarmDetail = g.GeozoneName FROM rvlfOrganizationGeozone g INNER JOIN rvlfVehicle v   
     ON g.OrganizationId=v.OrganizationId INNER JOIN rvlfVehicleAssignment va ON   
     v.VehicleId = va.VehicleId   
     INNER JOIN rvlfVehicleGeozone vg ON vg.VehicleID = v.VehicleID AND   
        vg.GeozoneNo = g.GeozoneNo  
     WHERE BoxId = @intBoxID and GeozoneId = --CAST(@vcAlarmDesc as bigint)  
     (CAST( SUBSTRING(@vcAlarmDesc,  
      CHARINDEX('=',@vcAlarmDesc,1)+1,(CHARINDEX(';',@vcAlarmDesc,1)  
      - CHARINDEX('=',@vcAlarmDesc,1))-1) as bigint))  
    SET @vcAlarmDetail = ISNULL(@vcAlarmDetail,'Geozone Deleted') + ' '+   
     CASE WHEN @tiBoxMsgInTypeID = 5 THEN ' - In' ELSE ' - Out' END  
   END  
  ELSE  
   BEGIN  
    SELECT @vcAlarmDetail = g.GeozoneName FROM rvlfOrganizationGeozone g INNER JOIN rvlfVehicle v   
     ON g.OrganizationId=v.OrganizationId INNER JOIN rvlfVehicleAssignment va ON   
      v.VehicleID = va.VehicleID  
      INNER JOIN rvlfVehicleGeozone vg ON vg.VehicleID = v.VehicleID AND   
        vg.GeozoneNo = g.GeozoneNo  
     WHERE BoxId = @intBoxID and GeozoneId = --CAST(@vcAlarmDesc as bigint)  
     (CAST( @vcAlarmDesc as bigint))   
    SET @vcAlarmDetail = ISNULL(@vcAlarmDetail,'Geozone Deleted') + ' '+   
     CASE WHEN @tiBoxMsgInTypeID = 5 THEN ' - In' ELSE ' - Out' END  
   END  
 END  
 ELSE IF @tiBoxMsgInTypeID = 28  
 BEGIN  
  DECLARE @bigOrganizationID bigint  
  SELECT @bigOrganizationID = v.OrganizationId  FROM rvlfVehicle v  
   INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId and va.BoxId = @intBoxID  
  SET @vcAlarmDetail = (SELECT g.GeozoneName from rvlfOrganizationGeozone g WHERE g.GeozoneId IN   
   (select * from dbo.rvlf_fn_ConvertArrayToTable(@vcAlarmDesc,','))  
   AND g.OrganizationID = @bigOrganizationID FOR XML AUTO)  
  IF @vcAlarmDetail IS NULL  
   BEGIN  
    SET @vcAlarmDetail = ''  
   END  
  ELSE  
   BEGIN  
    SET @vcAlarmDetail = '<GeozoneList>'+@vcAlarmdetail+'</GeozoneList>'  
   END  
 END  
 ELSE IF @tiBoxMsgInTypeID = 19  
  BEGIN  
   DECLARE @intIPReason int   
   SET @intIPReason  = CAST(SUBSTRING(@vcAlarmDesc, CHARINDEX('=',@vcAlarmDesc,1)+1,CHARINDEX(';',@vcAlarmDesc,1)-(CHARINDEX('=',@vcAlarmDesc,1)+1) ) as int)   
   SET @vcAlarmDetail = 'IP Update - '+  
    CASE WHEN @intIPReason = 1 THEN 'Power Up' WHEN @intIPReason = 2 THEN 'Failed'  
      WHEN @intIPReason = 3 THEN 'Sleep' WHEN @intIPReason = 4 THEN 'Attach ERROR'  
      WHEN @intIPReason = 5 THEN 'PPP TERMINATE' WHEN @intIPReason = 6 THEN 'Long PPP Negotiation'   
      WHEN @intIPReason = 7 THEN 'PPP Negotiated To' WHEN @intIPReason = 8 THEN 'No Diag'   
      WHEN @intIPReason = 9 THEN 'Force Reset' WHEN @intIPReason = 10 THEN 'Std Msg Failed'   
      WHEN @intIPReason = 11 THEN 'Mdm Reset Fail' WHEN @intIPReason = 12 THEN 'Wake Up'   
      WHEN @intIPReason = 13 THEN 'Register To' WHEN @intIPReason = 14 THEN 'Attach To'   
      WHEN @intIPReason = 15 THEN 'AT failed' WHEN @intIPReason = 16 THEN 'Dial To'   
      WHEN @intIPReason = 17 THEN 'Dial failed' WHEN @intIPReason = 18 THEN 'Errors > 10'   
      WHEN @intIPReason = 19 THEN 'Can''t attached'  
      ELSE 'Unknown' END  
  END  
 ELSE IF @tiBoxMsgInTypeID = 42  
   BEGIN  
		SET @FuelLevelPercentage = CAST(dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'Fuel%=',';') as int)                          
		SET @FuelLevelPercentage = CASE WHEN @FuelLevelPercentage <=0 THEN 0 ELSE @FuelLevelPercentage END                          
		SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = CASE CapacityUnits WHEN 1 THEN 'litres' WHEN 2 THEN 'gals' ELSE 'litres' END
		FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID                                                       
		--SELECT @vcAlarmDetail = Case when @Lang = 'LanguageArNew' Then isnull(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi' THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc) else BoxMsgInTypeDesc END 
		--FROM rvlfBoxMsgInType  WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID                           
		SELECT @vcAlarmDetail = @vcMoxMsgInTypeName	+ ' (Actual Fuel Drained - ' +		--+ ' ('+ cast(@FuelLevelPercentage as varchar(3))+ '% - '+  
								cast(cast(((@FuelLevelPercentage / 100.00) * @tankCapacity)as int) as varchar(5)) +' '+ @vcFuelUnits +')'  
   END  
 ELSE IF @tiBoxMsgInTypeID = 41  
   BEGIN  
    SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID  
      
    --SELECT @vcAlarmDetail = @vcAlarmDetail + ' ' +   
    -- CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0  
    -- THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,  
    -- LEN(@vcAlarmDesc)), ';', '%') ELSE '' END   
   END  
 ELSE IF @tiBoxMsgInTypeID IN (37, 38, 39, 42, 45, 46, 47, 48, 49, 50)  
  BEGIN  
   --SET @FuelLevelPercentage =(( CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0  
   --   THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,  
   --   LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int) * 33)-600)/24.1  
    SET @FuelLevelPercentage =CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0  
      THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,  
      LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int)  
   SET @FuelLevelPercentage = CASE WHEN @FuelLevelPercentage <=0 THEN 0 ELSE @FuelLevelPercentage END  
   SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = ISNULL(CapacityUnits,'gals') FROM rvlfVehicle v INNER JOIN  
    rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID  
     
   SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID  
   SELECT @vcAlarmDetail = @vcAlarmDetail   
    + ' ('+ cast(@FuelLevelPercentage as varchar(3))+ '% - '+   
    cast(cast(((@FuelLevelPercentage / 100.00) * @tankCapacity)as int) as varchar(5)) +' '+ @vcFuelUnits +')'  
     --CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0  
     -- THEN ' (' +  REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,  
     -- LEN(@vcAlarmDesc)), ';', '%)') ELSE '' END  
  END  
 --ELSE IF @tiBoxMsgInTypeID = 54  
 -- BEGIN  
 --  --SELECT @vcAlarmDetail = '<table><tr><td>'+ REPLACE(REPLACE(@vcAlarmDesc,'=','<td>:</td><td>'),';','</td></tr><tr><td>' )+'</table>'  
 -- END  
 --ELSE IF @tiBoxMsgInTypeID = 51  
 -- BEGIN  
 --  SET @vcAlarmDetail = 'Speed viol  
 -- END 
 ELSE IF @tiBoxMsgInTypeID = 100 -- RFID Identification                
  BEGIN           
   DECLARE @VCKEYUSERNAME VARCHAR(max)=NULL     
    DECLARE @RFID Varchar(50)=null        
   declare @Punch varchar(100)=null                
     IF(@vcAlarmDesc LIKE '%RF_ID=%')     --6                                           
    BEGIN            
    set @RFID=dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'RF_ID=',';')         
    IF(charindex('InOutEnable',@vcAlarmDesc,1)>0) --5        
    BEGIN        
     declare @InOutEnable varchar(2) =dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'InOutEnable:',';')         
     SELECT @VCKEYUSERNAME=IButtonKeyName FROM rvlfIButtonMapping WHERE IButtonKey=@RFID        
    IF @VCKEYUSERNAME IS NULL OR @VCKEYUSERNAME=''                                
     BEGIN  --2                                               
      SET @vcAlarmDetail= SUBSTRING(@vcAlarmDesc,CHARINDEX('RF_ID=',@vcAlarmDesc,1),LEN(@vcAlarmDesc))        
      set @vcAlarmDetail =left(@vcAlarmDetail,len(@vcAlarmDetail)-1)        
      set @Punch = (select dbo.rvlf_fn_GetParamValueWithIndex (@vcAlarmDesc,'Punch:',';'))              
      set @vcAlarmDetail=@vcAlarmDetail + isnull(case when @Punch='UnauthorizedIN' or  @Punch='UnauthorizedOUT' then ' - Unauthorized' end,'')              
      IF(@InOutEnable ='1' and @InOutEnable is not null) --1                       
      begin           
  SET @vcAlarmDetail = 'RF_ID='+@RFID                  
  + ' - ' + SUBSTRING(@vcAlarmDesc,CHARINDEX('Punch:',            
  @vcAlarmDesc,1)+6, CHARINDEX(';',@vcAlarmDesc, CHARINDEX('Punch:',@vcAlarmDesc,1)) - (CHARINDEX('Punch:',@vcAlarmDesc,1)+6))              
   end    --1                 
    END  --2                                                
    ELSE --3         
     BEGIN                                                      
      SET @vcAlarmDetail='User - '+ @VCKEYUSERNAME +' [RFID]'                                                
      IF(@InOutEnable='0' and @InOutEnable is not null)                        
      BEGIN --4                       
  SET @vcAlarmDetail = 'User - '+ @VCKEYUSERNAME +' [RFID]'+ ' - ' + SUBSTRING(@vcAlarmDesc,CHARINDEX('Punch:',@vcAlarmDesc,1)+6,           
  CHARINDEX(';',@vcAlarmDesc, CHARINDEX('Punch:',@vcAlarmDesc,1)) - (CHARINDEX('Punch:',@vcAlarmDesc,1)+6))                               
   end  --4                     
    END--3        
END  --5                                   
END--6          
Else IF(@vcAlarmDesc LIKE '%Finger%')                                            
  BEGIN                                     
   IF(@vcAlarmDesc LIKE '%Finger Matched;FingerID:%')                                            
   Begin                                            
    Declare @vaFingerID varchar(10)=null                                                
    Declare @VaFingerPrintName varchar(100)=null                                            
    Select  @vaFingerID = (SUBSTRING(@vcAlarmDesc, CHARINDEX('FingerID:',@vcAlarmDesc,0)+9,                                            
       (CHARINDEX(';',@vcAlarmDesc,CHARINDEX('FingerID:',@vcAlarmDesc,1)))                                             
       -(CHARINDEX('FingerID:',@vcAlarmDesc,1)+9)))           
   Select @VaFingerPrintName = IButtonKeyName from rvlfIButtonMapping 
   where boxid= @intBoxID and IButtonKey = cast(@vaFingerID as int) and keytype =4 
    SET @vcAlarmDetail= 'Finger Matched (' + @VaFingerPrintName + ')' End                                            
   else if(@vcAlarmDesc LIKE '%Finger Not Matched;%') 
   Begin 
    SET @vcAlarmDetail= replace(@vcAlarmDesc,';','') 
   End 
   else 
   Begin 
    SET @vcAlarmDetail= 'Finger Matched' 
   End 
  End 
 END   
 ELSE  
 BEGIN  
    
  SELECT @vcAlarmDetail =BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID  
    
  IF @bitCanShowFuelLevel = 1 AND @tiBoxMsgInTypeID NOT IN (19,20,21,22,35,40,55,54,56,53)  
   BEGIN  
    SET @vcAlarmDetail = @vcAlarmDetail  
    --SET @FuelLevelPercentage =(( CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0  
    --  THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,  
    --  LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int) * 33)-600)/24.1  
    --SET @FuelLevelPercentage =CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0  
    --  THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,  
    --  LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int)  
	SET @FuelLevelPercentage = CAST(dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'Fuel%=',';') as int)                          
    SET @FuelLevelPercentage = CASE WHEN @FuelLevelPercentage <=0 THEN 0 ELSE @FuelLevelPercentage END  
    SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = CASE CapacityUnits WHEN 1 THEN 'litres' WHEN 2 THEN 'gals' ELSE 'litres' END
	FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID  
      
    SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID  
    SELECT @vcAlarmDetail = @vcAlarmDetail + CASE	WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0 
													THEN ' (Fuel Level = ' + cast(@FuelLevelPercentage as varchar(3))+ '% - ' 
													+ cast(cast(((@FuelLevelPercentage / 100.00) * @tankCapacity)as int) as varchar(5)) +' '+ @vcFuelUnits +')'  
    END  
   END  
 END   
 -- Return the result of the function  
 RETURN @vcAlarmDetail  
END  

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetAlarmDetailsForTrips_New]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetAlarmDetailsForTrips_New]    
(    
 @vcAlarmDesc varchar(250),    
 @tiBoxMsgInTypeID tinyint,    
 @intBoxID int = null,    
 @uiMessageInId uniqueidentifier = null,    
 @dtOriginDateTime DateTime = null,    
 @bitCanShowFuelLevel bit = null,  
 @Lang nvarchar(20) = null   
)    
RETURNS nvarchar(MAX)    
AS    
BEGIN    
 DECLARE @vcAlarmDetail nvarchar(MAX)    
 DECLARE @tiSensorID tinyint    
 DECLARE @SecondsToConvert int    
 DECLARE @vcMoxMsgInTypeName nvarchar(100)    
 DECLARE @tankCapacity int     
 DECLARE @FuelLevelPercentage int    
 DECLARE @vcFuelUnits varchar(10)    
     
 SELECT @vcMoxMsgInTypeName = Case when @Lang = 'LanguageArNew' Then isnull(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi' 
 THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc)  else BoxMsgInTypeDesc  END FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID
      
 IF @tiBoxMsgInTypeID = 11 OR @tiBoxMsgInTypeID = 2 OR @tiBoxMsgInTypeID = 3    
  OR @tiBoxMsgInTypeID= 13    
 BEGIN    
  DECLARE @vcActionOn nvarchar(15)    
  DECLARE @vcActionOff nvarchar(15)    
        
  SET @tiSensorID = CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('=',@vcAlarmDesc)+1,    
  CHARINDEX(';',@vcAlarmDesc,1)-CHARINDEX('=',@vcAlarmDesc)-1    
  ) As tinyint)    
      
  IF @tiSensorID = 31     
   BEGIN    
    SET @vcAlarmDetail = 'Alarm - Tamper'    
   END    
  ELSE IF @tiSensorID = 27    
   BEGIN    
    SET @vcAlarmDetail = 'Alarm - Fuel drain'    
        
    SELECT @vcAlarmDetail = @vcAlarmDetail + ' ' +     
     CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0    
     THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,    
     LEN(@vcAlarmDesc)), ';', '%') ELSE '' END     
   END    
  ELSE IF NOT  EXISTS (SELECT SensorName FROM rvlfBoxSensorsCfg WHERE SensorId = @tiSensorId and BoxID = @intBoxID)    
   BEGIN    
    SET @vcAlarmDetail = 'Unknown sensor'    
   END    
  ELSE     
   BEGIN    
    SELECT @vcAlarmDetail = ISNULL(Case when @Lang = 'LanguageArNew' Then SN.SensorName_Ar else SC.SensorName end , 'Unknown sensor')  ,     
     @vcActionOn = Case when @Lang = 'LanguageArNew' Then isnull(SN.ActionOn_Ar,'') ELSE ISNULL(SC.ActionOn,'') END,   
     @vcActionOff = Case when @Lang = 'LanguageArNew' Then isnull(SN.ActionOff_Ar,'') else ISNULL(SC.ActionOff,'')  END        
     FROM rvlfBoxSensorsCfg SC      
     INNER JOIN rvlfsensor SN on SN.sensorID = SC.SensorID   
     WHERE SC.SensorId = @tiSensorId and BoxID = @intBoxID    
    SET @vcAlarmDetail = @vcAlarmDetail     
    DECLARE @intSensorStateStart int     
    
    SET @intSensorStateStart = CHARINDEX('=',@vcAlarmDesc,LEN('SENSOR_NUM=')+1)    
    DECLARE @intSensorStateEnd int     
    SET @intSensorStateEnd = CHARINDEX(';',@vcAlarmDesc,15)    
    SET @vcAlarmDetail = @vcAlarmDetail + ' '+     
     CASE WHEN (SUBSTRING(@vcAlarmDesc,@intSensorStateStart+1, @intSensorStateEnd - @intSensorStateStart-1)) = 'ON' THEN     
      @vcActionOn    
     ELSE      
      @vcActionOff     
     END    
    IF RIGHT(@vcAlarmDetail,1) = ';'    
    BEGIN    
     SET @vcAlarmDetail = SUBSTRING(@vcAlarmDetail,1,LEN(@vcAlarmDetail)-1)    
    END    
    SET @vcAlarmDetail = @vcAlarmDetail+CASE WHEN @tiBoxMsgInTypeID= 13 THEN ' - Bad Sensor' ELSE '' END    
  END    
 END    
 ELSE IF @tiBoxMsgInTypeID = 9     
 BEGIN    
  SET @SecondsToConvert = CAST(SUBSTRING (@vcAlarmDesc, CHARINDEX(':',@vcAlarmDesc,1)+1,    
   CHARINDEX(';',@vcAlarmDesc)-1 -CHARINDEX(':',@vcAlarmDesc,1)) AS int)    
  SET @vcAlarmDetail = @vcMoxMsgInTypeName + ' '+ CASE WHEN @SecondsToConvert = 0    
  THEN Case when @Lang = 'LanguageArNew' Then  N'(/#' else 'started' END ELSE Case when @Lang = 'LanguageArNew' Then N'%F*GI ' else 'end ' end + dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert) END    
 END    
 ELSE IF @tiBoxMsgInTypeID = 14 OR @tiBoxMsgInTypeID = 15 OR     
  @tiBoxMsgInTypeID = 16 OR @tiBoxMsgInTypeID = 17 OR @tiBoxMsgInTypeID = 24    
 BEGIN    
  SET @SecondsToConvert = CAST(SUBSTRING (@vcAlarmDesc, CHARINDEX(':',@vcAlarmDesc,1)+1,    
   CHARINDEX(';',@vcAlarmDesc)-1 -CHARINDEX(':',@vcAlarmDesc,1)) AS int)    
  SET @vcAlarmDetail = @vcMoxMsgInTypeName + ' '+     
   dbo.rvlf_fn_GetTimeFromSeconds(@SecondsToConvert)    
 END    
    
 ELSE IF @tiBoxMsgInTypeID = 5 OR @tiBoxMsgInTypeID = 6    
 BEGIN    
  IF @uiMessageInId IS NOT NULL    
   BEGIN    
    SELECT @vcAlarmDetail = g.GeozoneName FROM rvlfOrganizationGeozone g INNER JOIN rvlfVehicle v     
     ON g.OrganizationId=v.OrganizationId INNER JOIN rvlfVehicleAssignment va ON     
     v.VehicleId = va.VehicleId     
     INNER JOIN rvlfVehicleGeozone vg ON vg.VehicleID = v.VehicleID AND     
        vg.GeozoneNo = g.GeozoneNo    
     WHERE BoxId = @intBoxID and GeozoneId = --CAST(@vcAlarmDesc as bigint)    
     (CAST( SUBSTRING(@vcAlarmDesc,    
      CHARINDEX('=',@vcAlarmDesc,1)+1,(CHARINDEX(';',@vcAlarmDesc,1)    
      - CHARINDEX('=',@vcAlarmDesc,1))-1) as bigint))    
    SET @vcAlarmDetail = ISNULL(@vcAlarmDetail,'Geozone Deleted') + ' '+     
     CASE WHEN @tiBoxMsgInTypeID = 5 THEN ' - In' ELSE ' - Out' END    
   END    
  ELSE    
   BEGIN    
    SELECT @vcAlarmDetail = g.GeozoneName FROM rvlfOrganizationGeozone g INNER JOIN rvlfVehicle v     
     ON g.OrganizationId=v.OrganizationId INNER JOIN rvlfVehicleAssignment va ON     
      v.VehicleID = va.VehicleID    
      INNER JOIN rvlfVehicleGeozone vg ON vg.VehicleID = v.VehicleID AND     
        vg.GeozoneNo = g.GeozoneNo    
     WHERE BoxId = @intBoxID and GeozoneId = --CAST(@vcAlarmDesc as bigint)    
     (CAST( @vcAlarmDesc as bigint))     
    SET @vcAlarmDetail = ISNULL(@vcAlarmDetail,'Geozone Deleted') + ' '+     
     CASE WHEN @tiBoxMsgInTypeID = 5 THEN ' - In' ELSE ' - Out' END    
   END    
 END    
 ELSE IF @tiBoxMsgInTypeID = 28    
 BEGIN    
  DECLARE @bigOrganizationID bigint    
  SELECT @bigOrganizationID = v.OrganizationId  FROM rvlfVehicle v    
   INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId and va.BoxId = @intBoxID    
  SET @vcAlarmDetail = (SELECT g.GeozoneName from rvlfOrganizationGeozone g WHERE g.GeozoneId IN     
   (select * from dbo.rvlf_fn_ConvertArrayToTable(@vcAlarmDesc,','))    
   AND g.OrganizationID = @bigOrganizationID FOR XML AUTO)    
  IF @vcAlarmDetail IS NULL    
   BEGIN    
    SET @vcAlarmDetail = ''    
   END    
  ELSE    
   BEGIN    
    SET @vcAlarmDetail = '<GeozoneList>'+@vcAlarmdetail+'</GeozoneList>'    
   END    
 END    
 ELSE IF @tiBoxMsgInTypeID = 19    
  BEGIN    
   DECLARE @intIPReason int     
   SET @intIPReason  = CAST(SUBSTRING(@vcAlarmDesc, CHARINDEX('=',@vcAlarmDesc,1)+1,CHARINDEX(';',@vcAlarmDesc,1)-(CHARINDEX('=',@vcAlarmDesc,1)+1) ) as int)     
   SET @vcAlarmDetail = 'IP Update - '+    
    CASE WHEN @intIPReason = 1 THEN 'Power Up' WHEN @intIPReason = 2 THEN 'Failed'    
      WHEN @intIPReason = 3 THEN 'Sleep' WHEN @intIPReason = 4 THEN 'Attach ERROR'    
      WHEN @intIPReason = 5 THEN 'PPP TERMINATE' WHEN @intIPReason = 6 THEN 'Long PPP Negotiation'     
      WHEN @intIPReason = 7 THEN 'PPP Negotiated To' WHEN @intIPReason = 8 THEN 'No Diag'     
      WHEN @intIPReason = 9 THEN 'Force Reset' WHEN @intIPReason = 10 THEN 'Std Msg Failed'     
      WHEN @intIPReason = 11 THEN 'Mdm Reset Fail' WHEN @intIPReason = 12 THEN 'Wake Up'     
      WHEN @intIPReason = 13 THEN 'Register To' WHEN @intIPReason = 14 THEN 'Attach To'     
      WHEN @intIPReason = 15 THEN 'AT failed' WHEN @intIPReason = 16 THEN 'Dial To'     
      WHEN @intIPReason = 17 THEN 'Dial failed' WHEN @intIPReason = 18 THEN 'Errors > 10'     
      WHEN @intIPReason = 19 THEN 'Can''t attached'    
      ELSE 'Unknown' END    
  END    
 ELSE IF @tiBoxMsgInTypeID = 42    
   BEGIN
		SET @FuelLevelPercentage = CAST(dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'Fuel%=',';') as int)                          
		SET @FuelLevelPercentage = CASE WHEN @FuelLevelPercentage <=0 THEN 0 ELSE @FuelLevelPercentage END                          
		SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = CASE CapacityUnits WHEN 1 THEN 'litres' WHEN 2 THEN 'gals' ELSE 'litres' END
		FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID                                                       
		--SELECT @vcAlarmDetail = Case when @Lang = 'LanguageArNew' Then isnull(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi' 
		--THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc) else BoxMsgInTypeDesc END FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID
		SELECT @vcAlarmDetail = @vcMoxMsgInTypeName	+ ' (Actual Fuel Drained - ' +		--+ ' ('+ cast(@FuelLevelPercentage as varchar(3))+ '% - '+  
								cast(cast(((@FuelLevelPercentage / 100.00) * @tankCapacity)as int) as varchar(5)) +' '+ @vcFuelUnits +')' 
   END    
 ELSE IF @tiBoxMsgInTypeID = 41    
   BEGIN    
    SELECT @vcAlarmDetail = Case when @Lang = 'LanguageArNew' Then BoxMsgInTypeDesc_Ar else BoxMsgInTypeDesc end FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID   
        
    --SELECT @vcAlarmDetail = @vcAlarmDetail + ' ' +     
    -- CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0    
    -- THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,    
    -- LEN(@vcAlarmDesc)), ';', '%') ELSE '' END     
   END    
 ELSE IF @tiBoxMsgInTypeID IN (37, 38, 39, 42, 45, 46, 47, 48, 49, 50)    
  BEGIN    
   --SET @FuelLevelPercentage =(( CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0    
   --   THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,    
   --   LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int) * 33)-600)/24.1    
    SET @FuelLevelPercentage =CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0    
      THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,    
      LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int)    
   SET @FuelLevelPercentage = CASE WHEN @FuelLevelPercentage <=0 THEN 0 ELSE @FuelLevelPercentage END    
   SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = ISNULL(CapacityUnits,'gals') FROM rvlfVehicle v INNER JOIN    
    rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID    
       
   SELECT @vcAlarmDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID    
   SELECT @vcAlarmDetail = @vcAlarmDetail     
    + ' ('+ cast(@FuelLevelPercentage as varchar(3))+ '% - '+     
    cast(cast(((@FuelLevelPercentage / 100.00) * @tankCapacity)as int) as varchar(5)) +' '+ @vcFuelUnits +')'    
     --CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0    
     -- THEN ' (' +  REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,    
     -- LEN(@vcAlarmDesc)), ';', '%)') ELSE '' END    
  END    
 --ELSE IF @tiBoxMsgInTypeID = 54    
 -- BEGIN    
 --  --SELECT @vcAlarmDetail = '<table><tr><td>'+ REPLACE(REPLACE(@vcAlarmDesc,'=','<td>:</td><td>'),';','</td></tr><tr><td>' )+'</table>'    
 -- END    
 --ELSE IF @tiBoxMsgInTypeID = 51    
 -- BEGIN    
 --  SET @vcAlarmDetail = 'Speed viol    
 -- END    
 ELSE    
 BEGIN    
      
  SELECT @vcAlarmDetail = Case when @Lang = 'LanguageArNew' Then BoxMsgInTypeDesc_Ar else BoxMsgInTypeDesc end FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID        
      
  IF @bitCanShowFuelLevel = 1 AND @tiBoxMsgInTypeID NOT IN (19,20,21,22,35,40,55,54,56,53)    
   BEGIN    
   SET @vcAlarmDetail = @vcAlarmDetail    
    --SET @FuelLevelPercentage =(( CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0    
    --  THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,    
    --  LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int) * 33)-600)/24.1    
    --SET @FuelLevelPercentage =CAST(CASE WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0    
    --  THEN REPLACE(SUBSTRING ( @vcAlarmDesc, CHARINDEX('Fuel%=',@vcAlarmDesc, 1)+6,    
    --  LEN(@vcAlarmDesc)), ';', '') ELSE '0' END as int)    
	SET @FuelLevelPercentage = CAST(dbo.rvlf_fn_GetParamValueWithIndex(@vcAlarmDesc,'Fuel%=',';') as int)                          
    SET @FuelLevelPercentage = CASE WHEN @FuelLevelPercentage <=0 THEN 0 ELSE @FuelLevelPercentage END    
    SELECT @tankCapacity = ISNULL(v.TankCapacity,0), @vcFuelUnits = CASE CapacityUnits WHEN 1 THEN 'litres' WHEN 2 THEN 'gals' ELSE 'litres' END
	FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID WHERE BoxID = @intBoxID    
        
    SELECT @vcAlarmDetail = Case when @Lang = 'LanguageArNew' Then BoxMsgInTypeDesc_Ar else BoxMsgInTypeDesc end FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID    
    SELECT @vcAlarmDetail = @vcAlarmDetail + CASE	WHEN CHARINDEX('Fuel%=',@vcAlarmDesc, 1) <> 0 
													THEN ' (Fuel Level = ' + cast(@FuelLevelPercentage as varchar(3))+ '% - ' 
													+ cast(cast(((@FuelLevelPercentage / 100.00) * @tankCapacity)as int) as varchar(5)) +' '+ @vcFuelUnits +')' 
    END    
   END    
 END     
 -- Return the result of the function    
 RETURN @vcAlarmDetail    
END 

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetArabicMonth]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



Create Function [dbo].[rvlf_fn_GetArabicMonth] 
(	
	@TDate varchar(max) = null,
	@PasDateFormat int = null
)
RETURNS NVarchar(max)
AS
BEGIN 
   DECLARE @FinalEnMonth NVarchar(max)		
   DECLARE @tblMonthsEN TABLE (MName NVarchar(max))
   DECLARE @ValidateMonth Nvarchar(max)	
   IF(@TDate IS NOT NULL and @PasDateFormat IS NOT NULL)
   BEGIN
		Insert into @tblMonthsEN
		select FieldValue from rvlf_fn_ConvertArrayToTableArENMonth(N'Jan-يناير,Feb-فبراير,Mar-مارس,Apr-أبريل/إبريل,May-مايو,Jun-يونيو/يونية,Jul-يوليو/يولية,Aug-أغسطس,Sep-سبتمبر,Oct-أكتوبر,Nov-نوفمبر,Dec-ديسمبر',',')

		DECLARE @MonthLooping NVarchar(max)            
		SELECT @MonthLooping = MIN(MName) from @tblMonthsEN            
		WHILE @MonthLooping IS NOT NULL            
		BEGIN      
			select @ValidateMonth = MName from @tblMonthsEN where  MName= @MonthLooping
			if @PasDateFormat = 107
			begin
				if SUBSTRING(@ValidateMonth,1,3)   = SUBSTRING(@TDate,1,3)  
				Begin
					set	@FinalEnMonth = SUBSTRING(@ValidateMonth,5,len(@ValidateMonth)) + SUBSTRING(@TDate,4,LEN(@TDate))
				End
			End
			else if @PasDateFormat = 106
			begin 	
				if SUBSTRING(@ValidateMonth,1,3)   = SUBSTRING(@TDate,4,3)  
				Begin
					set	@FinalEnMonth = SUBSTRING(@TDate,1,3) + SUBSTRING(@ValidateMonth,5,len(@ValidateMonth)) + SUBSTRING(@TDate,7,LEN(@TDate))
				End
			End			
   SELECT @MonthLooping = MIN(MName) from @tblMonthsEN WHERE MName > @MonthLooping            
   END
    
   END
	    
   RETURN @FinalEnMonth
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetCameraHex]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetCameraHex]
(
  @intBoxID int,        
  @intImageID int,
  @startdate as datetime,
  @enddate datetime
)
RETURNS varchar(MAX)
AS
BEGIN	
	DECLARE @CamHexData varchar(max)
	
	SELECT top 100 @CamHexData = coalesce(@CamHexData + ',', '') + ImageData FROM rvlfCameraImages where boxid = @intBoxID and imageid =@intImageID 
	--and Receiveddate between CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109)	
	order by CamMasterID 
		
	-- Return the result of the function
	RETURN @CamHexData
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetCmdMsgDetails]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetCmdMsgDetails]
(
	@vcAlarmDesc varchar(500),
	@tiBoxCmdOutTypeId int,
	@intBoxID int = null
)
RETURNS varchar(MAX)
AS
BEGIN
	DECLARE @vcMsgDetail varchar(MAX)
	
	IF @tiBoxCmdOutTypeId = 4
	BEGIN 
	
		DECLARE @OutputId AS TINYINT = CAST(SUBSTRING(@vcAlarmDesc, 1, 1) AS TINYINT)
		DECLARE @Action AS TINYINT = CAST(SUBSTRING(@vcAlarmDesc, 2, 1) AS TINYINT)

		SET @vcMsgDetail = (SELECT OutputName + ' ' + (CASE WHEN @Action = 1 THEN ActionOn ELSE ActionOff END) 
		                    FROM rvlfBoxOutputsCfg WHERE OutputId = @OutputId AND BoxId = @intBoxId)
		                    
		IF (@vcMsgDetail IS NULL OR @vcMsgDetail = '')
		BEGIN
		
			SET @vcMsgDetail = (SELECT OutputName + ' ' + (CASE WHEN @Action = 1 THEN SUBSTRING(OutputAction ,1, CHARINDEX('/',OutputAction,1)-1) ELSE SUBSTRING(OutputAction ,CHARINDEX('/',OutputAction,1)+1, LEN(OutputAction)) END) 
		                        FROM rvlfOutput WHERE OutputId = @OutputId)
		                        
		END

	END
	ELSE IF @tiBoxCmdOutTypeId = 39 
	BEGIN
				
		DECLARE @Pos INT = CHARINDEX(',',@vcAlarmDesc,0)
		DECLARE @SPos INT = 1
		DECLARE @Count INT = 0
		DECLARE @MsgKind TINYINT 

		WHILE @Pos > 0
		BEGIN
		    
			IF @Count = 3
			BEGIN
				SET @MsgKind = CONVERT(TINYINT, SUBSTRING(@vcAlarmDesc,@SPos,@Pos-@SPos))
			END
		    
			IF @Count = 4 AND @MsgKind = 1
			BEGIN
				SELECT @vcMsgDetail = MsgName FROM rvlfPrecannedMessages WHERE PrecannedMsgId = CONVERT(TINYINT, SUBSTRING(@vcAlarmDesc,@SPos,@Pos-@SPos)) AND IsServerMsg = 1
			END
		    
			IF @Count = 7 AND @MsgKind = 0
			BEGIN
				SELECT @vcMsgDetail = SUBSTRING(@vcAlarmDesc,@SPos,@Pos-@SPos)
			END
		    
			SET @SPos = @Pos + 1
			SET @Pos = CHARINDEX(',',@vcAlarmDesc,@Pos+1)
			SET @Count = @Count + 1
		END

		IF @vcMsgDetail IS NOT NULL
		BEGIN
			SET @vcMsgDetail = 'Server Msg=' + @vcMsgDetail
		END

	END

	-- Return the result of the function
	RETURN @vcMsgDetail
	
END





GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetDoorSensorDetails]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[rvlf_fn_GetDoorSensorDetails]
(
	@vcAlarmDesc varchar(250),
	@tiBoxMsgInTypeID tinyint,
	@intBoxID int = null,
	@uiMessageInId uniqueidentifier = null,
	@dtOriginDateTime DateTime = null
)
RETURNS varchar(MAX)
AS
BEGIN
	DECLARE @vcAlarmDetail varchar(MAX)
	DECLARE @tiSensorID tinyint
	DECLARE @SecondsToConvert int
	DECLARE @vcMoxMsgInTypeName varchar(100)
	DECLARE @tankCapacity int 
	DECLARE @FuelLevelPercentage int
	DECLARE @vcFuelUnits varchar(10)
	
	SELECT @vcMoxMsgInTypeName = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID
		
	IF @tiBoxMsgInTypeID = 11 OR @tiBoxMsgInTypeID = 2 OR @tiBoxMsgInTypeID = 3
		OR @tiBoxMsgInTypeID= 13
	BEGIN
		DECLARE @vcActionOn varchar(15)
		DECLARE @vcActionOff varchar(15)
				
		SET @tiSensorID = CAST(SUBSTRING(@vcAlarmDesc,CHARINDEX('=',@vcAlarmDesc)+1,
		CHARINDEX(';',@vcAlarmDesc,1)-CHARINDEX('=',@vcAlarmDesc)-1
		) As tinyint)
		
	if(@tiSensorID =1)
			BEGIN
				SELECT @vcAlarmDetail = ISNULL(SensorName, 'Unknown sensor') , 
					@vcActionOn = ISNULL(ActionOn,''), @vcActionOff = ISNULL(ActionOff,'')
				 FROM rvlfBoxSensorsCfg WHERE SensorId = @tiSensorId and BoxID = @intBoxID
				SET @vcAlarmDetail = @vcAlarmDetail 
				DECLARE @intSensorStateStart int 

				SET @intSensorStateStart = CHARINDEX('=',@vcAlarmDesc,LEN('SENSOR_NUM=')+1)
				DECLARE @intSensorStateEnd int 
				SET @intSensorStateEnd = CHARINDEX(';',@vcAlarmDesc,15)
				SET @vcAlarmDetail = @vcAlarmDetail + ' '+ 
					CASE WHEN (SUBSTRING(@vcAlarmDesc,@intSensorStateStart+1, @intSensorStateEnd - @intSensorStateStart-1)) = 'ON' THEN 
						@vcActionOn
					ELSE  
						@vcActionOff 
					END
				IF RIGHT(@vcAlarmDetail,1) = ';'
				BEGIN
					SET @vcAlarmDetail = SUBSTRING(@vcAlarmDetail,1,LEN(@vcAlarmDetail)-1)
				END
				SET @vcAlarmDetail = @vcAlarmDetail+CASE WHEN @tiBoxMsgInTypeID= 13 THEN ' - Bad Sensor' ELSE '' END
		END
	END
	
	-- Return the result of the function
	RETURN @vcAlarmDetail
END





GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetDTCDetails]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetDTCDetails]
(@DTCCode as varchar(6))
RETURNS VARCHAR(MAX)
AS
/******************************************************************************/  
-- Name			: rvlf_fn_GetDTCDetails  
-- Description	: To get the DTC code details
-- Author		: S. Sakthi Gopinath
-- Created Date	: 01-March-2012
-- Company		: Angler Technologies  
-- History		: <<Date(dd-MON-yyyy)>> Initial Reason  
/******************************************************************************/  
BEGIN
	DECLARE @DTCDetails varchar(max)
	SELECT @DTCDetails = CASE 
							  WHEN @DTCCode='P0000' THEN ''
							  WHEN @DTCCode='P0016' THEN 'Crank shaft position - Camshaft position correlation'
							  WHEN @DTCCode='P0022' THEN 'A camshaft position - Timing over retatrded'
							  WHEN @DTCCode='P0100' THEN 'Mass or Volume Air Flow Circuit Malfunction'
							  WHEN @DTCCode='P0105' THEN 'Maniofold Absolute pressure circuit malfunction'
							  WHEN @DTCCode='P0110' THEN 'Intake Air Temperature Circuit Malfunction'
							  WHEN @DTCCode='P0200' THEN 'Injector circuit malfunction'
							  WHEN @DTCCode='P0216' THEN 'Injection Timing Control Malfunction'
							  WHEN @DTCCode='P0217' THEN 'Engine Over Temperature'
							  WHEN @DTCCode like '%P03%' THEN
								CASE WHEN CAST(SUBSTRING(@DTCCode,4,2) AS int) =0 THEN 'Random/Multiple Cylinder Misfire Detected'
									 WHEN CAST(SUBSTRING(@DTCCode,4,2) AS int) =85 THEN 'Crank shaft position sensor B circuit malfunction'
		  							 ELSE 'Cylinder '+CAST(CAST(SUBSTRING(@DTCCode,4,2) AS int) AS VARCHAR)+' Misfire' 
		  						END
							  WHEN @DTCCode='P0460' THEN 'Fuel Level Sensor Circuit Malfunction'
							  WHEN @DTCCode='C0000' THEN 'Vehicle Speed Information Circuit Malfunction'
							  WHEN @DTCCode='C0110' THEN 'Pump Motor Circuit Malfunction'
							  WHEN @DTCCode='C0238' THEN 'Wheel Speed Mismatch'
							  WHEN @DTCCode='B0005' THEN 'In Park Switch Circuit Malfunction'
							  WHEN @DTCCode='B0530' THEN 'Fuel Level Sensor Stuck'
							  WHEN @DTCCode='B0856' THEN 'Battery 2 Out of Range'
							  ELSE @DTCCode
						 END	
	RETURN @DTCDetails
END
GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetDuration]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetDuration]
(
	@vcCustomProperty varchar(1000),
	@tiBoxMsgInTypeID tinyint,
	@intBoxID int = null,
	@bitIsFormatted bit = 1
)
RETURNS varchar(200)
AS
BEGIN
	DECLARE @vcAlarmDetail varchar(200)
	
	IF @tiBoxMsgInTypeID = 14 OR @tiBoxMsgInTypeID = 15 OR @tiBoxMsgInTypeID = 9 OR
		@tiBoxMsgInTypeID = 16 OR @tiBoxMsgInTypeID = 17 OR @tiBoxMsgInTypeID = 24 OR @tiBoxMsgInTypeID = 51
	BEGIN
		DECLARE @vcBoxMsgInTypeDesc varchar(100)
		SELECT @vcBoxMsgInTypeDesc = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID
		DECLARE @SecondsToConvert int
		SET @SecondsToConvert = CAST(SUBSTRING (@vcCustomProperty, CHARINDEX(':',@vcCustomProperty,1)+1,
			CHARINDEX(';',@vcCustomProperty)-1 -CHARINDEX(':',@vcCustomProperty,1)) AS int)
		IF @bitIsFormatted = 1
		BEGIN
			SET @vcAlarmDetail = convert(varchar,CAST( RTRIM(CONVERT(char(8),
				 @SecondsToConvert/3600) ) + ':' + CONVERT(char(2), (@SecondsToConvert % 3600) / 60)
				+ ':' + CONVERT(char(2), @SecondsToConvert % 60) as Datetime),108)
		END
		ELSE
		BEGIN
			SET @vcAlarmDetail = CAST(@SecondsToConvert as varchar(200))
		END
	END
	-- Return the result of the function
	RETURN @vcAlarmDetail
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetDurationInSeconds]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetDurationInSeconds]
(
	@input VARCHAR(20) 
)
RETURNS BIGINT
AS
BEGIN
	DECLARE @vcduration BIGINT
	DECLARE @tblDuration TABLE (Slno INT IDENTITY(1,1), VALUE VARCHAR(4))
	set @input = replace(@input,'.',':')
	INSERT INTO @tblDuration(VALUE)
	SELECT FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(REPLACE(REPLACE(@input,' ',':'),'D',''),':')
	SELECT @vcduration = (CASE WHEN COUNT(Slno) = 4 THEN 
	(SELECT SUM(CASE WHEN Slno=1 THEN CAST(REPLACE(VALUE,'D','') AS INT)*24*3600 
	WHEN Slno=2 THEN CAST(VALUE AS INT)* 3600 
	WHEN Slno=3 THEN CAST(VALUE AS INT) * 60 ELSE CAST(VALUE AS INT) END) FROM @tblDuration)
	ELSE	(SELECT SUM(CASE WHEN Slno=1 THEN CAST(VALUE  AS INT) *3600 
	WHEN Slno=2 THEN CAST(VALUE AS INT)  * 60 
	ELSE CAST(VALUE	AS INT)  END) FROM @tblDuration) END)	FROM @tblDuration
	RETURN @vcduration
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetEmailIds]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[rvlf_fn_GetEmailIds] 
(
	@vcUserIds varchar(max)
)
RETURNS varchar(max)
AS
BEGIN
   DECLARE @vcEmailIds varchar(max)
		
   IF(@vcUserIds IS NOT NULL)
   BEGIN
		
		SELECT @vcEmailIds = ISNULL(@vcEmailIds + ';', '')+ Email
	    FROM rvlfUser
	    WHERE UserId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcUserIds,','))
			AND ISDELETE=0
    
   END
	    
   RETURN @vcEmailIds
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetEnergyConsumptionForShift]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Karthikeyan>
-- Create date: <Create Date, ,05-07-2018>
-- Description:	<Description, ,Get the OdometerValue based on the shift timing>
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_GetEnergyConsumptionForShift]
(
	-- Add the parameters for the function here
	@BoxId nvarchar(100) =null,
	@OriginDate datetime =null,
	@FunType int=null
)
RETURNS bigint
AS
BEGIN
	DECLARE @ResultVar bigint=0
	declare @FilterValue nvarchar(10)
	if(@FunType=1)
	begin
		set @FilterValue='WH1='
	end
	else
	begin
		set @FilterValue='WH2='
	end 
	declare @StartDate datetime, @EndDate datetime, @EqType int,@MaxValue bigint=0,@minValue bigint=0
	set @OriginDate =dateadd(MI,30,dateadd(HH,5,@OriginDate))
	select @StartDate=dbo.rvlf_fn_GetShiftStartDateandTime(@BoxId,@OriginDate)

	Select @MaxValue=MAX(isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,@FilterValue,';'),0)) ,@minValue=min(isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,@FilterValue,';'),0)) from rvlfMsgInHst where BoxId=@BoxId and dateadd(MI,30,dateadd(HH,5,OriginDateTime)) between @StartDate and @OriginDate and dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,@FilterValue,';') is not null
	set @ResultVar=@MaxValue-@minValue
	RETURN isnull(@ResultVar,0)
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetFuelDetails]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetFuelDetails]
(
	@vcFuelDesc varchar(1000)=null,
	@tiBoxMsgInTypeID tinyint=null,
	@intBoxID int = 2,
	@uiMessageInId uniqueidentifier = null,
	@dtOriginDateTime DateTime =null
)
RETURNS varchar(MAX)
AS
BEGIN
	DECLARE @vcFuelDetail varchar(MAX)	=''
	DECLARE @vcMoxMsgInTypeName varchar(100)	
	DECLARE @FuelLevelPercentage nvarchar(50)=''

	
	SELECT @vcMoxMsgInTypeName = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID
		
			BEGIN		
						
			SET @FuelLevelPercentage =
			CASE WHEN CHARINDEX('Fuel%=',@vcFuelDesc, 1) <> 0 THEN
						 SUBSTRING(@vcFuelDesc,CHARINDEX('Fuel%=',@vcFuelDesc,1)+6,
							CHARINDEX(';',@vcFuelDesc, CHARINDEX('Fuel%=',@vcFuelDesc,1)) - (CHARINDEX('Fuel%=',@vcFuelDesc,1)+6))
						ELSE '0' END
			
			DECLARE @fuelInLit AS Varchar(20)
			
		    SET @fuelInLit = (CASE WHEN (@FuelLevelPercentage = 'Transition' OR @FuelLevelPercentage = '0') THEN '0 lit.' 
		                      ELSE CAST(ROUND(CAST(((@FuelLevelPercentage / 100.00) * (CASE WHEN @intBoxID IN (189, 35, 190, 999982) THEN 225 WHEN @intBoxID = 191 THEN 250 ELSE 57 END)) AS DECIMAL), 0, 0) AS Varchar(10)) + ' litres.' END)
						
			IF @tiBoxMsgInTypeID =90 OR  @tiBoxMsgInTypeID = 92 
				BEGIN
					SELECT @vcFuelDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID
				END
			
			IF @FuelLevelPercentage = 'Transition' 
				BEGIN
					SELECT @vcFuelDetail = 'Fuel '+ @FuelLevelPercentage 			
				END
			ELSE
				BEGIN	
					IF @tiBoxMsgInTypeID =90 OR @tiBoxMsgInTypeID = 92 
						BEGIN							
							SELECT @vcFuelDetail = @vcFuelDetail  + ' ('+ cast(@FuelLevelPercentage as varchar(3))+ '% - '+  @fuelInLit +')'	
						END
			 
					ELSE
						BEGIN
							SET @vcFuelDetail = (CASE WHEN CHARINDEX(')',@vcFuelDetail, 1) <> 0 
											  THEN REPLACE(@vcFuelDetail, ')', (',Fuel Level = ' + @FuelLevelPercentage + '% - ' + @fuelInLit ))
											  ELSE @vcFuelDetail + 'Fuel Level = ' + @FuelLevelPercentage + '% - ' + @fuelInLit  END)	
						END
				END		
								
		END	
	
	
	-- Return the result of the function
	RETURN @vcFuelDetail

END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetGeneratorParameterName]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetGeneratorParameterName]
(
	@tiGenParamNo tinyint
)
RETURNS varchar(200)
AS
BEGIN
	DECLARE @vcGenParamName varchar(200)
	
	IF @tiGenParamNo = 1
	BEGIN
		SET @vcGenParamName = 'Hybrid Battery Temp'
	END
	IF @tiGenParamNo = 2
	BEGIN
		SET @vcGenParamName = 'Engine Temp'
	END
	IF @tiGenParamNo = 3
	BEGIN
		SET @vcGenParamName = 'High Engine Temp'
	END
	IF @tiGenParamNo = 4
	BEGIN
		SET @vcGenParamName = 'Low Oil Pressure'
	END
	IF @tiGenParamNo = 5
	BEGIN
		SET @vcGenParamName = 'Fuel Level in %'
	END
	IF @tiGenParamNo = 6
	BEGIN
		SET @vcGenParamName = 'Common Alarm'
	END
	IF @tiGenParamNo = 7
	BEGIN
		SET @vcGenParamName = 'Status_ON_OFF'
	END
	IF @tiGenParamNo = 8
	BEGIN
		SET @vcGenParamName = 'Control Card Mode Auto Manual'
	END
	IF @tiGenParamNo = 9
	BEGIN
		SET @vcGenParamName = 'RPM Positive'
	END
	IF @tiGenParamNo = 10
	BEGIN
		SET @vcGenParamName = 'RPM Negative'
	END
	IF @tiGenParamNo = 11
	BEGIN
		SET @vcGenParamName = 'Speed Regulation Mode Auto Manual'
	END
	IF @tiGenParamNo = 12
	BEGIN
		SET @vcGenParamName = 'Service Hours'
	END
	IF @tiGenParamNo = 13
	BEGIN
		SET @vcGenParamName = 'Hybrid Battery Voltage'
	END
	IF @tiGenParamNo = 14
	BEGIN
		SET @vcGenParamName = 'Hybrid Battery Current'
	END
	IF @tiGenParamNo = 15
	BEGIN
		SET @vcGenParamName = 'Hybrid Genset Current'
	END
	IF @tiGenParamNo = 16
	BEGIN
		SET @vcGenParamName = 'AC Voltage Genset Phase1'
	END
	IF @tiGenParamNo = 17
	BEGIN
		SET @vcGenParamName = 'AC Voltage Genset Phase2'
	END
	IF @tiGenParamNo = 18
	BEGIN
		SET @vcGenParamName = 'AC Voltage Genset Phase3'
	END
	IF @tiGenParamNo = 19
	BEGIN
		SET @vcGenParamName = 'Fuel Level in Liters'
	END
	IF @tiGenParamNo = 20
	BEGIN
		SET @vcGenParamName = 'Generator Frequency'
	END
	IF @tiGenParamNo = 21
	BEGIN
		SET @vcGenParamName = 'Total Kw Hrs'
	END
	
	-- Return the result of the function
	RETURN @vcGenParamName
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetHHMMSSFromSec]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 CREATE FUNCTION [dbo].[rvlf_fn_GetHHMMSSFromSec]      
(      
 @intTotalSeconds bigint       
)      
RETURNS varchar(50)      
AS      
BEGIN      
 SELECT @intTotalSeconds = ABS(@intTotalSeconds)      
 DECLARE @vcduration varchar(50)      
        
  SET @vcduration =  CONVERT(varchar(max), @intTotalSeconds/3600)      
+ ':' + RIGHT('0' + CONVERT(varchar(max), (@intTotalSeconds % 3600) / 60), 2)      
+ ':' + RIGHT('0' + CONVERT(varchar(max), @intTotalSeconds % 60), 2)      
        
         
 RETURN @vcduration      
END 


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetIdlingTime_MFC]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetIdlingTime_MFC]
(@intBoxLooping bigint,@dtStartDate datetime,@dtEndDate datetime)RETURNS VARCHAR(10)
AS
/****************************************************************************************************************
Function Name	: SELECT dbo.rvlf_fn_GetIdlingTime_MFC(3989,'2013-04-03 05:40:52.000','2013-04-03 06:16:38.000')
Created By		: Sakthi Gopinath S
Created Date	: 04-Mar-2013
****************************************************************************************************************/
BEGIN
DECLARE @vcStopTime bigint
DECLARE @tbl_IgnitionMessageForProcessingTrip TABLE(            
  [OriginDateTime] [datetime] NOT NULL,            
  [BoxMsgInTypeId] [tinyint] NULL,            
  [CustomProp] [varchar](600) NULL,              
  [Speed] int NULL,            
  [Ignition] bit null,              
  [Address] varchar(300) null,            
  [OdoMeter] bigint null,            
  Lat numeric(10,6),            
  Long numeric(10,6)            
 )   

DECLARE @TBL_IdlingStart TABLE
 (            
  Processid bigint identity(1,1),            
  Boxid int,            
  StartTime datetime,            
  OdoStart bigint,            
  idling int,            
  tripId int
 )            
             
 DECLARE @TBL_IdlingStop TABLE
 (            
  Processid bigint identity(1,1),     
  Boxid int,            
  StopTime datetime,            
  OdoEnd bigint,            
  idling int,
  tripId int,            
  IsTripCompleted bit            
 ) 

DELETE FROM @tbl_IgnitionMessageForProcessingTrip
INSERT INTO @tbl_IgnitionMessageForProcessingTrip(OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,Address,OdoMeter,Lat,Long)             
SELECT h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,CAST(SUBSTRING(sensormask,6,1) as bit),
CASE WHEN (H.LandMarkID IS NULL OR H.LandMarkID = 0) THEN             
REPLACE(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''') ELSE L.LandmarkName END,            
CASE WHEN CustomProp LIKE '%Odometer=%' THEN CAST( SUBSTRING (CustomProp,CHARINDEX('Odometer=',CustomProp,1)+9,CHARINDEX(';',CustomProp,            
CHARINDEX('Odometer=',CustomProp,1)) - (CHARINDEX('Odometer=',CustomProp,1)+9)) as bigint) ELSE 0 END,H.Latitude,H.Longitude                       
FROM rvlfMsgInHst H  LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID                                      
WHERE h.BoxID = @intBoxLooping AND H.BoxMsgInTypeId IN (9) AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate    
AND h.CustomProp LIKE '%idling:%' ORDER BY h.origindatetime ASC  
 
INSERT INTO @TBL_IdlingStart (Boxid,StartTime,OdoStart,idling)
SELECT @intBoxLooping,OriginDateTime,OdoMeter,CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,            
(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT)
FROM @tbl_IgnitionMessageForProcessingTrip WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
AND BoxMsgInTypeId IN(9) AND 
CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,            
(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT) = 0

INSERT INTO @TBL_IdlingStop (Boxid,StopTime,OdoEnd,idling)
SELECT @intBoxLooping,OriginDateTime,OdoMeter,CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,            
(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT)
FROM @tbl_IgnitionMessageForProcessingTrip WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
AND BoxMsgInTypeId IN(9) AND
CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,            
(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT) > 0

--PREPARE THE TRIPS AND DETAILS                
DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBL_IdlingStop)             
DECLARE @DTSTART DATETIME=null,@DTEND DATETIME=null,@DTSTOPSTART DATETIME =NULL              
DECLARE @INC INT=1                   
WHILE @LOOP IS NOT NULL            
 BEGIN         
  SELECT @DTSTOPSTART=NULL,@DTSTART=NULL
  SELECT TOP 1 @DTSTOPSTART=StopTime FROM @TBL_IdlingStop WHERE Processid >= @LOOP
  SELECT TOP 1 @DTSTART=MIN(StartTime) FROM @TBL_IdlingStart WHERE StartTime < @DTSTOPSTART     
  UPDATE top(1) @TBL_IdlingStop SET IsTripCompleted=1 WHERE StopTime=@DTSTOPSTART AND @DTSTART < @DTSTOPSTART
  SET @INC =@INC +1            
  SELECT @LOOP =MIN(Processid) FROM @TBL_IdlingStop WHERE Processid > @LOOP  AND StopTime > @DTSTOPSTART            
END   
DECLARE @FirstStopTime int=0
DECLARE @SecondStopTime int=0
SELECT TOP 1 @FirstStopTime=(CASE WHEN BoxMsgInTypeID=9 AND CustomProp NOT LIKE 'Idling:0;%' THEN DATEDIFF(S,@dtStartDate,OriginDateTime) ELSE 0 END) FROM @tbl_IgnitionMessageForProcessingTrip
SELECT TOP 1 @SecondStopTime=(CASE WHEN BoxMsgInTypeID=9 AND CustomProp LIKE 'Idling:0;%' THEN DATEDIFF(S,OriginDateTime,@dtEndDate) ELSE 0 END) FROM @tbl_IgnitionMessageForProcessingTrip
ORDER BY OriginDateTime DESC
--SELECT @vcStopTime=ISNULL((SUM(ISNULL(idling,0))+@FirstStopTime+@SecondStopTime),0) FROM @TBL_IdlingStop WHERE IsTripCompleted=1
SELECT @vcStopTime=ISNULL((SELECT SUM(ISNULL(idling,0)) FROM @TBL_IdlingStop WHERE IsTripCompleted=1),0)+@FirstStopTime+@SecondStopTime

RETURN @vcStopTime
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetKeyMessages]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetKeyMessages]
(
	@vcUserLan varchar(20),
	@VcKeyString varchar(100)	
)
RETURNS nvarchar(MAX)
AS
BEGIN
	DECLARE @vcMsgs nvarchar(100)
	
	select @vcMsgs = (case when @vcUserLan='LanguageArNew' then message_ar else message_en end) from rvlfSensormessages where message_en = @VcKeyString
	
	RETURN @vcMsgs
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetMaintenanceServiceCategories]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Function [dbo].[rvlf_fn_GetMaintenanceServiceCategories] 
(
	@bigServiceId bigint = NULL
)
RETURNS varchar(max)
AS
BEGIN
   DECLARE @vcServiceCategories varchar(max)
		
   IF(@bigServiceId IS NOT NULL)
   BEGIN
		
		SELECT @vcServiceCategories = ISNULL(@vcServiceCategories + ', ', '')+ msc.ServiceCategoryName
	    FROM rvlfMaintenanceCategoryService mc 
	    INNER JOIN rvlfMaintenanceServiceCategory msc ON msc.ServiceCategoryId = mc.ServiceCategoryId 
	    WHERE mc.ServiceId = @bigServiceId
    
   END
     
   RETURN @vcServiceCategories
END




GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetMaintenanceServices]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[rvlf_fn_GetMaintenanceServices] 
(
	@tiType tinyint,
	@bigServiceCategoryID bigint = NULL,
	@bigServiceDetailsId bigint = NULL
)
RETURNS varchar(max)
AS
BEGIN
   DECLARE @vcServiceNames varchar(max)
		
   IF(@bigServiceCategoryID IS NOT NULL AND @tiType = 0)
   BEGIN
		
		SELECT @vcServiceNames = ISNULL(@vcServiceNames + ', ', '')+ ms.ServiceName
	    FROM rvlfMaintenanceService ms
	    INNER JOIN rvlfMaintenanceCategoryService mc ON mc.ServiceId = ms.ServiceId
	    WHERE mc.ServiceCategoryId = @bigServiceCategoryID
    
   END
   ELSE IF(@bigServiceDetailsId IS NOT NULL AND @tiType = 1)
   BEGIN
   
		SELECT @vcServiceNames = ISNULL(@vcServiceNames + ', ', '')+ ms.ServiceName
	    FROM rvlfMaintenanceServiceDetails sd
	    INNER JOIN rvlfMaintenanceService ms ON ms.ServiceId = sd.ServiceId
	    WHERE sd.ServiceDetailsId = @bigServiceDetailsId
   
   END
   ELSE IF(@bigServiceCategoryID IS NOT NULL AND @tiType = 2)
   BEGIN
		
		SELECT @vcServiceNames = ISNULL(@vcServiceNames + ',', '')+ CONVERT(Varchar(15),ServiceId)
	    FROM rvlfMaintenanceCategoryService 
	    WHERE ServiceCategoryId = @bigServiceCategoryID
    
   END	    

 ELSE IF(@bigServiceCategoryID IS NOT NULL AND @bigServiceDetailsId IS NOT NULL AND @tiType = 3)  -- Here @bigServiceCategoryID refers Plan Id
   BEGIN
   
		SELECT @vcServiceNames = ISNULL(@vcServiceNames + ', ', '')+ ms.ServiceName
	    FROM rvlfMaintenanceService ms  
	    INNER JOIN rvlfMaintenancePlanServices ps ON ps.ServiceId = ms.ServiceId	  
	    WHERE ps.PlanId = @bigServiceCategoryID
	    AND ms.ServiceId not in (Select ServiceId from rvlfMaintenanceServiceDetails Where ServiceDetailsId = @bigServiceDetailsId)
   
   END  
 
 ELSE IF(@bigServiceCategoryID IS NOT NULL AND @tiType = 4) -- Here @bigServiceCategoryID refers Plan Id
   BEGIN
   
		SELECT @vcServiceNames = ISNULL(@vcServiceNames + ',', '')+ CONVERT(VARCHAR(6), ms.ServiceId)
	    FROM rvlfMaintenanceService ms
		INNER JOIN rvlfMaintenancePlanServices ps ON ps.ServiceId = ms.ServiceId
		WHERE ps.PlanId = @bigServiceCategoryID
   
   END   
 ELSE IF(@bigServiceCategoryID IS NOT NULL AND @tiType = 5) -- Here @bigServiceCategoryID refers Plan Id
   BEGIN
   
		SELECT @vcServiceNames = ISNULL(@vcServiceNames + ', ', '')+ ms.ServiceName
	    FROM rvlfMaintenanceService ms
		INNER JOIN rvlfMaintenancePlanServices ps ON ps.ServiceId = ms.ServiceId
		WHERE ps.PlanId = @bigServiceCategoryID
   
   END    
 ELSE IF(@bigServiceDetailsId IS NOT NULL AND @tiType = 6) -- Here @bigServiceDetailsId refers AdhocServiceId
   BEGIN
   
		SELECT @vcServiceNames = ISNULL(@vcServiceNames + ', ', '')+ ms.ServiceName
	    FROM rvlfMaintenanceService ms
		INNER JOIN rvlfAdhocServiceDetails ad ON ad.ServiceId = ms.ServiceId
		WHERE ad.AdhocServiceId = @bigServiceDetailsId
   
   END       
   
   RETURN @vcServiceNames
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_Fn_GetMapItValues]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================          
-- Author:  Vijay          
-- Create date: <Create Date,,>          
-- Description: Get the Mapit values  
-- =============================================          
CREATE FUNCTION [dbo].[rvlf_Fn_GetMapItValues]          
(          
 -- Add the parameters for the function here          
 @vcBoxIds AS INT,          
 @bigQueryingUser AS BIGINT,        
 @FilterCase  VARCHAR(2)        
)          
          
RETURNS  @rvlf_Tbl_ReturnmapItValues TABLE                 
(                
-- Add the column definitions for the TABLE variable here                
 mapItValues VARCHAR(MAX) ,          
 Landmarkvalues VARCHAR(MAX),          
 LandmarkIds VARCHAR(MAX),          
 NotCurPosVeh VARCHAR(MAX)         
)             
AS          
BEGIN          
 -- Fill the table variable with the rows for your result set          
 -- Add the SELECT statement with parameter references here          
           
 --DECLARE @vcMapVal NVARCHAR(MAX)=NULL,@vcLandmarkVal VARCHAR(MAX)=NULL,          
 --@vcLandmarkIds VARCHAR(MAX)=NULL,@vcNotCurPosVeh VARCHAR(MAX)=NULL              
           
 DECLARE @Lang varchar(50);               
  select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser            
             
 --DECLARE THE VARIABLES FOR GET THE TIMEZONE DETAILS                
 DECLARE @SpeedUnit varchar(50),@ConversionFactor numeric (10,2) = 1.0 ,@vcMapVal NVARCHAR(MAX)=NULL,@vcLandmarkVal VARCHAR(MAX)=NULL,                
  @vcLandmarkIds VARCHAR(MAX)=NULL,@vcNotCurPosVeh VARCHAR(MAX)=NULL                     
                 
 SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                    
   @SpeedUnit = CASE WHEN up.Distance = 0 THEN 'MPH' ELSE 'KMPH' END                   
  FROM rvlfUserPreferences up                 
   INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                    
  WHERE UP.UserId  = @bigQueryingUser                   
 -- get the mapit values                
 --SELECT (CAST(MAPVAL AS NVARCHAR(MAX)))+'~&~'                 
 -- FROM (            
           
       
   IF (@FilterCase = 'M')           
   BEGIN        
       
   SELECT @vcMapVal=coalesce(@vcMapVal,'')+(CAST(MAPVAL AS VARCHAR(MAX)))+'~&~'             
  FROM (            
   SELECT( CAST(ISNULL(B.LastLatitude,'') AS VARCHAR)             
     + '~#~' + CAST(ISNULL(B.LastLongitude,'') AS VARCHAR)             
     + '~#~' + CAST(REPLACE(ISNULL(B.LastStreetAddress,'Address is not resolved'),'''','\''')AS NVARCHAR(MAX))      
     + '~#~' + CAST((CASE WHEN B.LastValidDateTime = B.LastStatusDateTime THEN CASE WHEN H.BoxMsgInTypeId IN (2,3,12) THEN '-' ELSE CAST(CAST((B.LastSpeed * @ConversionFactor) as int) as varchar(30)) END ELSE '-' END) AS VARCHAR) + ' ' + CAST(@SpeedUnit AS VARCHAR)             
     + '~#~' + CAST((CASE WHEN LastSpeed = 0 THEN -1 ELSE B.Heading END) AS VARCHAR)          
     + '~#~' + RV.VehicleDescription            
     + '~#~' + (CASE WHEN (SELECT ISNULL(OrgId,0) FROM rvlfOrganizationServiceURL_App WHERE OrgId=B.OrganizationId) <> 0 THEN '2' ELSE  
     CAST(CASE WHEN H.BoxMsgInTypeId = 37 /* Analog (Fuel) Sensor Status - LOW*/ THEN 3              
           WHEN H.BoxMsgInTypeId = 38 /* Analog (Fuel) Sensor Status - MEDIUM*/ THEN 4              
           WHEN H.BoxMsgInTypeId = 39 /* Analog (Fuel) Sensor Status - HIGH */ THEN 5              
           WHEN H.BoxMsgInTypeId = 42 /* Alamr Fuel Drain */ THEN 6      
           WHEN CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1 /* Violation or Alarms */ THEN 7            
           WHEN H.BoxMsgInTypeId = 3 THEN 0          
           WHEN H.BoxMsgInTypeId = 12 THEN 10  /*Sleep Mode*/        
           WHEN H.BoxMsgInTypeId = 24 THEN 9  /*Extended Idling*/        
           WHEN H.BoxMsgInTypeId = 9 THEN /*Idling started and end*/        
    CASE WHEN CAST(SUBSTRING(CustomProp,CHARINDEX(':',CustomProp,LEN('Idling:')+1)+8,CHARINDEX(';',CustomProp,8) - CHARINDEX(':',CustomProp,LEN('Idling:'))-1) AS INT) = 0 THEN 8         
    ELSE 9        
    END        
          WHEN H.BoxMsgInTypeId = 2 THEN           
    CASE WHEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) = 3 THEN         
     CASE WHEN (SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1)) = 'ON' THEN 1         
           ELSE 0 END         
          ELSE 2        
             END         
          ELSE 2 END AS VARCHAR) END)  
     + '~#~' + (dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId, h.MessageInID, h.OriginDateTime))             
     + '~#~' + ISNULL(L.LandmarkName,'-')              
     + '~#~' + ISNULL(DM.DisplayName,'-')             
     + '~#~' + CAST(ISNULL(DM.Photo,'') AS VARCHAR(200))             
     + '~#~' + CAST(ISNULL(dm.Mobileno,'-') AS VARCHAR)             
     + '~#~' + 'Caption_Phno') AS MAPVAL              
    FROM rvlfBoxId B             
     INNER JOIN rvlfMsgInHst h ON B.MessageInId = h.MessageInID              
     INNER JOIN rvlfVehicleAssignment RVA ON RVA.BoxId = B.BoxId       
     INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId     
     INNER JOIN rvlfVehicle RV ON RV.VehicleId =RVA.VehicleId             
     LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID               
     LEFT OUTER JOIN rvlfIButtonMapping BM ON H.BoxId = BM.BoxID               
     --LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId = BM.DriverId             
     LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId in (select Top 1 DriverId from rvlfDriverAssignment where Boxid = B.BoxId ORDER BY AssignmentId)  
    WHERE B.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))            
   ) AS TBL      
       
              
    END        
ELSE  IF (@FilterCase = 'L')        
BEGIN        
--GET THE LANDMARK DETAILS           
 SELECT @vcLandmarkVal=coalesce(@vcLandmarkVal,'')+(CAST(MAPVAL AS VARCHAR(MAX)))+'~&~',@vcLandmarkIds=coalesce(@vcLandmarkIds,'')+(CAST(LandmarkID AS VARCHAR))+','                
  FROM (                
   SELECT(CAST(ISNULL(L.Latitude,'') AS VARCHAR)                 
     + '~#~' + CAST(ISNULL(L.Longitude,'') AS VARCHAR)                 
     + '~#~' + CAST(ISNULL(L.Radius,'') AS VARCHAR)                
     + '~#~' + L.LandmarkName                 
     + '~#~' + L.StreetAddress                
     ) AS MAPVAL,L.LandMarkID                
    FROM rvlfBoxId B                 
     INNER JOIN rvlfMsgInHst h ON B.MessageInId = h.MessageInID                       
     INNER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID                       
    WHERE B.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                
      AND H.LANDMARKID IS NOT NULL                    
   ) AS TBL GROUP BY LandmarkID,MAPVAL                 
END         
ELSE IF (@FilterCase = 'P')        
BEGIN        
 --get the vehicles which have not the cureent possition                  
 SELECT @vcNotCurPosVeh=coalesce(@vcNotCurPosVeh,'')+(CAST(MAPVAL AS VARCHAR(MAX)))+'\n'                 
  FROM (                
   SELECT  rv.VehicleDescription AS MAPVAL                
    FROM rvlfBoxId B                  
     INNER JOIN rvlfVehicleAssignment RVA ON RVA.BoxId = B.BoxId                 
     INNER JOIN rvlfVehicle RV ON RV.VehicleId =RVA.VehicleId                        
    WHERE B.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                
      AND B.LastValidDateTime <> B.LastStatusDateTime                     
   ) AS TBL             
END        
   INSERT INTO @rvlf_Tbl_ReturnmapItValues          
    SELECT @vcMapVal as Mapvalues,ISNULL(@vcLandmarkVal,'') as Landmarkvalues,ISNULL(@vcLandmarkIds,'') as LandmarkIds,ISNULL(@vcNotCurPosVeh,'') as NotCurPosVeh                 
 RETURN           
END 

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_Fn_GetMapItValues_ADOR]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_Fn_GetMapItValues_ADOR]                  
(                  
 -- Add the parameters for the function here                  
 @vcBoxIds			AS INT,                  
 @bigQueryingUser	AS BIGINT,                
 @FilterCase		VARCHAR(2),
 @FleetID			AS BIGINT = NULL,
 @MessageInID	uniqueidentifier =null
)                  
                  
RETURNS  @rvlf_Tbl_ReturnmapItValues TABLE                         
(                        
-- Add the column definitions for the TABLE variable here    
 mapItValues NVARCHAR(MAX) ,                  
 Landmarkvalues NVARCHAR(MAX),                  
 LandmarkIds VARCHAR(MAX),                  
 NotCurPosVeh VARCHAR(MAX)                 
)                     
AS                  
BEGIN                  
	-- Fill the table variable with the rows for your result set                  
	-- Add the SELECT statement with parameter references here 
                   
	DECLARE @Lang varchar(50);                       
	SELECT @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser                    
                     
	--DECLARE THE VARIABLES FOR GET THE TIMEZONE DETAILS                        
	DECLARE @SpeedUnit varchar(50),@ConversionFactor numeric (10,2) = 1.0 ,@vcMapVal NVARCHAR(MAX)=NULL,@vcLandmarkVal VARCHAR(MAX)=NULL,                        
			@vcLandmarkIds VARCHAR(MAX)=NULL,@vcNotCurPosVeh VARCHAR(MAX)=NULL                             
                         
	SELECT	@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                            
			@SpeedUnit = CASE WHEN up.Distance = 0 THEN 'MPH' ELSE 'KMPH' END                           
	FROM rvlfUserPreferences up                         
	INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                            
	WHERE UP.UserId  = @bigQueryingUser                                          
 
 Declare @ESPstatus table (Boxid bigint,ESPstatus tinyint)
 Insert into @ESPstatus 
 select EquipmentId,sum(cast(isalarm as tinyint)) from adrControllerMaster group by EquipmentId  

IF (@FilterCase = 'M')                   
BEGIN
	 
    -- removed ~&~ for issue mapit not plotted foe more than 1 vehicle in monitor (~&~ added page itself)24-dec-14.    
   SELECT @vcMapVal=coalesce(@vcMapVal,'')+(CAST(MAPVAL AS NVARCHAR(MAX))) + '~&~'    
   --SELECT @vcMapVal=coalesce(@vcMapVal,'')+(CAST(MAPVAL AS NVARCHAR(MAX)))    
   FROM (                    
  
	SELECT( CAST(ISNULL(B.LastLatitude,'') AS VARCHAR)                     
     + '~#~' + CAST(ISNULL(B.LastLongitude,'') AS VARCHAR)                     
     + '~#~' + CAST(ISNULL((Case WHEN @Lang='LanguageArNew' THEN ISNULL(B.LastStreetAddress_AR,B.LastStreetAddress) ELSE B.LastStreetAddress END),'Address is not resolved')AS NVARCHAR(MAX))              
     + '~#~' + Md.EquipmentName                    
     + '~#~' + (dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, h.MessageInID, h.OriginDateTime,@Lang))                     
	 + '~#~' + ISNULL((SELECT FleetName FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From rvlfFleetVehicles Where VehicleId = MD.VehicleId
  and FleetId <> 176)), 'Site Not Assigned')
	 + '~#~' + '-'
	 + '~#~' + '-'
	 + '~#~' + (SELECT CAST(COUNT(ControllerId) AS varchar) FROM adrControllerMaster Where EquipmentId = MD.BoxId AND Isdeleted = 0)
	 + '~#~' + VT.VehicleTypeName
	 + '~#~' +	CASE WHEN DATEDIFF(HH,B.LastStatusDateTime,GETUTCDATE()) > 1 THEN 'Offline' when ESPstatus>0 THEN 'Alarm' ELSE 'Online' END	
     + '~#~' + B.WeatherInfo
	 + '~#~' + C.CustomerName
	 ) AS MAPVAL
    FROM rvlfBoxId B                     
    INNER JOIN rvlfMsgInHst h ON B.MessageInId = h.MessageInID --AND B.LastLatitude <> 0 AND B.LastValidDateTime = B.LastStatusDateTime                       
   --INNER JOIN rvlfVehicleAssignment RVA ON RVA.BoxId = B.BoxId 
    inner join @ESPstatus ES on b.BoxId=es.Boxid    
   INNER JOIN rvlfMAKDevices MD ON B.BoxId=MD.BoxId             
    INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId             
   -- INNER JOIN rvlfVehicle RV ON RV.VehicleId = RVA.VehicleId                     
	INNER JOIN rvlfFleetVehicles FV ON FV.VehicleId = md.VehicleId --and FV.FleetId <> 176
	INNER JOIN rvlfFleet F ON F.FleetId = FV.FleetId 	
	---LEFT OUTER JOIN rvlfMakSubProducts MSP on MSP.SubtypeId=MD.SubTypeId                                           
	LEFT OUTER JOIN rvlfVehicleType VT On Md.SubTypeId = VT.VehicleTypeId
	LEFT OUTER JOIN rvlfCustomers C On MD.CustomerId = C.CustomerId
    WHERE B.BoxId =@vcBoxIds and h.MessageInID=@MessageInID and f.FleetId=@FleetID
	--IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,',') WHERE FieldValue Not IN (Select BoxID From @tblAssignedEquips))
    ) AS TBL
END
	
ELSE  IF (@FilterCase = 'L')                
BEGIN                
--GET THE LANDMARK DETAILS                   
	SELECT	@vcLandmarkVal=coalesce(@vcLandmarkVal,'')+(CAST(MAPVAL AS VARCHAR(MAX)))+'~&~',
			@vcLandmarkIds=coalesce(@vcLandmarkIds,'')+(CAST(LandmarkID AS VARCHAR))+','                        
	FROM (SELECT(CAST(ISNULL(L.Latitude,'') AS VARCHAR)                         
			+ '~#~' + CAST(ISNULL(L.Longitude,'') AS VARCHAR)                         
			+ '~#~' + CAST(ISNULL(L.Radius,'') AS VARCHAR)            
			+ '~#~' + L.LandmarkName                         
			+ '~#~' + L.StreetAddress) AS MAPVAL,L.LandMarkID           
			FROM rvlfBoxId B                         
			INNER JOIN rvlfMsgInHst h ON B.MessageInId = h.MessageInID                               
			INNER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID                               
			WHERE B.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                        
			AND H.LANDMARKID IS NOT NULL) 
	AS TBL GROUP BY LandmarkID,MAPVAL                         
END

ELSE IF (@FilterCase = 'P')                
BEGIN                
 --get the vehicles which have not the cureent possition                          
	SELECT @vcNotCurPosVeh=coalesce(@vcNotCurPosVeh,'')+(CAST(MAPVAL AS VARCHAR(MAX)))+'\n'                         
	FROM	(SELECT  rv.VehicleDescription AS MAPVAL                        
			FROM rvlfBoxId B    
			INNER JOIN rvlfVehicleAssignment RVA ON RVA.BoxId = B.BoxId                         
			INNER JOIN rvlfVehicle RV ON RV.VehicleId =RVA.VehicleId                                
			WHERE B.BoxId =@vcBoxIds --IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                        
			AND B.LastValidDateTime <> B.LastStatusDateTime) 
	AS TBL                     
END
                
INSERT INTO @rvlf_Tbl_ReturnmapItValues                  
SELECT @vcMapVal as Mapvalues,ISNULL(@vcLandmarkVal,'') as Landmarkvalues,ISNULL(@vcLandmarkIds,'') as LandmarkIds,    
ISNULL(@vcNotCurPosVeh,'') as NotCurPosVeh                         
 
RETURN

END     
    
    

    
    
	
GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_Fn_GetMapItValues_New]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================                  
-- Author:  Vijay                  
-- Create date: <Create Date,,>                  
-- Description: Get the Mapit values          
-- =============================================                  
CREATE FUNCTION [dbo].[rvlf_Fn_GetMapItValues_New]                  
(                  
 -- Add the parameters for the function here                  
 @vcBoxIds			AS INT,                  
 @bigQueryingUser	AS BIGINT,                
 @FilterCase		VARCHAR(2),
 @FleetID			AS BIGINT = NULL
)                  
                  
RETURNS  @rvlf_Tbl_ReturnmapItValues TABLE                         
(                        
-- Add the column definitions for the TABLE variable here    
 mapItValues NVARCHAR(MAX) ,                  
 Landmarkvalues NVARCHAR(MAX),                  
 LandmarkIds VARCHAR(MAX),                  
 NotCurPosVeh VARCHAR(MAX)                 
)                     
AS                  
BEGIN                  
	-- Fill the table variable with the rows for your result set                  
	-- Add the SELECT statement with parameter references here                  
                   
	--DECLARE @vcMapVal NVARCHAR(MAX)=NULL,@vcLandmarkVal VARCHAR(MAX)=NULL,                  
	--@vcLandmarkIds VARCHAR(MAX)=NULL,@vcNotCurPosVeh VARCHAR(MAX)=NULL                      
                   
	DECLARE @Lang varchar(50);                       
	SELECT @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser                    
                     
	--DECLARE THE VARIABLES FOR GET THE TIMEZONE DETAILS                        
	DECLARE @SpeedUnit varchar(50),@ConversionFactor numeric (10,2) = 1.0 ,@vcMapVal NVARCHAR(MAX)=NULL,@vcLandmarkVal VARCHAR(MAX)=NULL,                        
			@vcLandmarkIds VARCHAR(MAX)=NULL,@vcNotCurPosVeh VARCHAR(MAX)=NULL                             
                         
	SELECT	@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                            
			@SpeedUnit = CASE WHEN up.Distance = 0 THEN 'MPH' ELSE 'KMPH' END                           
	FROM rvlfUserPreferences up                         
	INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                            
	WHERE UP.UserId  = @bigQueryingUser                           
 -- get the mapit values                        
 --	SELECT (CAST(MAPVAL AS NVARCHAR(MAX)))+'~&~'                         
 -- FROM (                   
               
IF (@FilterCase = 'M')                   
BEGIN
	--Get the Equipments which are assigned to their respective Sites other than 'All' Site.
	DECLARE @tblAssignedEquips TABLE(BoxID bigint)

	Insert Into @tblAssignedEquips
	Select B.BoxId From rvlfBoxID B
	INNER JOIN rvlfVehicleAssignment RVA ON RVA.BoxId = B.BoxId               
	INNER JOIN rvlfVehicle RV ON RV.VehicleId = RVA.VehicleId                     
	INNER JOIN rvlfFleetVehicles FV ON FV.VehicleId = RV.VehicleId --and FV.FleetId <> 176
	INNER JOIN rvlfFleet F ON F.FleetId = FV.FleetId 
	Where B.ORganizationID = 86
	and FleetName <> 'All'
		
    -- removed ~&~ for issue mapit not plotted foe more than 1 vehicle in monitor (~&~ added page itself)24-dec-14.    
   SELECT @vcMapVal=coalesce(@vcMapVal,'')+(CAST(MAPVAL AS NVARCHAR(MAX))) + '~&~'    
   --SELECT @vcMapVal=coalesce(@vcMapVal,'')+(CAST(MAPVAL AS NVARCHAR(MAX)))    
   FROM (                    
   SELECT( CAST(ISNULL(B.LastLatitude,'') AS VARCHAR)                     
     + '~#~' + CAST(ISNULL(B.LastLongitude,'') AS VARCHAR)                     
     + '~#~' + CAST(ISNULL((Case WHEN @Lang='LanguageArNew' THEN ISNULL(B.LastStreetAddress_AR,B.LastStreetAddress) ELSE B.LastStreetAddress END),
																		'Address is not resolved')AS NVARCHAR(MAX))              
     --+ '~#~' + CAST((CASE WHEN B.LastValidDateTime = B.LastStatusDateTime THEN CASE WHEN H.BoxMsgInTypeId IN (3,2,12) THEN '-' 
					--ELSE CAST(CAST((B.LastSpeed * @ConversionFactor) as int) as varchar(30)) END ELSE '-' END) AS VARCHAR) + ' ' + CAST(@SpeedUnit AS VARCHAR)                     
     --+ '~#~' + CAST((CASE WHEN LastSpeed = 0 THEN -1 ELSE B.Heading END) AS VARCHAR)                  
     + '~#~' + RV.VehicleDescription                    
     --+ '~#~' + CAST(CASE	WHEN H.BoxMsgInTypeId = 37 /* Analog (Fuel) Sensor Status - LOW*/ THEN 3                      
					--		WHEN H.BoxMsgInTypeId = 38 /* Analog (Fuel) Sensor Status - MEDIUM*/ THEN 4                      
					--		WHEN H.BoxMsgInTypeId = 39 /* Analog (Fuel) Sensor Status - HIGH */ THEN 5                      
					--		WHEN H.BoxMsgInTypeId = 42 /* Alamr Fuel Drain */ THEN 6              
					--		WHEN CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1 /* Violation or Alarms */ THEN 7                    
					--		WHEN H.BoxMsgInTypeId = 3 THEN 0                  
					--		WHEN H.BoxMsgInTypeId = 12 THEN 10  /*Sleep Mode*/                
					--		WHEN H.BoxMsgInTypeId = 24 THEN 9  /*Extended Idling*/                
					--		WHEN H.BoxMsgInTypeId = 9 THEN /*Idling started and end*/                
					--									CASE	WHEN	CAST(SUBSTRING(CustomProp,CHARINDEX(':',CustomProp,LEN('Idling:')+1)+8, 
					--													CHARINDEX(';',CustomProp,8) - CHARINDEX(':',CustomProp,LEN('Idling:'))-1) AS INT) = 0 THEN 8                 
					--											ELSE 9 END                
					--		WHEN H.BoxMsgInTypeId = 2 THEN  CASE WHEN	CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,CHARINDEX(';',CustomProp,1)-
					--													CHARINDEX('=',CustomProp)-1) As tinyint) = 3 THEN                 
					--										CASE WHEN	(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,
					--													CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1)) = 'ON' 
					--											THEN 1  ELSE 0 END                 
					--										ELSE 2 END                 
					--		ELSE 2 END AS VARCHAR)
     + '~#~' + (dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, h.MessageInID, h.OriginDateTime,@Lang))                     
     --+ '~#~' + ISNULL(L.LandmarkName,'-')                      
     --+ '~#~' + ISNULL(DM.DisplayName,'-')                     
     --+ '~#~' + REPLACE(CAST(ISNULL(DM.Photo,'') AS VARCHAR(200)),'~','..')
     --+ '~#~' + CAST(ISNULL(dm.Mobileno,'-') AS VARCHAR)                     
     --+ '~#~' +  (Case WHEN @Lang='LanguageArNew' THEN N''*5D' When @Lang='LanguageHindi' THEN N'8		*	0	M		' ELSE 'Contact' END)
	 + '~#~' + ISNULL(F.FleetName, '')
	 + '~#~' + ISNULL(F.PowerPlantRating, '')
	 + '~#~' + ISNULL(F.RatingOfHVREquip, '')
	 + '~#~' + (SELECT CAST(COUNT(ControllerId) AS varchar) FROM adrControllerMaster Where EquipmentId = MD.BoxId AND Isdeleted = 0)
	 + '~#~' + VT.VehicleTypeName
	 + '~#~' +	CASE	WHEN H.CustomProp LIKE '%IsAlarm=1;%' THEN 'Alarm' 
						ELSE (CASE WHEN DATEDIFF(HH,B.LastStatusDateTime,GETUTCDATE()) > 1 THEN 'Offline' ELSE 'Online' END) END	
     --+ '~#~' + MD.EquipmentSrNo
     + '~#~' + B.WeatherInfo
	 + '~#~' + C.CustomerName
	 ) AS MAPVAL
     --+ '~#~' + 'Caption_Phno') AS MAPVAL                      
    FROM rvlfBoxId B                     
    INNER JOIN rvlfMsgInHst h ON B.MessageInId = h.MessageInID --AND B.LastLatitude <> 0 AND B.LastValidDateTime = B.LastStatusDateTime                       
    INNER JOIN rvlfVehicleAssignment RVA ON RVA.BoxId = B.BoxId               
    INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId             
    INNER JOIN rvlfVehicle RV ON RV.VehicleId = RVA.VehicleId                     
	INNER JOIN rvlfFleetVehicles FV ON FV.VehicleId = RV.VehicleId --and FV.FleetId <> 176
	INNER JOIN rvlfFleet F ON F.FleetId = FV.FleetId 
	INNER JOIN rvlfMAKDevices MD ON MD.VehicleId = RV.VehicleId
	---LEFT OUTER JOIN rvlfMakSubProducts MSP on MSP.SubtypeId=MD.SubTypeId                                           
	LEFT OUTER JOIN rvlfVehicleType VT On RV.VehicleTypeId = VT.VehicleTypeId
	LEFT OUTER JOIN rvlfCustomers C On MD.CustomerId = C.CustomerId
    WHERE B.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))
	AND	  F.FleetName <> 'All' --(@FleetID IS NULL OR @FleetID = '' OR (F.FleetId = @FleetID))

	UNION ALL

	SELECT( CAST(ISNULL(B.LastLatitude,'') AS VARCHAR)                     
     + '~#~' + CAST(ISNULL(B.LastLongitude,'') AS VARCHAR)                     
     + '~#~' + CAST(ISNULL((Case WHEN @Lang='LanguageArNew' THEN ISNULL(B.LastStreetAddress_AR,B.LastStreetAddress) ELSE B.LastStreetAddress END),'Address is not resolved')AS NVARCHAR(MAX))              
     + '~#~' + RV.VehicleDescription                    
     + '~#~' + (dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, h.MessageInID, h.OriginDateTime,@Lang))                     
	 + '~#~' + 'Site Not Assigned'
	 + '~#~' + '-'
	 + '~#~' + '-'
	 + '~#~' + (SELECT CAST(COUNT(ControllerId) AS varchar) FROM adrControllerMaster Where EquipmentId = MD.BoxId AND Isdeleted = 0)
	 + '~#~' + VT.VehicleTypeName
	 + '~#~' +	CASE	WHEN H.CustomProp LIKE '%IsAlarm=1;%' THEN 'Alarm' 
						ELSE (CASE WHEN DATEDIFF(HH,B.LastStatusDateTime,GETUTCDATE()) > 1 THEN 'Offline' ELSE 'Online' END) END	
     + '~#~' + B.WeatherInfo
	 + '~#~' + C.CustomerName
	 ) AS MAPVAL
    FROM rvlfBoxId B                     
    INNER JOIN rvlfMsgInHst h ON B.MessageInId = h.MessageInID --AND B.LastLatitude <> 0 AND B.LastValidDateTime = B.LastStatusDateTime                       
    INNER JOIN rvlfVehicleAssignment RVA ON RVA.BoxId = B.BoxId               
    INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId             
    INNER JOIN rvlfVehicle RV ON RV.VehicleId = RVA.VehicleId                     
	INNER JOIN rvlfFleetVehicles FV ON FV.VehicleId = RV.VehicleId --and FV.FleetId <> 176
	INNER JOIN rvlfFleet F ON F.FleetId = FV.FleetId 
	INNER JOIN rvlfMAKDevices MD ON MD.VehicleId = RV.VehicleId
	---LEFT OUTER JOIN rvlfMakSubProducts MSP on MSP.SubtypeId=MD.SubTypeId                                           
	LEFT OUTER JOIN rvlfVehicleType VT On RV.VehicleTypeId = VT.VehicleTypeId
	LEFT OUTER JOIN rvlfCustomers C On MD.CustomerId = C.CustomerId
    WHERE B.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,',') WHERE FieldValue Not IN (Select BoxID From @tblAssignedEquips))
    ) AS TBL
END
	
ELSE  IF (@FilterCase = 'L')                
BEGIN                
--GET THE LANDMARK DETAILS                   
	SELECT	@vcLandmarkVal=coalesce(@vcLandmarkVal,'')+(CAST(MAPVAL AS VARCHAR(MAX)))+'~&~',
			@vcLandmarkIds=coalesce(@vcLandmarkIds,'')+(CAST(LandmarkID AS VARCHAR))+','                        
	FROM (SELECT(CAST(ISNULL(L.Latitude,'') AS VARCHAR)                         
			+ '~#~' + CAST(ISNULL(L.Longitude,'') AS VARCHAR)                         
			+ '~#~' + CAST(ISNULL(L.Radius,'') AS VARCHAR)                        
			+ '~#~' + L.LandmarkName                         
			+ '~#~' + L.StreetAddress) AS MAPVAL,L.LandMarkID                        
			FROM rvlfBoxId B                         
			INNER JOIN rvlfMsgInHst h ON B.MessageInId = h.MessageInID                               
			INNER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID                               
			WHERE B.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                        
			AND H.LANDMARKID IS NOT NULL) 
	AS TBL GROUP BY LandmarkID,MAPVAL                         
END

ELSE IF (@FilterCase = 'P')                
BEGIN                
 --get the vehicles which have not the cureent possition                          
	SELECT @vcNotCurPosVeh=coalesce(@vcNotCurPosVeh,'')+(CAST(MAPVAL AS VARCHAR(MAX)))+'\n'                         
	FROM	(SELECT  rv.VehicleDescription AS MAPVAL                        
			FROM rvlfBoxId B                          
			INNER JOIN rvlfVehicleAssignment RVA ON RVA.BoxId = B.BoxId                         
			INNER JOIN rvlfVehicle RV ON RV.VehicleId =RVA.VehicleId                                
			WHERE B.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                        
			AND B.LastValidDateTime <> B.LastStatusDateTime) 
	AS TBL                     
END
                
INSERT INTO @rvlf_Tbl_ReturnmapItValues                  
SELECT @vcMapVal as Mapvalues,ISNULL(@vcLandmarkVal,'') as Landmarkvalues,ISNULL(@vcLandmarkIds,'') as LandmarkIds,    
ISNULL(@vcNotCurPosVeh,'') as NotCurPosVeh                         
 
RETURN

END     
    
    

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetMDTDetails]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[rvlf_fn_GetMDTDetails]
(
	@tiType tinyint,
	@vcCustomProp varchar(500),
	@tiTypeId int,
	@intBoxID int = null
)
RETURNS varchar(MAX)
AS
BEGIN
	
	DECLARE @vcMsgDetail varchar(MAX)
	
	IF @tiTypeId = 77 -- Get MDT Message
	BEGIN
		
		DECLARE @MDTUserId AS Varchar(50) = ''
		DECLARE @MsgKind AS char(1) = SUBSTRING(@vcCustomProp, CHARINDEX('Msg Kind',@vcCustomProp) + 9, 
					(CHARINDEX('Cancode',@vcCustomProp) - CHARINDEX('Msg Kind',@vcCustomProp) - 10))

		IF @MsgKind = '0'
		BEGIN

		 SET @vcMsgDetail = SUBSTRING(@vcCustomProp, CHARINDEX('Message=',@vcCustomProp) + 0, 
								(CHARINDEX('Group ID',@vcCustomProp) - CHARINDEX('Message=',@vcCustomProp) - 0))
		 SET @vcMsgDetail = REPLACE(REPLACE(@vcMsgDetail, ';', ''), 'Message=', '')
		 
		 SET @MDTUserId = SUBSTRING(@vcCustomProp, CHARINDEX('User ID=',@vcCustomProp) + 8, 
									(CHARINDEX('Message',@vcCustomProp) - CHARINDEX('User ID=',@vcCustomProp) - 9))
		 
		END					
		ELSE 
		BEGIN

		 DECLARE @Cancode AS INT = CONVERT(INT, SUBSTRING(@vcCustomProp, CHARINDEX('Cancode=',@vcCustomProp) + 8, 
								(CHARINDEX('User ID',@vcCustomProp) - CHARINDEX('Cancode=',@vcCustomProp) - 9)))
								
		 SELECT @vcMsgDetail = MsgName FROM rvlfPrecannedMessages WHERE PrecannedMsgId = @Cancode AND IsServerMsg = 0
		 
		 SET @MDTUserId = SUBSTRING(@vcCustomProp, CHARINDEX('User ID=',@vcCustomProp) + 8, 
									(CHARINDEX('Group ID',@vcCustomProp) - CHARINDEX('User ID=',@vcCustomProp) - 9))
		
		END
		
		IF @tiType = 2 -- Get User Name
		BEGIN
		
			SET @vcMsgDetail = ''
			
			IF EXISTS (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUserId )--AND BoxId = @intBoxID
			BEGIN
		
				SET @vcMsgDetail = (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUserId )--AND BoxId = @intBoxID
		
		    END
		
		END
		ELSE IF @tiType = 3 -- Get Message Type
		BEGIN
		
			SET @vcMsgDetail = (CASE WHEN @MsgKind  = '0' THEN 'Free Text' ELSE 'Precanned' END)
		
		END
	
	END
	ELSE IF @tiTypeId = 98
	BEGIN
	
		DECLARE @MDTUsrId AS Varchar(50) = SUBSTRING(@vcCustomProp, CHARINDEX('User ID=',@vcCustomProp) + 8, 
										(CHARINDEX(';;',@vcCustomProp) - CHARINDEX('User ID=',@vcCustomProp) - 8))
										
		SET @vcMsgDetail = ''
		
		IF EXISTS (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUsrId )--AND BoxId = @intBoxID
		BEGIN
		
			SET @MDTUsrId = (SELECT MDTUserName FROM rvlfMDTUserTable WHERE MDTUserId = @MDTUsrId )--AND BoxId = @intBoxID
		    SET @vcMsgDetail = @MDTUsrId
		
		END
			
		IF @tiType = 1 -- Get Login Message
		BEGIN								
		
			SET @vcMsgDetail = @MDTUsrId + ' logged ' + SUBSTRING(@vcCustomProp, CHARINDEX('Login Status=',@vcCustomProp) + 13, 
											(CHARINDEX(';',@vcCustomProp) - CHARINDEX('Login Status=',@vcCustomProp) - 13))
		END

	END
	ELSE
	BEGIN
	
	    SET @vcCustomProp = @vcCustomProp + ','
	    
		DECLARE @Pos INT = CHARINDEX(',',@vcCustomProp,0)
		DECLARE @SPos INT = 1
		DECLARE @Count INT = 0
		DECLARE @CMsgKind TINYINT 
		DECLARE @AlertMsg TINYINT 

		WHILE @Pos > 0
		BEGIN
		    
			IF @Count = 3
			BEGIN
				SET @CMsgKind = CONVERT(TINYINT, SUBSTRING(@vcCustomProp,@SPos,@Pos-@SPos))
			END
		    
			IF @Count = 4 AND @CMsgKind = 1
			BEGIN
				SELECT @vcMsgDetail = MsgName FROM rvlfPrecannedMessages WHERE PrecannedMsgId = CONVERT(TINYINT, SUBSTRING(@vcCustomProp,@SPos,@Pos-@SPos)) AND IsServerMsg = 1
			END
			
			IF @Count = 5
			BEGIN
				SELECT @AlertMsg = CONVERT(TINYINT, SUBSTRING(@vcCustomProp,@SPos,@Pos-@SPos))
			END
		    
			IF @Count = 7 AND @CMsgKind = 0
			BEGIN
				SELECT @vcMsgDetail = SUBSTRING(@vcCustomProp,@SPos,@Pos-@SPos)
			END
		    
			SET @SPos = @Pos + 1
			SET @Pos = CHARINDEX(',',@vcCustomProp,@Pos+1)
			SET @Count = @Count + 1
		END
		
		IF @tiType = 3 -- Get Message Type
		BEGIN
			
			SET @vcMsgDetail = (CASE WHEN @CMsgKind = 0 THEN 'Free Text' ELSE 'Precanned' END) + (CASE WHEN @AlertMsg = 0 THEN '' ELSE ' Alert' END)
		
		END
	
	END

	-- Return the result of the function
	RETURN @vcMsgDetail
	
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetMDTIds]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetMDTIds]
( 
	@bigOrganizationId bigint=null,
	@IsServerMsg bit=null
)
RETURNS TINYINT
/******************************************************************************/
--	Name		:	[rvlf_fn_GetMDTIds]6,1
--	Description	:	Get the MDT precanned message ids based on the message type and organization
--	Author		:	Narayanasamy.V
--	History		:	Initial Version
/******************************************************************************/
BEGIN
	DECLARE @tblIDs TABLE
	(
		Id tinyint identity(1,1),
		MsgId tinyint
	)
	INSERT INTO @tblIDs (MsgId)
		SELECT PrecannedMsgId FROM rvlfPrecannedMessages 
			WHERE IsServerMsg=@IsServerMsg AND OrganizationId =@bigOrganizationId ORDER BY PrecannedMsgId
	
	DECLARE @INC TINYINT=(SELECT ISNULL(MIN(Id),0) FROM @tblIDs)	
	WHILE @INC IS NOT NULL
		BEGIN			
			IF(@INC!=(SELECT MsgId FROM @tblIDs WHERE Id=@INC))			
				BEGIN					
					BREAK
				END
			SELECT @INC =MIN(Id) FROM @tblIDs WHERE Id>@INC 
		END			
	IF(@INC IS NULL OR @INC='')
		SELECT @INC=(COUNT(Id)+1) FROM @tblIDs 
	
RETURN @INC 		
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetMessageOutParam]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetMessageOutParam]
(
	@vcCustomParam varchar(250),
	@tiBoxCmdOutTypeID tinyint,
	@intBoxID varchar(15) = null
)
RETURNS varchar(MAX)
AS
BEGIN
	DECLARE @vcCommandDetail varchar(MAX)
	DECLARE @tiSensorID tinyint
	DECLARE @SecondsToConvert int
	DECLARE @vcBoxCmdOutTypeName varchar(100)
	
	SELECT @vcBoxCmdOutTypeName = BoxCmdOutTypeName FROM rvlfBoxCmdOutType WHERE BoxCmdOutTypeId = @tiBoxCmdOutTypeID
		
	IF @tiBoxCmdOutTypeID in (1,2,19,14)
	BEGIN
		SET @vcCommandDetail = CASE WHEN @tiBoxCmdOutTypeID = 1 THEN dbo.rvlf_fn_GetTimeFromSeconds(cast(@vcCustomParam as int))
				WHEN @tiBoxCmdOutTypeID = 2 THEN @vcCustomParam
				WHEN @tiBoxCmdOutTypeID = 14 THEN @vcCustomParam
				WHEN @tiBoxCmdOutTypeID = 19 THEN @vcCustomParam
			END
	END
	ELSE IF @tiBoxCmdOutTypeID = 3 OR @tiBoxCmdOutTypeID = 27
		BEGIN
		DECLARE @vcSnsMask  varchar(8) = CASE WHEN @tiBoxCmdOutTypeID = 3 THEN REPLACE(@vcCustomParam, ',','')
			ELSE REPLACE (SUBSTRING(@vcCustomParam,1, CHARINDEX(':',@vcCustomParam,1)-1),',','') END
			IF @vcSnsMask IS NOT NULL AND LEN(@vcSnsMask) = 8
				BEGIN
					DECLARE @intIterator int
					DECLARE @vcSensorName varchar(40)
					DECLARE @intIndex int = 8
					SET @vcCommandDetail = '<table calss##sensordetails><tr><td colspan##4>Sensor Details</td></tr>'
					SELECT @intIterator = MIN(SensorId) FROM rvlfSensor
					WHILE @intIterator IS NOT NULL
					BEGIN
						IF EXISTS(select * from rvlfBoxSensorsCfg WHERE BoxId = @intBoxId AND SensorId = @intIterator)
						BEGIN
							SELECT @vcSensorName=SensorName FROM rvlfBoxSensorsCfg
								WHERE SensorId = @intIterator AND BoxId = @intBoxId
							SET @vcCommandDetail = @vcCommandDetail + '<tr><td width=10px></td><td>'+ @vcSensorName +'</td><td>:</td><td>' 
								+ CASE WHEN SUBSTRING(@vcSnsMask,@intIndex,1) = 1 THEN 'Enabled' ELSE 'Disabled' END + '</td></tr>'
						END
						SELECT @intIterator = MIN(SensorId ) FROM rvlfSensor WHERE SensorId > @intIterator --AND BoxId = @intBoxId
							SET @intIndex = @intIndex-1
					END
					SET @vcCommandDetail = @vcCommandDetail + '</table>'--Char(13)
				END
			IF @tiBoxCmdOutTypeID = 27
				BEGIN
					DECLARE @vcOthers varchar(8) = RIGHT(@vcCustomParam, 8)
					SET @vcCommandDetail = @vcCommandDetail+'<table><tr><td colspan=4>Other Parmeters :</td><tr><td width=10px></td><td>Turn Packet</td><td>:</td><td>'
					SET @vcCommandDetail = @vcCommandDetail+CASE WHEN Substring(@vcOthers,1,1)='1' THEN 'Enabled' ELSE 'Disabled' END
					SET @vcCommandDetail = @vcCommandDetail+'</td></tr><tr><td width=10px></td><td>Tamper Packet</td><td>:</td><td>'
					SET @vcCommandDetail = @vcCommandDetail+CASE WHEN Substring(@vcOthers,2,1)='1' THEN 'Enabled' ELSE 'Disabled' END
					SET @vcCommandDetail = @vcCommandDetail+'</td></tr><tr><td width=10px></td><td>Extended Idiling</td><td>:</td><td>'
					SET @vcCommandDetail = @vcCommandDetail+CASE WHEN Substring(@vcOthers,7,1)='1' THEN 'Enabled' ELSE 'Disabled' END
					SET @vcCommandDetail = @vcCommandDetail+'</td></tr><tr><td width=10px></td><td>Auto Arm</td><td>:</td><td>'
					SET @vcCommandDetail = @vcCommandDetail+CASE WHEN Substring(@vcOthers,8,1)='1' THEN 'Enabled' ELSE 'Disabled' END
					SET @vcCommandDetail = @vcCommandDetail+'</td></tr></table>'
				END
		END
	ELSE IF @tiBoxCmdOutTypeID =25 OR @tiBoxCmdOutTypeID =26
		BEGIN
			DECLARE @tblInformation table (Slno int identity (1,1), data varchar(400))
			INSERT INTO  @tblInformation (data) select * from dbo.rvlf_fn_ConvertArrayToTable(@vcCustomParam,',')
			select @vcCommandDetail='<table><tr><td>Address</td><td>:</td><td>'+data+'</td></tr>' from @tblInformation where Slno = 1
			select @vcCommandDetail= @vcCommandDetail+'<tr><td>No of Bytes</td><td>:</td><td>'+data+'</td></tr>' from @tblInformation where Slno = 2
			IF @tiBoxCmdOutTypeID =26 
				BEGIN
					SET @vcCommandDetail= @vcCommandDetail+'</table>'
				END
			ELSE
				BEGIN
					select @vcCommandDetail= @vcCommandDetail+'<tr><td>Data</td><td>:</td><td>'+
						data+'</td></tr></table>' from @tblInformation where Slno = 3
				END
		END
	ELSE IF @tiBoxCmdOutTypeID =28
		BEGIN
			SET @vcCommandDetail = CASE WHEN @vcCustomParam ='True' THEN 'Enabled' ELSE 'Disabled' END
		END
	ELSE IF @tiBoxCmdOutTypeID in (5,6,7,8,9,10,13,15,16,17,18,21) 
		BEGIN
			SET @vcCommandDetail = 'Nothing'
		END
	ELSE IF @tiBoxCmdOutTypeID = 11
	BEGIN
		SELECT @vcCommandDetail = ISNULL(g.GeozoneName, 'Geozone Deleted') FROM rvlfOrganizationGeozone g 
			WHERE g.GeozoneId=CAST(@vcCustomParam AS bigint)
			AND g.OrganizationId = (SELECT v.OrganizationID FROM rvlfVehicle v  INNER JOIN 
				rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID 
				WHERE va.BoxId = @intBoxID)
		SET @vcCommandDetail = ISNULL(@vcCommandDetail, 'Geozone Deleted')
	END
	ELSE IF @tiBoxCmdOutTypeID = 22
	BEGIN
		SELECT @vcCommandDetail = FwName from rvlfFirmware WHERE FwId= 
			CAST(SUBSTRING(@vcCustomParam,CHARINDEX(':', @vcCustomParam, 
				CHARINDEX ('version',@vcCustomParam,1))+1,10) as int)
	END
	ELSE IF @tiBoxCmdOutTypeID = 12
	BEGIN
		DECLARE @vcGeozoneNames varchar(max)
		IF @vcCustomParam = '65535' 
		BEGIN
			SET @vcCommandDetail = 'All'
		END
		ELSE
		BEGIN
			SELECT  @vcGeozoneNames = ISNULL(@vcGeozoneNames + ', ', '') + GeozoneName FROM rvlfOrganizationGeozone 
				WHERE OrganizationId = (SELECT v.OrganizationID FROM rvlfVehicle v  INNER JOIN 
				rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID 
				WHERE va.BoxId = @intBoxID)AND GeozoneId IN
					(SELECT *  from dbo.rvlf_fn_ConvertArrayToTable(@vcCustomParam,','))
			SET @vcCommandDetail = ISNULL(@vcGeozoneNames, 'Geozone Deleted')
		END
	END
	ELSE IF @tiBoxCmdOutTypeID = 23
	BEGIN
		SET @vcCommandDetail = '<table calss##sensordetails><tr><td colspan##3>'+
			'Fuel Settings</td></tr><tr><td>'
			DECLARE @tblFuelParam TABLE (ID int identity(1,1), value varchar(40))
			INSERT INTO @tblFuelParam (value) SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcCustomParam, ',')

			SET @vcCommandDetail = '<table calss##sensordetails><tr><td colspan##3>'+
						'Fuel Settings</td></tr><tr><td>'

			DECLARE @ParamValue int 

			SELECT @ParamValue = CAST(value as int) FROM @tblFuelParam WHERE ID=1
			SET @vcCommandDetail= @vcCommandDetail +'<tr><td>Report Interval</td><td>:</td><td>'
				+ CASE WHEN @ParamValue = 0 THEN 'Disabled' 
					WHEN @ParamValue Between 1 and 29 OR @ParamValue > 86400 THEN 'Reserved' 
					ELSE  dbo.rvlf_fn_GetTimeFromSeconds(@ParamValue) END 

			SELECT @ParamValue = CAST(value as int) FROM @tblFuelParam WHERE ID=2

			SET @vcCommandDetail= @vcCommandDetail + '</td><tr><td>Fuel Drain Rate</td><td>:</td><td>'
					+ CASE WHEN @ParamValue = 0 THEN 'Disabled' 
					WHEN @ParamValue > 100 THEN 'Reserved' 
					ELSE CAST(@ParamValue as varchar(5)) END 

			SELECT @ParamValue = CAST(value as int) from @tblFuelParam WHERE ID=3

			SET @vcCommandDetail= @vcCommandDetail + '</td><tr><td>Fuel Low Level Threshold</td><td>:</td><td>'
					+ CASE WHEN @ParamValue = 0 THEN 'Disabled' 
					WHEN @ParamValue > 100 THEN 'Reserved' 
					ELSE CAST(@ParamValue as varchar(5)) END 

			SELECT @ParamValue = CAST(value as int) from @tblFuelParam WHERE ID=4
			SET @vcCommandDetail= @vcCommandDetail + '</td><tr><td>Fuel High Level Threshold</td><td>:</td><td>'
					+ CASE WHEN @ParamValue = 0 THEN 'Disabled' 
					WHEN @ParamValue > 100 THEN 'Reserved' 
					ELSE CAST(@ParamValue as varchar(5)) END 
		SET @vcCommandDetail= @vcCommandDetail + '</td></tr></table>'

	END
	ELSE IF @tiBoxCmdOutTypeID = 29
		BEGIN
			SET @vcCommandDetail= @vcCustomParam + ' hr(s).'
		END
	ELSE IF @tiBoxCmdOutTypeID = 29
		BEGIN
			SET @vcCommandDetail= @vcCustomParam + ' hr(s).'
		END
	ELSE IF @tiBoxCmdOutTypeID = 30
		BEGIN
			-- Extract middle two values as the other settings 
			SET @vcCommandDetail= '<table><tr><td>Sleep Time</td><td>:</td><td>'+LEFT(@vcCustomParam,2) + ' hr(s)</td></tr><td>Wakeup Time</td><td>:</td><td>'
				+RIGHT(@vcCustomParam,2) + ' hr(s)</td></tr></table>'
		END
	ELSE IF @tiBoxCmdOutTypeID = 39 -- Send MDT Message to Device
		BEGIN
			DECLARE @tblParam TABLE (ID int identity(1,1), value varchar(200))
			INSERT INTO @tblParam (value) SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcCustomParam, ',')

			DECLARE @Msg AS Varchar(200) = ''
			SET @vcCommandDetail = '<table>'

			IF EXISTS (SELECT value FROM @tblParam WHERE ID = 4 AND value = 0)
			BEGIN

				SELECT @Msg = value FROM @tblParam WHERE ID = 8
				SET @vcCommandDetail = @vcCommandDetail + '<tr><td width="100px">Message Kind</td><td width="10px"> : </td><td>Free Text</td></tr>'
							
			END
			ELSE
			BEGIN

				DECLARE @CannedId AS Varchar(2) = (SELECT value FROM @tblParam WHERE ID = 5)
				SELECT @Msg = MsgName FROM rvlfPrecannedMessages WHERE PrecannedMsgId = CONVERT(TINYINT, @CannedId) AND IsServerMsg = 1
				SET @vcCommandDetail = @vcCommandDetail + '<tr><td>Message Kind</td><td> : </td><td>Precanned</td></tr>'

			END

			IF EXISTS (SELECT value FROM @tblParam WHERE ID = 6 AND value = 1)
			BEGIN

				SET @vcCommandDetail = @vcCommandDetail + '<tr><td>Alert Message</td><td> : </td><td>Yes</td></tr>'

			END
			ELSE
			BEGIN

				SET @vcCommandDetail = @vcCommandDetail + '<tr><td>Alert Message</td><td>:</td><td>No</td></tr>'

			END

			SET @vcCommandDetail = @vcCommandDetail + '<tr><td>Server Message</td><td>:</td><td>'+ @Msg + '</td></tr></table>'
		END
	ELSE
	BEGIN
		SET @vcCommandDetail = 'Nothing'
	END
	-- Return the result of the function
	RETURN @vcCommandDetail
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetModulesOperations]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[rvlf_fn_GetModulesOperations] 
(
	@bigintPackageID bigint = NULL,
	@bigintUserGroupId bigint = NULL, 
	@bitIsModule bit
)
RETURNS varchar(max)
AS
BEGIN
	DECLARE @vcModuleID varchar(max)
		IF( @bitIsModule = 1)
			BEGIN
			   
			   DECLARE @tblModuleList TABLE (ModuleID bigint)
			   
			   IF(@bigintPackageID IS NOT NULL AND @bigintPackageID > 0)
			   BEGIN
					
					INSERT INTO @tblModuleList 
						SELECT distinct ModuleID FROM rvlfPackageOperations 
							WHERE PackageId = @bigintPackageID AND
							ModuleID NOT IN (SELECT ParentModuleID FROM rvlfModule WHERE ParentModuleID IS NOT NULL)
						SELECT @vcModuleID = ISNULL(@vcModuleID + ',', '')+ 
						CAST(ModuleID as Varchar) FROM @tblModuleList
			    END
			    
			   IF(@bigintUserGroupId IS NOT NULL AND @bigintUserGroupId > 0)
			   BEGIN
					
					INSERT INTO @tblModuleList 
						SELECT distinct ModuleID FROM rvlfUserGroupSecurity 
							WHERE UserGroupId = @bigintUserGroupId AND
							ModuleID NOT IN (SELECT ParentModuleID FROM rvlfModule WHERE ParentModuleID IS NOT NULL)
						SELECT @vcModuleID = ISNULL(@vcModuleID + ',', '')+ 
						CAST(ModuleID as Varchar) FROM @tblModuleList
			    
			    END
			END
		ELSE
			BEGIN
			
			 IF(@bigintPackageID IS NOT NULL AND @bigintPackageID > 0)
			 BEGIN
			
				SELECT @vcModuleID = ISNULL(@vcModuleID + ',', '')+ 
					CAST(OperationID as Varchar) FROM rvlfPackageOperations 
				WHERE PackageId = @bigintPackageID and OperationId IS NOT NULL
					
		      END
		      
		       IF(@bigintUserGroupId IS NOT NULL AND @bigintUserGroupId > 0)
			   BEGIN
			   
					SELECT @vcModuleID = ISNULL(@vcModuleID + ',', '')+ 
						CAST(OperationTypeId as Varchar) FROM rvlfUserGroupSecurity 
					WHERE UserGroupId = @bigintUserGroupId and OperationTypeId IS NOT NULL
			   
			   END
			END
	RETURN @vcModuleID
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetNotificationsList]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[rvlf_fn_GetNotificationsList]    
(    
 @tiNotificationType tinyint,    
 @bigTypeID bigint,    
 @bitIsEmail bit = 1,    
 @bitIsID bit = 1,    
 @bitUserName bit =0    
)    
/******************************************************************************/    
-- Name  : rvlf_fn_GetNotificationsList  5, 1644, 1,0,1  
-- Description : To get the list of users who has to be notified,    
-- Author  : M. Jebamalai Jaya Chitra.    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 17-Sep-2009 MJJC Created Intial Version     
/******************************************************************************/    
RETURNS varchar(max)    
AS    
BEGIN    
 DECLARE @vcUsersList VARCHAR(max) = null    
 /******************** Returns the Email / SMS list of user IDs ********************/    
 IF @bitIsEmail = 1 and @bitIsID = 1     
 BEGIN    
  SELECT @vcUsersList = ISNULL(@vcUsersList + ',','') + CAST(n.UserID as varchar)    
   FROM rvlfNotificationList n INNER JOIN      
    rvlfUser u ON n.UserID=u.UserId AND u.IsHidden=0    
    WHERE n.NotificationType = @tiNotificationType and n.TypeID = @bigTypeID and     
    n.Email = 1 AND (u.IsActive = 1 OR ((@tiNotificationType BETWEEN 7 AND 8) AND u.IsRegisteredUser = 0))    
 END    
 ELSE IF @bitIsEmail = 0 and @bitIsID = 1     
 BEGIN    
  SELECT @vcUsersList = ISNULL(@vcUsersList + ',','') + CAST(n.UserID as varchar)    
   FROM rvlfNotificationList n INNER JOIN      
    rvlfUser u ON n.UserID=u.UserId AND u.IsHidden=0     
    WHERE n.NotificationType = @tiNotificationType and n.TypeID = @bigTypeID and     
    n.SMS = 1 AND (u.IsActive = 1 OR ((@tiNotificationType BETWEEN 7 AND 8) AND u.IsRegisteredUser = 0))    
 END    
 /******************** Returns the Email / SMS list of email ID or mobile no ********************/    
 ELSE IF @bitIsEmail = 1 and @bitIsID = 0 and @bitUserName = 0    
 BEGIN    
  SELECT @vcUsersList = ISNULL(@vcUsersList + ';','') + u.Email    
   FROM rvlfNotificationList n    
    INNER JOIN rvlfUser u On n.UserID=u.UserId AND u.IsHidden=0
    WHERE n.NotificationType = @tiNotificationType and n.TypeID = @bigTypeID and     
    n.Email = 1 AND (u.IsActive = 1 OR ((@tiNotificationType BETWEEN 7 AND 8) AND u.IsRegisteredUser = 0)) order by username asc    
        
 END    
 ELSE IF @bitIsEmail = 0 and @bitIsID = 0 and @bitUserName = 0    
 BEGIN    
  SELECT @vcUsersList = ISNULL(@vcUsersList + ';','') + u.MobileNo    
   FROM rvlfNotificationList n    
    INNER JOIN rvlfUser u On n.UserID=u.UserId AND u.IsHidden=0   
    WHERE n.NotificationType = @tiNotificationType and n.TypeID = @bigTypeID and     
    n.SMS = 1 AND (u.IsActive = 1 OR ((@tiNotificationType BETWEEN 7 AND 8) AND u.IsRegisteredUser = 0)) order by username asc    
 END    
     
 /******************** Returns the Email / SMS list of user names ********************/    
 ELSE IF @bitIsEmail = 1 and @bitUserName = 1    
 BEGIN    
  SELECT @vcUsersList = ISNULL(@vcUsersList + ',','') + u.userName    
   FROM rvlfNotificationList n    
    INNER JOIN rvlfUser u On n.UserID=u.UserId AND u.IsHidden=0   
    WHERE n.NotificationType = @tiNotificationType and n.TypeID = @bigTypeID and     
    n.Email = 1 AND (u.IsActive = 1 OR ((@tiNotificationType BETWEEN 7 AND 8) AND u.IsRegisteredUser = 0)) order by username asc    
        
 END    
 ELSE IF @bitIsEmail = 0 and @bitUserName = 1    
 BEGIN    
  SELECT @vcUsersList = ISNULL(@vcUsersList + ',','') + u.username    
   FROM rvlfNotificationList n    
    INNER JOIN rvlfUser u On n.UserID=u.UserId AND u.IsHidden=0 
    WHERE n.NotificationType = @tiNotificationType and n.TypeID = @bigTypeID and     
    n.SMS = 1 AND (u.IsActive = 1 OR ((@tiNotificationType BETWEEN 7 AND 8) AND u.IsRegisteredUser = 0)) order by username asc    
 END    
 RETURN @vcUsersList    
END    
    
--SELECT dbo.rvlf_fn_GetNotificationsList(3,7,1,0,1)    

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetParamValue]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetParamValue]      
(           
 @vcCustomProp VARCHAR(MAX)=null,        
 @selectedVal VARCHAR(MAX)=null        
)      
RETURNS varchar(50)      
AS      
BEGIN      
        
 DECLARE @ParamValue varchar(150)      
 DECLARE @tblSelectedParameters TABLE (Id INT, ParameterName VARCHAR(150))        
 INSERT INTO @tblSelectedParameters        
 SELECT [Identity],FieldValue FROM dbo.rvlf_fn_ConvertArrayToTableWithIdentity(@selectedVal,',')      
       
 DECLARE @alarm VARCHAR(1500)        
 DECLARE @fault VARCHAR(1500)        
 --SELECT @alarm=REPLACE(REPLACE(FieldValue,'Alarm_Condition=',''),':true,',',')        
 SELECT @alarm=REPLACE(FieldValue,'Alarm_Condition=','')  
 FROM dbo.rvlf_fn_ConvertArrayToTable(@vcCustomProp,';') WHERE FieldValue LIKE 'Alarm_Condition%'        
 SELECT @fault=REPLACE(FieldValue,'Fault_Condition=','')  
 FROM dbo.rvlf_fn_ConvertArrayToTable(@vcCustomProp,';') WHERE FieldValue LIKE 'Fault_Condition%'      
        
 SELECT @ParamValue=Col.Value FROM @tblSelectedParameters tp INNER JOIN        
 (SELECT       
 CASE WHEN CHARINDEX('=',ABC.AlarmFaultDescription,0) = 0 THEN ABC.AlarmFaultDescription ELSE        
 SUBSTRING(ABC.AlarmFaultDescription,1,(CHARINDEX('=',ABC.AlarmFaultDescription,0)-1)) END AS DescText,       
 CASE WHEN CHARINDEX('=',ABC.AlarmFaultDescription,0) = 0 THEN 'false' ELSE        
 SUBSTRING(ABC.AlarmFaultDescription,(CHARINDEX('=',ABC.AlarmFaultDescription,0)+1),         
 (LEN(ABC.AlarmFaultDescription) - (CHARINDEX('=',ABC.AlarmFaultDescription,0)))) END AS Value      
 FROM      
 (SELECT [Identity],FieldValue AS  AlarmFaultDescription FROM dbo.rvlf_fn_ConvertArrayToTableWithIdentity(@vcCustomProp,';')       
 WHERE CHARINDEX('Fault_Condition=[',FieldValue,0)<>1 and CHARINDEX('Alarm_Condition=[',FieldValue,0)<>1        
 UNION ALL       
 SELECT [Identity],REPLACE(REPLACE(FieldValue,']',''),':','=')         
 AS AlarmFaultDescription FROM dbo.rvlf_fn_ConvertArrayToTableWithIdentity(REPLACE(@alarm+','+@fault,'[',''),',')) ABC) Col        
 ON Col.DescText=tp.ParameterName        
         
 RETURN @ParamValue      
END 

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetParamValueWithIndex]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetParamValueWithIndex]              
(              
@CustomProp varchar(max),          
@StringName Varchar(50),          
@Separator char(1)          
)              
RETURNS varchar(max)              
AS              
BEGIN              
  
IF(LEN(@CustomProp)> 0 AND RIGHT(@CustomProp, 1) <> ';')  
BEGIN  
SET @CustomProp = @CustomProp+';'  
END  
     
 DECLARE @vcduration varchar(max)     
 if(@Separator is null)    
 begin    
 Set @vcduration = case when CHARINDEX(@StringName,@CustomProp,1)!=0 then                    
 SUBSTRING(@CustomProp,CHARINDEX(@StringName,@CustomProp,1)+len(@StringName),((CHARINDEX(@StringName,@CustomProp,1)+len(@StringName)))) else null end     
 end    
 else    
 begin           
 Set @vcduration = case when CHARINDEX(@StringName,@CustomProp,1)!=0 then                    
 SUBSTRING(@CustomProp,CHARINDEX(@StringName,@CustomProp,1)+len(@StringName),(CHARINDEX(@Separator,@CustomProp,CHARINDEX(@StringName,@CustomProp,1))-(CHARINDEX(@StringName,@CustomProp,1)+len(@StringName)))) else null end            
      end           
 RETURN @vcduration              
END   
  

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetParentChild]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
      
-- =============================================      
-- Author:  Vijay.N      
-- Create date: 8-Jun-2012      
-- Description: Get the child id and the parent id      
-- =============================================      
CREATE FUNCTION [dbo].[rvlf_fn_GetParentChild]      
(      
 -- Add the parameters for the function here      
 --@UserGroupName varchar(250),       
 @parent_id int      
)      
RETURNS       
@rvlf_Tbl_ReturnParentChild TABLE       
(      
-- Add the column definitions for the TABLE variable here      
ParentChildId int null      
)      
AS      
BEGIN      
      
--declare @UserGroupId as int      
      
--set @UserGroupId=(select GroupId from TA_Tbl_UserGroup where groupName=@UserGroupName and IsDeleted=0)       
      
-- Fill the table variable with the rows for your result set      
if(@parent_id<>0)      
 BEGIN      
   declare @rvlf_Tbl_ParentChild TABLE       
   (      
    -- Add the column definitions for the TABLE variable here      
   ID int identity(1,1) NOT NULL,      
   ParentChildId int null,      
   tier_cnt int NULL,      
   lineage_id varchar(50)      
   )        
         
   /* declare our tier cnt integer, and set it to two (for the number of tiers existing in the temp tabel for for our Nth level loop */      
   Declare @tier as int      
   SET @tier = 2      
      
   /* Let's build the root level This inserts the root level into the temp table */      
   INSERT INTO @rvlf_Tbl_ParentChild (ParentChildId,tier_cnt,lineage_id)      
   VALUES(@parent_id,1,'1')      
      
   /*      
   Now we must go get for first batch of children (if there are any)      
   */      
   INSERT INTO @rvlf_Tbl_ParentChild      
   Select Fleetid,2,'1' from rvlfParentChildFleetRelation where parentFleetid = @parent_id      
      
   /*      
   Now comes the magic- believe it or not. We need to stamp our newly added children with their genetic code, so to speak. Each line item is given a map back to its the top level parent via the lineage_id      
   */      
      
   UPDATE @rvlf_Tbl_ParentChild set lineage_id = lineage_id+LTRIM(STR(ID)) WHERE len(lineage_id) < tier_cnt      
      
   /*Now the table is initalized and ready for the Nth level iterations. So we start a while loop using the SQL Server's @@rowcount (i'm not sure what this variable is called in other platforms but I'm sure a rows affected variable should be available) . 
  
    
We also have our @tier int set to 2 (we've added two other tiers already, so that's the current tier).*/      
      
   WHILE @@rowcount > 0      
   BEGIN      
   SET @tier = @tier+1      
   /*Go get children nodes for the next tier that are not already accounted for */      
         
   INSERT INTO @rvlf_Tbl_ParentChild (ParentChildId,tier_cnt,lineage_id)      
   SELECT Fleetid, @tier,(select lineage_id from @rvlf_Tbl_ParentChild where ParentChildId = parentFleetid)      
   FROM rvlfParentChildFleetRelation         
   WHERE parentFleetid IN (select ParentChildId from @rvlf_Tbl_ParentChild)      
   AND Fleetid NOT in (select ParentChildId from @rvlf_Tbl_ParentChild)         
      
   /* Now stamp the lineage ID with last numeral, the ID field asigned to the new nodes */      
   UPDATE @rvlf_Tbl_ParentChild set lineage_id = lineage_id+LTRIM(STR(ID)) WHERE len(lineage_id) < tier_cnt      
   END      
      
   insert into @rvlf_Tbl_ReturnParentChild      
   select PC.ParentChildId from @rvlf_Tbl_ParentChild PC      
         
 END      
 RETURN       
END 

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetRouteDetails]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================                
-- Author:  Vijay N              
-- Create date: 5-Jul-2012              
-- Description: To the vehicle route deviation report(landmarkskipping).              
-- =============================================                
CREATE FUNCTION [dbo].[rvlf_fn_GetRouteDetails]                
(                 
 -- Add the parameters for the function here                
@BoxId varchar(MAX),                    
@startdate as datetime,                    
@enddate datetime,                    
@bigQueryingUser bigint = 0,          
@Type varchar(1) = 'L'               
)                
RETURNS @rvlfHistory TABLE                 
(                
--messageinid uniqueidentifier,                
deviceid BIGINT,                
latitude DECIMAL(10,6),                
longitude DECIMAL(10,6),                
[timestamp] DATETIME,                
--datetimereceived DATETIME,                
vehicledescription NVARCHAR(MAX),                
--timestampdisp DATETIME ,                
LandMarkId BIGINT,              
LandMarkname NVARCHAR(MAX),              
vehicleId BIGINT,              
StreetAddress NVARCHAR(MAX),              
Odometer BIGINT              
)                
AS                
BEGIN                 
                
                
DECLARE @TblTemp AS TABLE              
(              
[Rows] INT  IDENTITY PRIMARY KEY,                
messageinid uniqueidentifier,                
deviceid BIGINT,                
latitude DECIMAL(10,6),                
longitude DECIMAL(10,6),                
[timestamp] DATETIME,                
--datetimereceived DATETIME,                
vehicledescription NVARCHAR(MAX),                
--timestampdisp DATETIME ,                
LandMarkId BIGINT,              
vehicleId BIGINT,              
StreetAddress NVARCHAR(MAX),              
Odometer BIGINT              
 )               
 ------- Included by Kumuthini on 16-July-09 ---------------------                    
declare @Lang varchar(50)                       
select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser                    
                      
DECLARE @HoursToBeAdded INT = 0                    
DECLARE @MinsToBeAdded INT = 0                    
DECLARE @Distance varchar(20)                    
DECLARE @bigOrganizationID  bigint                     
DECLARE @DefaultDateFormat INT = 0                    
                     
DECLARE @ConversionFactor numeric (10,2) = 1.0                    
                     
SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                    
     @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                    
     @Distance = CASE WHEN up.Distance = 0 THEN 'MPH' ELSE 'KMPH' END,                    
     @bigOrganizationID = u.OrganizationId,                    
     @DefaultDateFormat=(case when  ISNULL(up.DefaultDateFormat,0)=0 then 107 else up.DefaultDateFormat end)                    
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz                    
  ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser                    
  INNER JOIN rvlfUser u ON u.UserId = up.UserId                    
          
              
RETURN                  
END 

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetScrollingAlarmDetails]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetScrollingAlarmDetails]
(
	@vcAlarmDesc varchar(250),
	@tiBoxMsgInTypeID tinyint,
	@intBoxID int = null
)
RETURNS varchar(MAX)
AS
BEGIN
	DECLARE @vcAlarmDetail varchar(MAX)
	
	SELECT @vcAlarmDetail = g.GeozoneName FROM rvlfOrganizationGeozone g INNER JOIN rvlfVehicle v 
		ON g.OrganizationId=v.OrganizationId INNER JOIN rvlfVehicleAssignment va ON 
			v.VehicleID = va.VehicleID 
			--INNER JOIN rvlfVehicleGeozone vg ON vg.VehicleID = v.VehicleID AND 	vg.GeozoneNo = g.GeozoneNo
		WHERE BoxId = @intBoxID and GeozoneId = --CAST(@vcAlarmDesc as bigint)
		(CAST( @vcAlarmDesc as bigint)) 
	
	SET @vcAlarmDetail = ISNULL(@vcAlarmDetail,'Geozone Deleted')
	SET @vcAlarmDetail = '<span title=''' + @vcAlarmDetail + ' ' + 
	                     CASE WHEN @tiBoxMsgInTypeID = 5 THEN ' - In' ELSE ' - Out' END + '''>' +
	                        CASE WHEN LEN(@vcAlarmDetail) <= 20 THEN @vcAlarmDetail
	                             ELSE LEFT(@vcAlarmDetail, 20) + '...' END 
	                        + ' ' + CASE WHEN @tiBoxMsgInTypeID = 5 THEN ' - In' ELSE ' - Out' END
                         
	-- Return the result of the function
	RETURN @vcAlarmDetail
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetSensorMaskInformation]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetSensorMaskInformation]
(
	@vcSnsMask varchar(8),
	@intBoxID int
)
RETURNS varchar(800)
AS
BEGIN
	DECLARE @vcSensorMask varchar(800)
	
	IF @vcSnsMask IS NOT NULL AND LEN(@vcSnsMask) = 8
	BEGIN
		DECLARE @intIterator int
		DECLARE @vcSensorName varchar(40)
		DECLARE @vcActionOn varchar(40)
		DECLARE @vcActionOff varchar(40)
		DECLARE @intIndex int = 8
		SET @vcSensorMask = '<table width=''100%''>'		
		SELECT @intIterator = MIN(SensorId) FROM rvlfSensor
		WHILE @intIterator IS NOT NULL
		BEGIN
			IF EXISTS(select * from rvlfBoxSensorsCfg WHERE BoxId = @intBoxId AND SensorId = @intIterator)
			BEGIN
				SELECT @vcSensorName=SensorName , @vcActionOn =ActionOn , @vcActionOff = ActionOff FROM rvlfBoxSensorsCfg
					WHERE SensorId = @intIterator AND BoxId = @intBoxID
				SET @vcSensorMask = @vcSensorMask + '<tr><td class##label>'+ @vcSensorName +'</td><td class##b>' 
					+ CASE WHEN SUBSTRING(@vcSnsMask,@intIndex,1) = 1 THEN @vcActionOn ELSE @vcActionOff END + '</td></tr>'				
			END
			SELECT @intIterator = MIN(SensorId) FROM rvlfSensor WHERE SensorId > @intIterator --and BoxId = @intBoxId
				SET @intIndex = @intIndex-1
		END
		SET @vcSensorMask = @vcSensorMask + '</table>'--Char(13)		
	END
	-- Return the result of the function
	Return @vcSensorMask
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetSensorMaskInformationCommand]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[rvlf_fn_GetSensorMaskInformationCommand]
(
	@vcSnsMask varchar(8),
	@intBoxID int
)
RETURNS varchar(800)
AS
BEGIN
	DECLARE @vcSensorMask varchar(800)
	
	IF @vcSnsMask IS NOT NULL AND LEN(@vcSnsMask) = 8
	BEGIN
		DECLARE @intIterator int
		DECLARE @vcSensorName varchar(40)
		DECLARE @vcActionOn varchar(40)
		DECLARE @vcActionOff varchar(40)
		DECLARE @intIndex int = 8
		--SET @vcSensorMask = '<table width=''100%''>'
		SET @vcSensorMask = ''
		SELECT @intIterator = MIN(SensorId) FROM rvlfSensor
		WHILE @intIterator IS NOT NULL
		BEGIN
			IF EXISTS(select * from rvlfBoxSensorsCfg WHERE BoxId = @intBoxId AND SensorId = @intIterator)
			BEGIN
				SELECT @vcSensorName=SensorName , @vcActionOn =ActionOn , @vcActionOff = ActionOff FROM rvlfBoxSensorsCfg
					WHERE BoxId = @intBoxID AND SensorId = @intIterator
				--SET @vcSensorMask = @vcSensorMask + '<tr><td class##label>'+ @vcSensorName +'</td><td class##b>' 
				--	+ CASE WHEN SUBSTRING(@vcSnsMask,@intIndex,1) = 1 THEN @vcActionOn ELSE @vcActionOff END + '</td></tr>'
				SET @vcSensorMask = @vcSensorMask + @vcSensorName +',' 
					+ CASE WHEN SUBSTRING(@vcSnsMask,@intIndex,1) = 1 THEN @vcActionOn ELSE @vcActionOff END + ','
			END
			SELECT @intIterator = MIN(SensorId) FROM rvlfSensor WHERE SensorId > @intIterator --and BoxId = @intBoxId
				SET @intIndex = @intIndex-1
		END
		--SET @vcSensorMask = @vcSensorMask + '</table>'--Char(13)
		SET @vcSensorMask = @vcSensorMask 
	END
	-- Return the result of the function
	Return @vcSensorMask
END




GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetSensorMaskInformationCommand_New]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE FUNCTION [dbo].[rvlf_fn_GetSensorMaskInformationCommand_New]  
(  
 @vcSnsMask varchar(8),  
 @intBoxID int ,
 @Lang varchar(15)  
)  
RETURNS nvarchar(800)  
AS  
BEGIN  
 DECLARE @vcSensorMask nvarchar(800)  
   
 IF @vcSnsMask IS NOT NULL AND LEN(@vcSnsMask) = 8  
 BEGIN  
  DECLARE @intIterator int  
  DECLARE @vcSensorName nvarchar(40)  
  DECLARE @vcActionOn nvarchar(40)  
  DECLARE @vcActionOff nvarchar(40)  
  DECLARE @intIndex int = 8  
  --SET @vcSensorMask = '<table width=''100%''>'  
  SET @vcSensorMask = ''  
  SELECT @intIterator = MIN(SensorId) FROM rvlfSensor  
  WHILE @intIterator IS NOT NULL  
  BEGIN  
   IF EXISTS(select * from rvlfBoxSensorsCfg WHERE BoxId = @intBoxId AND SensorId = @intIterator)  
   BEGIN  
    SELECT @vcSensorName= (Case when @Lang='LanguageArNew' Then isnull(S.SensorName_Ar,S.SensorName) else S.SensorName END), @vcActionOn = (Case when @Lang='LanguageArNew' Then isnull(S.ActionOn_Ar,S.ActionOn) else S.ActionOn end), @vcActionOff = (Case when @Lang='LanguageArNew' Then isnull(S.ActionOff_Ar,S.ActionOff) Else S.ActionOff end)   
    FROM  rvlfBoxSensorsCfg C   
     inner join  rvlfsensor S on S.SensorID = C.SensorID  
     WHERE BoxId = @intBoxID AND C.SensorId = @intIterator  
    --SET @vcSensorMask = @vcSensorMask + '<tr><td class##label>'+ @vcSensorName +'</td><td class##b>'   
    -- + CASE WHEN SUBSTRING(@vcSnsMask,@intIndex,1) = 1 THEN @vcActionOn ELSE @vcActionOff END + '</td></tr>'  
    SET @vcSensorMask = @vcSensorMask + @vcSensorName +','   
     + CASE WHEN SUBSTRING(@vcSnsMask,@intIndex,1) = 1 THEN @vcActionOn ELSE @vcActionOff END + ','  
   END  
   SELECT @intIterator = MIN(SensorId) FROM rvlfSensor WHERE SensorId > @intIterator --and BoxId = @intBoxId  
    SET @intIndex = @intIndex-1  
  END  
  --SET @vcSensorMask = @vcSensorMask + '</table>'--Char(13)  
  SET @vcSensorMask = @vcSensorMask   
 END  
 -- Return the result of the function  
 Return @vcSensorMask  
END  
  
  

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetSensorMsgInformation]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetSensorMsgInformation]
(
	@vcCustomProp varchar(600),
	@intBoxID int
)
RETURNS varchar(MAX)
AS
BEGIN
	DECLARE @vcSnsMask varchar(8)
	DECLARE @vcSensorMask varchar(MAX)
	
	SET @vcSnsMask = Substring(@vcCustomProp, CHARINDEX('=',@vcCustomProp,
		CHARINDEX ('SensorMessages=',@vcCustomProp,1)+1)+1,8)
	
	IF @vcSnsMask IS NOT NULL AND LEN(@vcSnsMask) = 8
	BEGIN
		DECLARE @intIterator int
		DECLARE @vcSensorName varchar(40)
		DECLARE @intIndex int = 8
		SET @vcSensorMask = '<table width##100%>'--<tr><td colspan##3>SensorMessages</td></tr>'
		SELECT @intIterator = MIN(SensorId) FROM rvlfSensor
		WHILE @intIterator IS NOT NULL
		BEGIN
			IF EXISTS(select * from rvlfBoxSensorsCfg WHERE BoxId = @intBoxId AND SensorId = @intIterator)
			BEGIN
				SELECT @vcSensorName=SensorName FROM rvlfBoxSensorsCfg
					WHERE SensorId = @intIterator AND BoxId = @intBoxId
				SET @vcSensorMask = @vcSensorMask + '<tr></td> <td class##label>'+ @vcSensorName +'</td><td class##b>' 
					+ CASE WHEN SUBSTRING(@vcSnsMask,@intIndex,1) = 1 THEN 'Enabled' ELSE 'Disabled' END + '</td></tr>'
			END
			SELECT @intIterator = MIN(SensorId ) FROM rvlfSensor WHERE SensorId > @intIterator-- AND BoxId = @intBoxId
				SET @intIndex = @intIndex-1
		END
		SET @vcSensorMask = @vcSensorMask + '</table>'--Char(13)
	END
	SET @vcSensorMask = REPLACE(@vcCustomProp,@vcSnsMask,@vcSensorMask)
	-- Return the result of the function
	RETURN @vcSensorMask
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetSensorMsgInformation_New]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[rvlf_fn_GetSensorMsgInformation_New]    
(    
 @vcCustomProp varchar(600),    
 @intBoxID int,  
 @Lang varchar(15)    
)    
RETURNS nvarchar(MAX)    
AS    
BEGIN    
 DECLARE @vcSnsMask nvarchar(8)    
 DECLARE @vcSensorMask nvarchar(MAX)    
     
 SET @vcSnsMask = Substring(@vcCustomProp, CHARINDEX('=',@vcCustomProp,    
  CHARINDEX ('SensorMessages=',@vcCustomProp,1)+1)+1,8)    
     
 IF @vcSnsMask IS NOT NULL AND LEN(@vcSnsMask) = 8    
 BEGIN    
  DECLARE @intIterator int    
  DECLARE @vcSensorName nvarchar(40)    
  DECLARE @intIndex int = 8    
  SET @vcSensorMask = '<table width##100%>'--<tr><td colspan##3>SensorMessages</td></tr>'    
  SELECT @intIterator = MIN(SensorId) FROM rvlfSensor    
  WHILE @intIterator IS NOT NULL    
  BEGIN    
   IF EXISTS(select * from rvlfBoxSensorsCfg WHERE BoxId = @intBoxId AND SensorId = @intIterator)    
   BEGIN    
    SELECT @vcSensorName= Case when @Lang = 'LanguageArNew' Then SN.SensorName_Ar else SN.SensorName end   
    FROM rvlfBoxSensorsCfg SC          
    INNER JOIN rvlfsensor SN on SN.sensorID = SC.SensorID   
     WHERE SC.SensorId = @intIterator AND SC.BoxId = @intBoxId    
    SET @vcSensorMask = @vcSensorMask + '<tr></td> <td class##label>'+ @vcSensorName +'</td><td class##b>'     
     + CASE WHEN SUBSTRING(@vcSnsMask,@intIndex,1) = 1 THEN 'Enabled' ELSE 'Disabled' END + '</td></tr>'    
   END    
   SELECT @intIterator = MIN(SensorId ) FROM rvlfSensor WHERE SensorId > @intIterator-- AND BoxId = @intBoxId    
    SET @intIndex = @intIndex-1    
  END    
  SET @vcSensorMask = @vcSensorMask + '</table>'--Char(13)    
 END    
 SET @vcSensorMask = REPLACE(@vcCustomProp,@vcSnsMask,@vcSensorMask)    
 -- Return the result of the function    
 RETURN @vcSensorMask    
END 

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetShiftStartDateandTime]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_GetShiftStartDateandTime]
(
	@BoxId nvarchar(100) =null,
	@OriginDate datetime =null
)
RETURNS datetime
AS
BEGIN
	-- Declare the return variable here
	declare @StartDate datetime, @EndDate datetime, @EqType int,@MaxValue bigint=0,@minValue bigint=0
	select @EqType=EConsumptionType from rvlfMAKDevices where BoxId=@BoxId
	if(@EqType=2)
		begin
			select  @StartDate=dateadd(MI,datediff(MI,cast(@OriginDate as time),StartTime),@OriginDate) from rvlf_EnergyConsumption where @OriginDate between cast(cast(getdate() as date) as varchar(20)) + ' ' + cast(StartTime as varchar(30)) and cast(cast(dateadd(DAY,1,getdate()) as date) as varchar(20)) + ' ' + cast(StartTime as varchar(30)) and EquipmentId=@BoxId and Shift=1
		end
	else
		begin
			select @StartDate=dateadd(MI,datediff(MI,cast(@OriginDate as time),StartTime),@OriginDate) from rvlf_EnergyConsumption where @OriginDate between cast(cast(getdate() as date) as varchar(20)) + ' ' + cast(StartTime as varchar(30)) and 
			case when Format(cast(StartTime as datetime),'tt') = 'PM' and Format(cast(EndTime as datetime),'tt')='AM' then 
				 cast(cast(dateadd(DAY,1,getdate()) as date) as varchar(20)) + ' ' + cast(EndTime as varchar(30)) 
			else 
				case when datediff(SS,StartTime,EndTime)<=0 then 
					 cast(cast(dateadd(DAY,1,getdate()) as date) as varchar(20)) + ' ' + cast(EndTime as varchar(30)) 
				else 
					 cast(cast(getdate() as date) as varchar(20)) + ' ' + cast(EndTime as varchar(30)) 
				end 
			end and EquipmentId=@BoxId
		end
	select @StartDate=case when @StartDate>getdate() then dateadd(DD,-1,@StartDate) else @StartDate end 
	RETURN @StartDate

END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetSMSCommand]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetSMSCommand]
(@CommandId int,         
 @vcCustomProp varchar(max)= null
 )

/******************************************************************************/
--	Name		:	[rvlf_fn_GetSMSCommandParam]
--	Description	:	Getting SMS command Parammeter for command Scheduling.
--	Author		:	Ranjith. N
--	History		:	Initial Version
/******************************************************************************/

RETURNS nvarchar(max)
BEGIN
 DECLARE @VCSmsMsg VARCHAR(max)  

     if @CommandId =255  
		Begin  
		  set @VCSmsMsg = 'Invalid command. Send Tri HELP to know the available commands and inputs.'       
		End  
	else if @CommandId = 254   
		Begin     
			set @VCSmsMsg = 'PositionUpdate- TRI vehicle GET PU \n ReportingInterval- TRI vehicle SET RI <mins> \n SpeedThreshold- TRI vehicle SET ST <kms>'       		
		End	
    else if @CommandId = 1   
		Begin     
			--set @VCSmsMsg =(CASE WHEN @tiValidGps = 0 THEN                 
			--	CASE WHEN @IsAddressAlreadyAvailable = 1 AND @vcStreetAddress!='N/A' THEN @vcStreetAddress ELSE NULL END       
			--ELSE 'N/A' END)  
		set @VCSmsMsg = Null 	
			
		end  
    else if @CommandId =2  
	Begin       	
		if not exists(select * from rvlf_fn_ConvertArrayToTable('5,10,15,30,60,120',',') a where a.FieldValue = 
		SUBSTRING(@vcCustomProp, CHARINDEX('Set Reporting Interval:',@vcCustomProp,0)+23,(CHARINDEX(';',@vcCustomProp,CHARINDEX('Set Reporting Interval:',@vcCustomProp,1))) -(CHARINDEX('Set Reporting Interval:',@vcCustomProp,1)+23)))
		begin 
			set @VCSmsMsg = 'Invalid input. Reporting Interval can be 5,10,15,30,60,120 mins' --range: 300-43200 Seconds'  
		end
		else
		begin
		set @VCSmsMsg = 'Reporting interval set as ' + SUBSTRING(@vcCustomProp, CHARINDEX('Set Reporting Interval:',@vcCustomProp,0)+23,(CHARINDEX(';',@vcCustomProp,CHARINDEX('Set Reporting Interval:',@vcCustomProp,1))) -(CHARINDEX('Set Reporting Interval:',@vcCustomProp,1)+23)) + ' Mins'  
		end		
	end  
    else if @CommandId =3  
    Begin      
		if not exists(select * from rvlf_fn_ConvertArrayToTable('80, 90, 100, 110, 120, 130, 140, 150, 160',',') a where a.FieldValue = 
         SUBSTRING(@vcCustomProp, CHARINDEX('Set Speed Threshold:',@vcCustomProp,0)+20,(CHARINDEX(';',@vcCustomProp,CHARINDEX('Set Speed Threshold:',@vcCustomProp,1))) -(CHARINDEX('Set Speed Threshold:',@vcCustomProp,1)+20)))
		begin  
			set @VCSmsMsg = 'Invalid input. Speed Threshold can be 80,90,100,110,120,130,140,150,160 kms'--Speed Threshold range: 80-160 kms'  
		end  
		else  
		begin  
			set @VCSmsMsg = 'Speed Threshold set as ' + SUBSTRING(@vcCustomProp, CHARINDEX('Set Speed Threshold:',@vcCustomProp,0)+20,(CHARINDEX(';',@vcCustomProp,CHARINDEX('Set Speed Threshold:',@vcCustomProp,1))) -(CHARINDEX('Set Speed Threshold:',@vcCustomProp,1)+20)) +  ' kms'  
		end  
    end  
    else   
    begin      
       set @VCSmsMsg = 'Invalid input. Send Tri HELP to know the available commands and inputs.'  
    end  
    
RETURN @VCSmsMsg
END



GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetSMSCommandFrame]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetSMSCommandFrame]
(@intBoxID int,         
 @vcCustomProp varchar(max)= null
 )

/******************************************************************************/
--	Name		:	[rvlf_fn_GetSMSCommandFrame]
--	Description	:	Getting SMS command Parammeter for command Scheduling.
--	Author		:	Ranjith. N
--	History		:	Initial Version
/******************************************************************************/

RETURNS nvarchar(max)
BEGIN
 DECLARE @VcSMSParam VARCHAR(max)  

   DECLARE @CommandId int   
         DECLARE @MobileNo varchar(20)  
         Declare @Userid varchar(50),@OrganizationID varchar(50),@UserName varchar(50),@Email varchar(50)  
         Declare @VehicleID varchar(50),@VehicleDescription varchar(50),@VehicleName varchar(50),@LicensePlate varchar(50)         
 
         SELECT @MobileNo = SUBSTRING(@vcCustomProp, CHARINDEX('MobileNo:',@vcCustomProp,0)+9,(CHARINDEX(';',@vcCustomProp,CHARINDEX('MobileNo:',@vcCustomProp,1))) -(CHARINDEX('MobileNo:',@vcCustomProp,1)+9)),  
                @CommandId = SUBSTRING(@vcCustomProp, CHARINDEX('Command:',@vcCustomProp,0)+8,LEN(@vcCustomProp))   
         Declare @VcSMSCommand varchar(max), @VcParam varchar(max)
         
    if @CommandId not in (254,255)
    Begin
      select @VehicleID =v.VehicleId,@VehicleDescription=v.VehicleDescription,@VehicleName=v.VehicleDescription,@LicensePlate=v.LicensePlate from rvlfVehicle v  
    inner join rvlfvehicleassignment va on va.VehicleId=v.VehicleId  
    where va.boxid = @intBoxID  
    End
    
    if @CommandId = 1   
	Begin 	Set @VcSMSCommand = '?' set @VcParam= null End
	
	else if @CommandId =2
	Begin 	Set @VcSMSCommand = 'R' 
			set @VcParam=cast(cast(SUBSTRING(@vcCustomProp, CHARINDEX('Set Reporting Interval:',@vcCustomProp,0)+23,(CHARINDEX(';',@vcCustomProp,CHARINDEX('Set Reporting Interval:',@vcCustomProp,1))) -(CHARINDEX('Set Reporting Interval:',@vcCustomProp,1)+23))* 60 as bigint) as varchar(10))
	End
	else if @CommandId =3
	 Begin 	Set @VcSMSCommand = 'S'
			Set @VcParam= SUBSTRING(@vcCustomProp, CHARINDEX('Set Speed Threshold:',@vcCustomProp,0)+20,(CHARINDEX(';',@vcCustomProp,CHARINDEX('Set Speed Threshold:',@vcCustomProp,1))) -(CHARINDEX('Set Speed Threshold:',@vcCustomProp,1)+20))
	  End
	 
    
Declare @IntCommAddressTypeID int, @VcCommAddressValue varchar(30), @TIntServiceID tinyint,@VcSystemInstalled varchar(50), @VcBoxProtocolTypeName varchar(25),
		@VcIP varchar(50), @VCPort varchar(10)

SELECT @IntCommAddressTypeID = c.CommAddressTypeID,@VcCommAddressValue= c.CommAddressValue, 
@TIntServiceID = s.ServiceID ,@VcSystemInstalled=s.SystemInstalled, @VcBoxProtocolTypeName= p.BoxProtocolTypeName FROM       
 rvlfBoxCommInfo c INNER JOIN rvlfBoxSettings b ON c.BoxId = b.BoxId      
 INNER JOIN rvlfBoxProtocolType p ON b.BoxProtocolTypeId = p.BoxProtocolTypeId      
 INNER JOIN rvlfServices s ON b.CommModeId = s.CommModeId       
 INNER JOIN rvlfVehicleAssignment va ON c.BoxId = va.BoxId      
 INNER JOIN rvlfVehicle v ON va. VehicleId =  v.VehicleId      
 WHERE       
 (c.BoxId = @intBoxID) AND      
 (v.VehicleId = @VehicleID)    
 
 SELECT @VcIP= element FROM  dbo.func_split(@VcCommAddressValue, ':') where elementid =1
    
 SELECT @VCPort = element FROM dbo.func_split(@VcCommAddressValue, ':') where elementid =2  

select @VcSMSParam = 'IP=' + @VcIP
                    + ';Port=' + @VCPort
                    + ';Message=' + @VcSMSCommand
                    + ';DeviceID=' + cast(@intBoxID as varchar(10))
                    +  case when @VcParam is not null then ';Param=' + @VcParam else '' end
                    + ';DCLID=' + @VcSystemInstalled
                    + ';UserID=' + cast(19 as varchar(10))
RETURN @VcSMSParam
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetSMSCommandUserRights]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[rvlf_fn_GetSMSCommandUserRights]
(@MobileNo varchar(20),
 @Boxid bigint
 )

/******************************************************************************/
--	Name		:	[rvlf_fn_GetSMSCommandUserRights]
--	Description	:	Getting SMS command Parammeter for user rights Scheduling.
--	Author		:	Ranjith. N
--	History		:	Initial Version
/******************************************************************************/

RETURNS nvarchar(max)
BEGIN
 DECLARE @VCSmsMsg VARCHAR(max)  


	--Declare @Userid int = null,@UserGroup int= null
	--select @Userid = u.UserId,@UserGroup = uga.UserGroupId from rvlfUser u
	--inner join rvlfUserGroupAssignment uga on uga.UserId = u.UserId
	--inner join rvlfUserGroupSecurity ugs on ugs.UserGroupId = uga.UserGroupId
	--where u.MobileNo = @MobileNo  and ugs.ModuleId = 26 and  ugs.OperationTypeId = 262
	----if @UserGroup <> 1
	----Begin
	--if @Userid = '' or @Userid is null
	--   Begin  
	--	  set @VCSmsMsg = 'Unknown mobile number! Please contact administrator.'       
	--	End 
	--Else
	--Begin
	--	IF not exists(select * from rvlfVehicleAssignment va inner join rvlfFleetVehicles fv on va.VehicleId = fv.VehicleId
	--					inner join rvlfFleetUsers fu on fv.FleetId = fu.FleetId inner join rvlfUser u  on u.UserId = fu.UserId
	--					where u.UserId = @Userid and va.BoxId = @Boxid and isnull(u.issmsqry,0) = 1 and u.mobileno = @MobileNo and isdelete =0)
	--	Begin
	--		set @VCSmsMsg = 'You do not have privilege to this vehicle! Please contact administrator.'   
	--	End
	--	Else
	--	Begin
	--		set @VCSmsMsg = null
	--	End 	
	--End
	----End
	----Else
	----Begin
	----set @VCSmsMsg = null
	----End
	
	Declare @Userid int = null,@UserGroup int= null
	select @Userid = u.UserId,@UserGroup = uga.UserGroupId from rvlfUser u
	inner join rvlfUserGroupAssignment uga on uga.UserId = u.UserId
	inner join rvlfUserGroupSecurity ugs on ugs.UserGroupId = uga.UserGroupId
	where u.MobileNo = @MobileNo  and ugs.ModuleId = 26 and  ugs.OperationTypeId = 262
	
	    IF not exists(select u.UserId from rvlfUser u inner join rvlfUserGroupAssignment uga on uga.UserId = u.UserId
						inner join rvlfUserGroupSecurity ugs on ugs.UserGroupId = uga.UserGroupId						
						where u.MobileNo = @MobileNo )
			set @VCSmsMsg = 'Unknown mobile number! Please contact administrator.' 
		else IF exists(select u.UserId from rvlfUser u inner join rvlfUserGroupAssignment uga on uga.UserId = u.UserId
						inner join rvlfUserGroupSecurity ugs on ugs.UserGroupId = uga.UserGroupId						
						where u.MobileNo = @MobileNo  and ugs.ModuleId = 26 and  ugs.OperationTypeId = 262 and uga.UserGroupId = 1)
			set @VCSmsMsg = null
		
		else IF not exists(select u.UserId from rvlfUser u inner join rvlfUserGroupAssignment uga on uga.UserId = u.UserId
						inner join rvlfUserGroupSecurity ugs on ugs.UserGroupId = uga.UserGroupId
						where u.MobileNo = @MobileNo  and ugs.ModuleId = 26 and  ugs.OperationTypeId = 262)
			set @VCSmsMsg = 'You do not have privilege to this vehicle! Please contact administrator.'   

		else IF not exists(select * from rvlfVehicleAssignment va inner join rvlfFleetVehicles fv on va.VehicleId = fv.VehicleId
						inner join rvlfFleetUsers fu on fv.FleetId = fu.FleetId inner join rvlfUser u  on u.UserId = fu.UserId
						where u.UserId = @Userid and va.BoxId = @Boxid and isnull(u.issmsqry,0) = 1 and u.mobileno = @MobileNo and isdelete =0)
		Begin
			set @VCSmsMsg = 'You do not have privilege to this vehicle! Please contact administrator.'   
		End
		Else
		Begin
			set @VCSmsMsg = null
		End 
    
RETURN @VCSmsMsg
END



GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetSMSSettings]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE function [dbo].[rvlf_fn_GetSMSSettings]  
 (@OrganizationID bigint)  
 Returns varchar(max)  
 as  
 begin   
 if exists(select OrganizationId from rvlfsmssettings where organizationid=@OrganizationID)
 begin
 set @OrganizationID = (case when @OrganizationID is null or @OrganizationID =0  then 6 else @OrganizationID end)  
 end
 else
 begin
 set @OrganizationID =6
 end
 
 
 declare @SMSSettings varchar(max)=null  
 select @SMSSettings = (ServiceUrlName+'?'+UnameKey+'='+Unamevalue+'&'+PasswordKey + '='+PasswordValue + '&'+SenderKey + '='+SenderValue  
 + '&'+DestinationKey+ '='+'<#Destination#>' + '&'+MessageKey + '='+'<#SMSMessage#>')  from rvlfSMSSettings    
 where (@OrganizationID IS NULL OR @OrganizationID =6 OR OrganizationId=@OrganizationID)  
 Return @SMSSettings  
 end
GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetStopTime_MFC]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetStopTime_MFC]
(@intBoxLooping bigint,@dtStartDate datetime,@dtEndDate datetime)RETURNS VARCHAR(10)
AS
/****************************************************************************************************************
Function Name	: SELECT dbo.rvlf_fn_GetStopTime_MFC(3989,'2013-04-03 05:40:52.000','2013-04-03 06:16:38.000')
Created By		: Sakthi Gopinath S
Created Date	: 04-Mar-2013
****************************************************************************************************************/
BEGIN
DECLARE @vcStopTime bigint
DECLARE @tbl_IgnitionMessageForProcessingTrip TABLE(            
  [OriginDateTime] [datetime] NOT NULL,            
  [BoxMsgInTypeId] [tinyint] NULL,            
  [CustomProp] [varchar](600) NULL,              
  [Speed] int NULL,            
  [Ignition] bit null,              
  [Address] varchar(300) null,            
  [OdoMeter] bigint null,            
  Lat numeric(10,6),            
  Long numeric(10,6)            
 )   

DECLARE @TBL_IgnitionStart TABLE
 (            
  Processid bigint identity(1,1),            
  Boxid int,            
  StartTime datetime,            
  OdoStart bigint,            
  StartAddress varchar(300),            
  Running int,            
  idling int,            
  Speed int,            
  StopInterval int,            
  tripId int,            
  Lat numeric(10,6),            
  Long numeric(10,6)            
 )            
             
 DECLARE @TBL_IgnitionStop TABLE
 (            
  Processid bigint identity(1,1),     
  Boxid int,            
  StopTime datetime,            
  OdoEnd bigint,            
  EndAddress varchar(300),            
  tripId int,            
  Lat numeric(10,6),            
  Long numeric(10,6),
  StopInterval int,                        
  IsTripCompleted bit            
 ) 

DELETE FROM @tbl_IgnitionMessageForProcessingTrip
INSERT INTO @tbl_IgnitionMessageForProcessingTrip(OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,Address,OdoMeter,Lat,Long)             
SELECT h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,CAST(SUBSTRING(sensormask,6,1) as bit),
CASE WHEN (H.LandMarkID IS NULL OR H.LandMarkID = 0) THEN             
REPLACE(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''') ELSE L.LandmarkName END,            
CASE WHEN CustomProp LIKE '%Odometer=%' THEN CAST( SUBSTRING (CustomProp,CHARINDEX('Odometer=',CustomProp,1)+9,CHARINDEX(';',CustomProp,            
CHARINDEX('Odometer=',CustomProp,1)) - (CHARINDEX('Odometer=',CustomProp,1)+9)) as bigint) ELSE 0 END,H.Latitude,H.Longitude                       
FROM rvlfMsgInHst H  LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID                                      
WHERE h.BoxID = @intBoxLooping AND H.BoxMsgInTypeId IN (2,3) AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate    
AND h.CustomProp LIKE '%SENSOR_NUM=3;%' ORDER BY h.origindatetime ASC  
 
INSERT INTO @TBL_IgnitionStart (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)            
SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long             
FROM @tbl_IgnitionMessageForProcessingTrip WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
AND BoxMsgInTypeId IN(2) 
--AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tbl_IgnitionMessageForProcessingTrip             
--WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)            
--AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tbl_IgnitionMessageForProcessingTrip             
--WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)              
--AND Ignition=1

INSERT INTO @TBL_IgnitionStop (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long)            
SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                
FROM @tbl_IgnitionMessageForProcessingTrip WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
AND BoxMsgInTypeId IN(3)
--AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tbl_IgnitionMessageForProcessingTrip             
--WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)            
--AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tbl_IgnitionMessageForProcessingTrip             
--WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)              

----PREPARE THE TRIPS AND DETAILS                
--DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBL_IgnitionStart)             
--DECLARE @DTSTART DATETIME=null,@DTEND DATETIME=null,@DTSTOPSTART DATETIME =NULL              
--DECLARE @INC INT=1                   
--WHILE @LOOP IS NOT NULL            
-- BEGIN            
--  SELECT TOP 1 @DTSTART=StartTime  FROM @TBL_IgnitionStart WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                
--  IF @DTSTOPSTART IS NOT NULL                     
--   UPDATE top(1) @TBL_IgnitionStart SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART             
--  SET @DTSTOPSTART=@DTSTART             
--  SET @DTEND=NULL            
--  SELECT TOP 1 @DTEND=StopTime FROM @TBL_IgnitionStop WHERE StopTime >@DTSTART             
--  UPDATE top(1) @TBL_IgnitionStart SET tripId=@INC WHERE StartTime =@DTSTART             
--  UPDATE top(1) @TBL_IgnitionStop SET tripId=@INC WHERE StopTime =@DTEND              
--  SET @INC =@INC +1            
--  SELECT @LOOP =MIN(Processid) FROM @TBL_IgnitionStart WHERE Processid > @LOOP  AND StartTime > @DTSTART            
--END              

--PREPARE THE TRIPS AND DETAILS                
DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBL_IgnitionStop)             
DECLARE @DTSTART DATETIME=null,@DTEND DATETIME=null,@DTSTOPSTART DATETIME =NULL              
DECLARE @INC INT=1                   
WHILE @LOOP IS NOT NULL            
 BEGIN         
  SELECT @DTSTOPSTART=NULL,@DTSTART=NULL
  SELECT TOP 1 @DTSTOPSTART=StopTime  FROM @TBL_IgnitionStop WHERE Processid >= @LOOP
  SELECT TOP 1 @DTSTART=StartTime FROM @TBL_IgnitionStart WHERE StartTime > @DTSTOPSTART     
  UPDATE top(1) @TBL_IgnitionStop SET StopInterval =ISNULL(DATEDIFF(S,@DTSTOPSTART,@DTSTART),0) WHERE StopTime=@DTSTOPSTART       
  SET @INC =@INC +1            
  SELECT @LOOP =MIN(Processid) FROM @TBL_IgnitionStop WHERE Processid > @LOOP  AND StopTime > @DTSTOPSTART            
END   

DECLARE @FirstStopTime int=0
DECLARE @SecondStopTime int=0
SELECT TOP 1 @FirstStopTime=(CASE WHEN BoxMsgInTypeID=2 THEN DATEDIFF(S,@dtStartDate,OriginDateTime) ELSE 0 END) FROM @tbl_IgnitionMessageForProcessingTrip
SELECT TOP 1 @SecondStopTime=(CASE WHEN BoxMsgInTypeID=3 THEN DATEDIFF(S,OriginDateTime,@dtEndDate) ELSE 0 END) FROM @tbl_IgnitionMessageForProcessingTrip
ORDER BY OriginDateTime DESC
SELECT @vcStopTime=ISNULL((SUM(ISNULL(StopInterval,0))+@FirstStopTime+@SecondStopTime),0) FROM @TBL_IgnitionStop
--+@FirstStopTime+@SecondStopTime
--SELECT * FROM #TBL_IgnitionStop
--DROP TABLE #tbl_IgnitionMessageForProcessingTrip
--DROP TABLE #TBL_IgnitionStart
--DROP TABLE #TBL_IgnitionStop
RETURN @vcStopTime
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetTemperatureDetails]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetTemperatureDetails]
(
	@vcTempDesc varchar(1000)=null,
	@tiBoxMsgInTypeID tinyint=null,
	@intBoxID int = Null,
	@uiMessageInId uniqueidentifier = null,
	@dtOriginDateTime DateTime =null,
	@vcTempType varchar(20)	
)
RETURNS varchar(MAX)
AS
BEGIN
	DECLARE @vcTempDetail varchar(MAX)	=''
	DECLARE @vcMoxMsgInTypeName varchar(100)
	
	SELECT @vcMoxMsgInTypeName = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID
		
	BEGIN		
		
			IF @tiBoxMsgInTypeID  = 81 OR  @tiBoxMsgInTypeID = 82 OR @tiBoxMsgInTypeID  = 83 OR @tiBoxMsgInTypeID  = 84
				OR @tiBoxMsgInTypeID  = 85 OR  @tiBoxMsgInTypeID = 86 OR @tiBoxMsgInTypeID  = 87 OR @tiBoxMsgInTypeID  = 88			 
				BEGIN				
					SELECT @vcTempDetail = BoxMsgInTypeDesc FROM rvlfBoxMsgInType WHERE BoxMsgInTypeID = @tiBoxMsgInTypeID
				END
		
			IF @vcTempDetail = ''
				BEGIN					
					IF @vcTempType ='Temp1' 
					BEGIN					
						SELECT @vcTempDetail= CASE WHEN h.CustomProp like '%Temperature Sensor-1 Value=%' THEN 
						CAST(SUBSTRING (CustomProp,CHARINDEX('Temperature Sensor-1 Value=',CustomProp,1)+27,
						CHARINDEX(' degree Celsius;',CustomProp,CHARINDEX('Temperature Sensor-1 Value=',CustomProp,1)) - (CHARINDEX('Temperature Sensor-1 Value=',CustomProp,1)+27)) as nvarchar(6)) END						
						FROM rvlfMsgInHst h 
						WHERE OriginDateTime=@dtOriginDateTime and MessageInID=@uiMessageInId and BoxId=@intBoxID and BoxMsgInTypeId=@tiBoxMsgInTypeID
						IF @vcTempDetail IS NOT NULL 
						SET @vcTempDetail = 'Temperature = ' + Cast(@vcTempDetail as nvarchar(6))
					END
					ELSE IF @vcTempType ='Temp2'
					BEGIN
					
						SELECT @vcTempDetail=CASE WHEN h.CustomProp like '%Temperature Sensor-2 Value=%' THEN 
						CAST(SUBSTRING (CustomProp,CHARINDEX('Temperature Sensor-2 Value=',CustomProp,1)+27,
						CHARINDEX(' degree Celsius;',CustomProp,CHARINDEX('Temperature Sensor-2 Value=',CustomProp,1)) - (CHARINDEX('Temperature Sensor-2 Value=',CustomProp,1)+27))as nvarchar(6)) END 
						FROM rvlfMsgInHst h 
						WHERE OriginDateTime=@dtOriginDateTime and MessageInID=@uiMessageInId and BoxId=@intBoxID and BoxMsgInTypeId=@tiBoxMsgInTypeID
						IF @vcTempDetail IS NOT NULL 
						SET @vcTempDetail = 'Temperature = ' + Cast(@vcTempDetail as nvarchar(6))
						
					END
					ELSE IF @vcTempType ='Temp3'
					BEGIN
					
						SELECT @vcTempDetail=CASE WHEN h.CustomProp like '%Temperature Sensor-3 Value=%' THEN 
						CAST(SUBSTRING (CustomProp,CHARINDEX('Temperature Sensor-3 Value=',CustomProp,1)+27,
						CHARINDEX(' degree Celsius;',CustomProp,CHARINDEX('Temperature Sensor-3 Value=',CustomProp,1)) - (CHARINDEX('Temperature Sensor-3 Value=',CustomProp,1)+27))as nvarchar(6)) END 
						FROM rvlfMsgInHst h 
						WHERE OriginDateTime=@dtOriginDateTime and MessageInID=@uiMessageInId and BoxId=@intBoxID and BoxMsgInTypeId=@tiBoxMsgInTypeID
						IF @vcTempDetail IS NOT NULL 
						SET @vcTempDetail = 'Temperature = ' + Cast(@vcTempDetail as nvarchar(6))
						
					END
					ELSE IF @vcTempType ='Temp4'
					BEGIN
					
						SELECT @vcTempDetail=CASE WHEN h.CustomProp like '%Temperature Sensor-4 Value=%' THEN 
						CAST(SUBSTRING (CustomProp,CHARINDEX('Temperature Sensor-4 Value=',CustomProp,1)+27,
						CHARINDEX(' degree Celsius;',CustomProp,CHARINDEX('Temperature Sensor-4 Value=',CustomProp,1)) - (CHARINDEX('Temperature Sensor-4 Value=',CustomProp,1)+27))as nvarchar(6)) END 
						FROM rvlfMsgInHst h 
						WHERE OriginDateTime=@dtOriginDateTime and MessageInID=@uiMessageInId and BoxId=@intBoxID and BoxMsgInTypeId=@tiBoxMsgInTypeID
						IF @vcTempDetail IS NOT NULL 
						SET @vcTempDetail = 'Temperature = ' + Cast(@vcTempDetail as nvarchar(6))
						
					END
				END
			ELSE
				BEGIN
					IF @vcTempType ='Temp1' 
					BEGIN
						SELECT @vcTempDetail= CASE WHEN h.CustomProp like '%Temperature Sensor-1 Value=%' THEN 
						CAST(SUBSTRING (CustomProp,CHARINDEX('Temperature Sensor-1 Value=',CustomProp,1)+27,
						CHARINDEX(' degree Celsius;',CustomProp,CHARINDEX('Temperature Sensor-1 Value=',CustomProp,1)) - (CHARINDEX('Temperature Sensor-1 Value=',CustomProp,1)+27)) as nvarchar(6)) END
						FROM rvlfMsgInHst h
						WHERE OriginDateTime=@dtOriginDateTime and MessageInID=@uiMessageInId and BoxId=@intBoxID and BoxMsgInTypeId=@tiBoxMsgInTypeID
						
						IF @vcTempDetail IS NOT NULL 
						BEGIN
							IF(@tiBoxMsgInTypeID = 83)
								SET @vcTempDetail = Replace(Replace(@vcMoxMsgInTypeName,'Sensor-2 Probe',''),'Sensor-1 Probe','') + ' = ' + Cast(@vcTempDetail as nvarchar(6))
							ELSE
								SET @vcTempDetail = Replace(Replace(@vcMoxMsgInTypeName,'Sensor-2',''),'Sensor-1','') +  ' = ' + Cast(@vcTempDetail as nvarchar(6))
						END							
					END
					ELSE IF @vcTempType ='Temp2'
					BEGIN
						SELECT @vcTempDetail=  CASE WHEN h.CustomProp like '%Temperature Sensor-2 Value=%' THEN 
						CAST(SUBSTRING (CustomProp,CHARINDEX('Temperature Sensor-2 Value=',CustomProp,1)+27,
						CHARINDEX(' degree Celsius;',CustomProp,CHARINDEX('Temperature Sensor-2 Value=',CustomProp,1)) - (CHARINDEX('Temperature Sensor-2 Value=',CustomProp,1)+27)) as nvarchar(6)) END
						FROM rvlfMsgInHst h
						WHERE OriginDateTime=@dtOriginDateTime and MessageInID=@uiMessageInId and BoxId=@intBoxID and BoxMsgInTypeId=@tiBoxMsgInTypeID
						
						IF @vcTempDetail IS NOT NULL 
						BEGIN
							IF(@tiBoxMsgInTypeID = 87)
								SET @vcTempDetail = Replace(Replace(@vcMoxMsgInTypeName,'Sensor-2 Probe',''),'Sensor-1 Probe','') + ' = ' + Cast(@vcTempDetail as nvarchar(6))
							ELSE
								SET @vcTempDetail = Replace(Replace(@vcMoxMsgInTypeName,'Sensor-2',''),'Sensor-1','') +  ' = ' + Cast(@vcTempDetail as nvarchar(6))
						END
					END

					ELSE IF @vcTempType ='Temp3'
					BEGIN
						SELECT @vcTempDetail=  CASE WHEN h.CustomProp like '%Temperature Sensor-3 Value=%' THEN 
						CAST(SUBSTRING (CustomProp,CHARINDEX('Temperature Sensor-3 Value=',CustomProp,1)+27,
						CHARINDEX(' degree Celsius;',CustomProp,CHARINDEX('Temperature Sensor-3 Value=',CustomProp,1)) - (CHARINDEX('Temperature Sensor-3 Value=',CustomProp,1)+27)) as nvarchar(6)) END
						FROM rvlfMsgInHst h
						WHERE OriginDateTime=@dtOriginDateTime and MessageInID=@uiMessageInId and BoxId=@intBoxID and BoxMsgInTypeId=@tiBoxMsgInTypeID
						
						IF @vcTempDetail IS NOT NULL 
						BEGIN
							IF(@tiBoxMsgInTypeID = 169)
								SET @vcTempDetail = Replace(@vcMoxMsgInTypeName,'Sensor-3 Probe','') + ' = ' + Cast(@vcTempDetail as nvarchar(6))
							ELSE
								SET @vcTempDetail =Replace(@vcMoxMsgInTypeName,'Sensor-3','')+  ' = ' + Cast(@vcTempDetail as nvarchar(6))
						END
					END
					ELSE IF @vcTempType ='Temp4'
					BEGIN
						SELECT @vcTempDetail=  CASE WHEN h.CustomProp like '%Temperature Sensor-4 Value=%' THEN 
						CAST(SUBSTRING (CustomProp,CHARINDEX('Temperature Sensor-4 Value=',CustomProp,1)+27,
						CHARINDEX(' degree Celsius;',CustomProp,CHARINDEX('Temperature Sensor-4 Value=',CustomProp,1)) - (CHARINDEX('Temperature Sensor-4 Value=',CustomProp,1)+27)) as nvarchar(6)) END
						FROM rvlfMsgInHst h
						WHERE OriginDateTime=@dtOriginDateTime and MessageInID=@uiMessageInId and BoxId=@intBoxID and BoxMsgInTypeId=@tiBoxMsgInTypeID
						
						IF @vcTempDetail IS NOT NULL 
						BEGIN
							IF(@tiBoxMsgInTypeID = 174)
								SET @vcTempDetail = Replace(@vcMoxMsgInTypeName,'Sensor-4 Probe','') + ' = ' + Cast(@vcTempDetail as nvarchar(6))
							ELSE
								SET @vcTempDetail = Replace(@vcMoxMsgInTypeName,'Sensor-4','') +  ' = ' + Cast(@vcTempDetail as nvarchar(6))
						END
					END
				END								
		End		
	
	-- Return the result of the function
	RETURN @vcTempDetail

END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetTimeFromSeconds]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetTimeFromSeconds]
(
	@intTotalSeconds int 
)
RETURNS varchar(20)
AS
BEGIN
	SELECT @intTotalSeconds = ABS(@intTotalSeconds)
	DECLARE @vcduration varchar(20)
	IF @intTotalSeconds < 86400
		SET @vcduration =  convert(varchar,CAST( RTRIM(CONVERT(char(8), @intTotalSeconds/3600) ) 
			+ ':' + CONVERT(char(2), (@intTotalSeconds % 3600) / 60) + ':' +
			CONVERT(char(2), @intTotalSeconds % 60) as Datetime),108)
	ELSE

		SET @vcduration = CAST(@intTotalSeconds/86400 as varchar) + 
		CASE WHEN (@intTotalSeconds/86400)>1 THEN 'D '  ELSE 'D ' END+
			convert(varchar,CAST( RTRIM(CONVERT(char(8), (@intTotalSeconds%86400)/3600) ) 
			+ ':' + CONVERT(char(2), (@intTotalSeconds % 3600) / 60) + ':' +
			CONVERT(char(2), (@intTotalSeconds % 60) )as Datetime),108)
			
	RETURN @vcduration
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetUserGroupsByUserID]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[rvlf_fn_GetUserGroupsByUserID] 
(
	@bigUserID bigint
)
RETURNS varchar(max)
AS
BEGIN
	DECLARE @vcUserGroups varchar(max) 
	select @vcUserGroups = substring(
			(SELECT ',' +g.UserGroupName AS [text()]
				FROM rvlfUserGroupAssignment as t INNER JOIN rvlfUserGroup g ON  t.UserGroupId = g.UserGroupId
				WHERE t.UserId = v.UserId 
				ORDER BY t.UserGroupId, t.UserId
				FOR XML PATH(''), type).value('(/text())[1]','varchar(max)'), 2, 1000)
	from rvlfUserGroupAssignment v WHERE v.UserId= @bigUserID
	group BY v.UserId	
	RETURN @vcUserGroups
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetUserServiceComment]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[rvlf_fn_GetUserServiceComment]    
	(    
	@bigUserID BIGINT,
	@boxID varchar(100),
	@Date datetime
	)    
RETURNS varchar(MAX)    
AS    
	BEGIN    

		DECLARE @vcServiceComment VARCHAR(MAX) = NULL    

		SELECT @vcServiceComment = ISNULL(@vcServiceComment+'','') + 
		'#' + cast(Right(Year(@Date),2) as varchar) + RIGHT('00'+cast(DATEPART(month,@Date) as varchar),2) + RIGHT('00'+cast(DATEPART(Day,@Date) as varchar),2) 
		+ RIGHT('00'+cast(DATEPART(HH,@Date) as varchar),2) + RIGHT('00'+cast(DATEPART(MI,@Date) as varchar),2)+ RIGHT('00'+cast(DATEPART(SS,@Date) as varchar),2) 
		+ '|' + D.BoxId + '|' + RIGHT('0000'+cast(isnull(RunningSerial,0) as varchar),4) + '|' + cast((CASE WHEN (vm.NearingPercentage >= pd.Notification1 AND vm.NearingPercentage < pd.Notification2) THEN '1'     
      WHEN (vm.NearingPercentage >= pd.Notification2 AND vm.NearingPercentage < pd.Notification3 AND pd.Notification2 <> 0) THEN '2'     
      WHEN (vm.NearingPercentage >= pd.Notification3 AND vm.NearingPercentage < 100 AND pd.Notification3 <> 0) THEN '3'     
      --WHEN (vm.NearingPercentage >= 100) THEN '3' ELSE '3' END) as varchar) + '|' + (CASE WHEN vm.ServiceType = 0 THEN 'Running Hours' WHEN vm.ServiceType = 1 THEN 'Odometer Reading'WHEN vm.ServiceType = 2 THEN 'Time Based' ELSE 'Concrete Mix Hours' END) + '|**|END|' + '$'
	        WHEN (vm.NearingPercentage >= 100) THEN '3' ELSE '3' END) as varchar) + '|' + mp.PlanName + '|**|END|' + '$'
		FROM rvlfVehicleMaintenanceService vm    
		INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId    
		INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId     
		INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId    
		INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId    
		INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId
		inner join rvlfMAKDevices D on  D.VehicleId=v.VehicleId
		INNER JOIN rvlfNotificationList nl ON nl.TypeID = vp.PlanId    
		INNER JOIN rvlfUser u ON u.UserId = nl.UserID    
		WHERE vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1 AND vm.IsNearing = 1 AND    
		CASE WHEN (vm.NearingPercentage >= pd.Notification1 AND vm.NearingPercentage < pd.Notification2 AND vm.IsNotification1Sent IS NULL) THEN 0     
		WHEN (vm.NearingPercentage >= pd.Notification2 AND vm.NearingPercentage < pd.Notification3 AND pd.Notification2 <> 0 AND vm.IsNotification2Sent IS NULL) THEN 1     
		WHEN (vm.NearingPercentage >= pd.Notification3 AND vm.NearingPercentage < 100 AND pd.Notification3 <> 0 AND vm.IsNotification3Sent IS NULL) THEN 2     
		WHEN (vm.NearingPercentage >= 100 AND (vm.NotificationDate IS NULL OR CONVERT(Varchar(10), vm.NotificationDate, 101) = CONVERT(Varchar(10), GETUTCDATE(), 101))) THEN 3    
		ELSE 4 END <> 4    
		AND nl.NotificationType = 8 AND nl.Email = 1 AND u.UserId = @bigUserID and D.BoxId=@boxID

		


		RETURN @vcServiceComment
	END    


	
GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetUserServiceNotifications]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[rvlf_fn_GetUserServiceNotifications]    
(    
 @bigUserID BIGINT    
)    
/******************************************************************************/    
-- Name  : rvlf_fn_GetUserServiceNotifications    
-- Description : To get the list of services to be notified for the particular user    
-- Author  : Kumuthini. L    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
/******************************************************************************/    
RETURNS varchar(MAX)    
AS    
BEGIN    
    
	DECLARE @ConversionFactor numeric (10,2) = 1.0    
    DECLARE @OdometerUnits Varchar(10) = ' km'
    DECLARE @DefaultDateFormat INT = 0            
    SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,    
    @OdometerUnits = CASE WHEN up.Distance = 0 THEN ' miles' ELSE ' km' END,
	@DefaultDateFormat=(case when  ISNULL(up.DefaultDateFormat,0)=0 then 106 else up.DefaultDateFormat end)    
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz    
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserID    
     
 DECLARE @vcServiceDetails VARCHAR(MAX) = NULL    
    
 SELECT @vcServiceDetails = ISNULL(@vcServiceDetails+'','') + ('<tr><td>' + v.VehicleDescription + '</td>' +    
 '<td>' + dbo.rvlf_fn_GetVehicleBasedFleets(v.VehicleId) + '</td><td>' + mp.PlanName + '</td>' +    
 '<td>' + (CASE WHEN vm.ServiceType = 0 THEN 'Running Hours' WHEN vm.ServiceType = 1 THEN 'Odometer Reading'WHEN vm.ServiceType = 2 THEN 'Time Based' ELSE 'Concrete Mix Hours' END) + '</td>' +    
 '<td>' + dbo.rvlf_fn_GetMaintenanceServices(5, mp.PlanId, NULL) + '</td>' +    
 '<td>' + CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3 THEN CONVERT(Varchar(10), (cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0))) + ' hrs'    
		WHEN vm.ServiceType = 1 THEN CONVERT(Varchar(11), CONVERT(INT, (cr.CurrentOdometerReading * @ConversionFactor))) + @OdometerUnits    
		WHEN vm.ServiceType = 2 THEN CONVERT(Varchar(11), GETUTCDATE(), @DefaultDateFormat) END + '</td>' +     
 '<td>' + (CASE WHEN vm.ServiceType = 0  OR vm.ServiceType = 3 THEN CONVERT(VARCHAR(11), vm.DueOn) WHEN vm.ServiceType = 1 THEN CONVERT(VARCHAR(11), CONVERT(INT, (vm.DueOn * @ConversionFactor))) ELSE CONVERT(VARCHAR(11), CONVERT(DATETIME, vm.DueOnDate), @DefaultDateFormat) END)    
     + (CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3 THEN ' hrs' WHEN vm.ServiceType = 1 THEN @OdometerUnits ELSE '' END) + '</td>' +    
 '<td>' + CONVERT(Varchar(15), vm.NearingPercentage) + '%' + '</td>' +    
 '<td>' + (CASE WHEN (vm.NearingPercentage >= pd.Notification1 AND vm.NearingPercentage < pd.Notification2) THEN 'Normal'     
      WHEN (vm.NearingPercentage >= pd.Notification2 AND vm.NearingPercentage < pd.Notification3 AND pd.Notification2 <> 0) THEN 'Warning'     
      WHEN (vm.NearingPercentage >= pd.Notification3 AND vm.NearingPercentage < 100 AND pd.Notification3 <> 0) THEN 'Critical'     
      WHEN (vm.NearingPercentage >= 100) THEN 'Critical'    
 ELSE 'None' END) + '</td></tr>')    
 FROM rvlfVehicleMaintenanceService vm    
 INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId    
 INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId     
 INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId    
 INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId    
 INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId    
 INNER JOIN rvlfNotificationList nl ON nl.TypeID = vp.PlanId    
 INNER JOIN rvlfUser u ON u.UserId = nl.UserID    
 WHERE vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1 AND vm.IsNearing = 1 AND    
 CASE WHEN (vm.NearingPercentage >= pd.Notification1 AND vm.NearingPercentage < pd.Notification2 AND vm.IsNotification1Sent IS NULL) THEN 0     
      WHEN (vm.NearingPercentage >= pd.Notification2 AND vm.NearingPercentage < pd.Notification3 AND pd.Notification2 <> 0 AND vm.IsNotification2Sent IS NULL) THEN 1     
      WHEN (vm.NearingPercentage >= pd.Notification3 AND vm.NearingPercentage < 100 AND pd.Notification3 <> 0 AND vm.IsNotification3Sent IS NULL) THEN 2     
      WHEN (vm.NearingPercentage >= 100 AND (vm.NotificationDate IS NULL OR CONVERT(Varchar(10), vm.NotificationDate, 101) = CONVERT(Varchar(10), GETUTCDATE(), 101))) THEN 3    
    ELSE 4 END <> 4    
 AND nl.NotificationType = 8 AND nl.Email = 1 AND u.UserId = @bigUserID    
    
 RETURN @vcServiceDetails    
    
END    
    
--SELECT dbo.rvlf_fn_GetUserServiceNotifications(37)    

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetUserServicePushNotifications]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[rvlf_fn_GetUserServicePushNotifications]    
(    
 @bigUserID BIGINT    
)    
/******************************************************************************/    
-- Name  : rvlf_fn_GetUserServiceNotifications    
-- Description : To get the list of services to be notified for the particular user    
-- Author  : Kumuthini. L    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
/******************************************************************************/    
RETURNS varchar(MAX)    
AS    
BEGIN    
    
	DECLARE @ConversionFactor numeric (10,2) = 1.0    
    DECLARE @OdometerUnits Varchar(10) = ' km'
    DECLARE @DefaultDateFormat INT = 0            
    SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,    
    @OdometerUnits = CASE WHEN up.Distance = 0 THEN ' miles' ELSE ' km' END,
	@DefaultDateFormat=(case when  ISNULL(up.DefaultDateFormat,0)=0 then 106 else up.DefaultDateFormat end)    
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz    
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserID    
     
 DECLARE @vcServiceDetails VARCHAR(MAX) = NULL    
    
 SELECT @vcServiceDetails = ISNULL(@vcServiceDetails+'','') + 
 ('Maintenance Notification - ' + 
	 (CASE WHEN (vm.NearingPercentage >= pd.Notification1 AND vm.NearingPercentage < pd.Notification2) THEN 'Normal'     
      WHEN (vm.NearingPercentage >= pd.Notification2 AND vm.NearingPercentage < pd.Notification3 AND pd.Notification2 <> 0) THEN 'Warning'     
      WHEN (vm.NearingPercentage >= pd.Notification3 AND vm.NearingPercentage < 100 AND pd.Notification3 <> 0) THEN 'Critical'     
      WHEN (vm.NearingPercentage >= 100) THEN 'Critical'    
 ELSE 'None' END) + ' - '  +  v.VehicleDescription 
 + '$' 
 + ' Maintenance service for  equipment ' + v.VehicleDescription  + ' is pending.' + CHAR(13) 
 + ' Plan: ' + mp.PlanName + CHAR(13) 
 + ' Services: ' 
 + (CASE WHEN vm.ServiceType = 0 THEN 'Running Hours' WHEN vm.ServiceType = 1 THEN 'Odometer Reading'WHEN vm.ServiceType = 2 THEN 'Time Based' ELSE 'Concrete Mix Hours' END) + CHAR(13)
 + ' Due on: '  + (CASE WHEN vm.ServiceType = 0  OR vm.ServiceType = 3 THEN CONVERT(VARCHAR(11), vm.DueOn) WHEN vm.ServiceType = 1 THEN CONVERT(VARCHAR(11), CONVERT(INT, (vm.DueOn * @ConversionFactor))) ELSE CONVERT(VARCHAR(11), CONVERT(DATETIME, vm.DueOnDate), @DefaultDateFormat) END)  + (CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3 THEN ' hrs' WHEN vm.ServiceType = 1 THEN @OdometerUnits ELSE '' END) + CHAR(13)
 + ' Current Date/Running Hrs: ' + 
   CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3 THEN CONVERT(Varchar(10), (cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0))) + ' hrs'    
		WHEN vm.ServiceType = 1 THEN CONVERT(Varchar(11), CONVERT(INT, (cr.CurrentOdometerReading * @ConversionFactor))) + @OdometerUnits    
		WHEN vm.ServiceType = 2 THEN CONVERT(Varchar(11), GETUTCDATE(), @DefaultDateFormat) END + CHAR(13)
+ ' Nearing %: ' + CONVERT(Varchar(15), vm.NearingPercentage) + '%') + '~'
 FROM rvlfVehicleMaintenanceService vm    
 INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId    
 INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId     
 INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId    
 INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId    
 INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId    
 INNER JOIN rvlfNotificationList nl ON nl.TypeID = vp.PlanId    
 INNER JOIN rvlfUser u ON u.UserId = nl.UserID    
 WHERE vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1 AND vm.IsNearing = 1 AND    
 CASE WHEN (vm.NearingPercentage >= pd.Notification1 AND vm.NearingPercentage < pd.Notification2 AND vm.IsNotification1Sent IS NULL) THEN 0     
      WHEN (vm.NearingPercentage >= pd.Notification2 AND vm.NearingPercentage < pd.Notification3 AND pd.Notification2 <> 0 AND vm.IsNotification2Sent IS NULL) THEN 1     
      WHEN (vm.NearingPercentage >= pd.Notification3 AND vm.NearingPercentage < 100 AND pd.Notification3 <> 0 AND vm.IsNotification3Sent IS NULL) THEN 2     
      WHEN (vm.NearingPercentage >= 100 AND (vm.NotificationDate IS NULL OR CONVERT(Varchar(10), vm.NotificationDate, 101) = CONVERT(Varchar(10), GETUTCDATE(), 101))) THEN 3    
    ELSE 4 END <> 4    
 AND nl.NotificationType = 8 AND nl.Email = 1 AND u.UserId = @bigUserID  
 
 select @vcServiceDetails=substring(@vcServiceDetails, 1, (len(@vcServiceDetails) - 1))
 
 RETURN @vcServiceDetails    
    
END    
    
--SELECT dbo.rvlf_fn_GetUserServiceNotifications(37)    

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetVehicleBasedFleets]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[rvlf_fn_GetVehicleBasedFleets] 
(
	@bigVehicleID bigint = NULL
)
RETURNS varchar(max)
AS
BEGIN
   DECLARE @vcFleetNames varchar(max)
		
   IF(@bigVehicleID IS NOT NULL)
   BEGIN
		
		SELECT @vcFleetNames = ISNULL(@vcFleetNames + ',', '')+ f.FleetName
	    FROM rvlfFleet f
	    INNER JOIN rvlfFleetVehicles fv ON fv.FleetId = f.FleetId
	    WHERE fv.VehicleId = @bigVehicleID
    
   END
       
	    
   RETURN @vcFleetNames
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetVehicleStatusNotification]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[rvlf_fn_GetVehicleStatusNotification]          
(          
 @bigOrganizationId Bigint = 0,          
 @dtEffectiveFrom DateTime = NULL,  
 @fleetId BIGINT = 0  
)          
/******************************************************************************/          
-- Name  : rvlf_fn_GetVehicleStatusNotification          
-- Description : To get the list of vehicles that are not reporting for 3 days           
--        from the Effective From Date for the Organization and forming          
--     the template for sending Email for the Org. Admin.          
-- Author  : Kumuthini. L          
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--          : 28-Mar-2012 Vijay -  Filter based on fleet  
/******************************************************************************/          
RETURNS varchar(MAX)          
AS          
BEGIN          
          
 DECLARE @vcDeviceStatus VARCHAR(MAX) = NULL          
                
 SELECT @vcDeviceStatus = ISNULL(@vcDeviceStatus+'','') + ('<tr><td>' + 
 (
 --CASE WHEN f.FleetName LIKE'%ALL%' THEN (SELECT VehicleDescription FROM rvlfVehicle WHERE vehicleId NOT IN(select vehicleId from rvlfFleetVehicles)) 
  --ELSE v.VehicleDescription END
  v.VehicleDescription ) + '</td>' +   '<td>'+
 (CASE WHEN f.FleetName LIKE'%ALL%' THEN 'ALL' ELSE f.FleetName END)+'</td>'+             
 '<td>' + CONVERT(VARCHAR(25), bi.LastStatusDateTime, 100) + '</td>' +           
 '<td>' + b.BoxMsgInTypeDesc + (CASE WHEN ih.StreetAddress IS NOT NULL AND ih.StreetAddress <> 'N/A' THEN ' - ' + ih.StreetAddress ELSE '' END) + '</td>' +           
 '<td>' + CONVERT(VARCHAR(10),DATEDIFF(DD, bi.LastStatusDateTime, GETUTCDATE())) + ' day(s)' + '</td></tr>')  
 FROM rvlfBoxId bi          
 INNER JOIN rvlfVehicleAssignment va ON va.BoxId = bi.BoxId           
 INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId          
 INNER JOIN rvlfMsgInHst ih ON ih.MessageInID = bi.MessageInId          
 INNER JOIN rvlfBoxMsgInType b ON b.BoxMsgInTypeId = ih.BoxMsgInTypeId        
 INNER JOIN rvlfFleetVehicles fv ON  fv.VehicleId = v.VehicleId       
 INNER JOIN rvlfFleet f ON  f.FleetId = fv.FleetId         
 WHERE   
 f.Fleetid = @fleetId AND   
 v.OrganizationId = @bigOrganizationId     
 AND bi.LastStatusDateTime > @dtEffectiveFrom            
-- AND DATEDIFF(DD, bi.LastStatusDateTime, GETUTCDATE()) > 3           
 AND cast (LastStatusDateTime AS DATE)   <  CAST (DATEADD(DAY, -3, GETUTCDATE()) AS DATE)      
       
 RETURN @vcDeviceStatus          
          
END 
GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_getWeekday]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_getWeekday]
    (
      @StartDate datetime,
       @EndDate datetime,
	   @weekday varchar(15)
    )
RETURNS @ReturnList TABLE
    (
      FieldValue datetime,
	  Weekdays varchar(2),
	  Daydate tinyint
    )
 
AS BEGIN 
	 
 ;with DateSequence
 as
 ( 
 select @StartDate Date union all select Date+1 from DateSequence where Date<@EndDate 
 )
INSERT  @ReturnList ( FieldValue,Weekdays,Daydate )
select date,DATEPART(weekday,date),DATEPART(day,date)  from DateSequence where (@weekday is null or datepart(WEEKDAY,Date) in (select FieldValue from  dbo.rvlf_fn_ConvertArrayToTable(@weekday,',')))
RETURN
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplate]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasue
-- Create date: 27-11-2015
-- Description:	To Fetch the KPI in HTML <li> format to display in the KPI Dashboard
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplate]
(
	-- Add the parameters for the function here
	@Sno				int,
	@Template			nvarchar(MAX),
	@TitleClrCode		nvarchar(10),
	@AssignmentID		int,
	@CustomTitle		nvarchar(75),
	@KPIID				int,
	@KPIName			nvarchar(75),
	@DisplayTypeID		tinyint,
	@CostKPIsValue		decimal(18,2),
	@TemperatureType	tinyint,
	@UnitName			nvarchar(10),
	@MinRange			int,
	@MaxRange			int,
	@FleetId			int,
	@BoxId				nvarchar(1000),
	@RefFreq			int,
	@Duration			int,
	@bigUserId			bigint,
	@bigOrganizationID	bigint
)				
RETURNS		nvarchar(MAX)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @BoxIds					TABLE (BOXID bigint,VehicleId INT,VehicleDescription nVarchar(150))
	DECLARE @ChangedTemplate		nvarchar(MAX)
	DECLARE @CurrValue				int
	DECLARE @CurrValueFormatted		nvarchar(50)
	DECLARE @intBoxID				int
	DECLARE @dtStartDate			datetime = NULL  
 	DECLARE @dtEndDate				datetime = NULL

	SET @dtStartDate = DATEADD(Hour,-@Duration,GETUTCDATE())
	SET @dtEndDate = GETUTCDATE()
	
	INSERT	INTO @BoxIds (BOXID,VehicleId,VehicleDescription)
	SELECT	va.BoxID,v.VehicleId,v.VehicleDescription FROM rvlfVehicleAssignment va
	INNER	JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
	INNER	JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
	WHERE	fv.FleetId = @FleetId AND (@BoxId IS NULL OR @BoxId = '0' OR @BoxId = '' or
    BoxId	in (select * from rvlf_fn_ConvertArrayToTable(@BoxId,','))) AND V.OrganizationId = @bigOrganizationID
    ORDER	BY BoxId
	
	--SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@BoxId,',')
		 
	DECLARE @Lang varchar(50)       
	SELECT @Lang=isnull(Lang,'LanguageEn') FROM rvlfUserPreferences WHERE UserId = @bigUserId

    DECLARE @DefaultDateFormat INT = 0     
	SELECT  @DefaultDateFormat=(CASE WHEN  isnull(up.DefaultDateFormat,0)= 0 THEN 106 ELSE up.DefaultDateFormat END)      
	FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId      
            
	IF @FleetId IS NULL      
	BEGIN      
		SELECT @FleetId=FleetID FROM rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1      
	END      
	DECLARE @HoursToBeAdded INT = 0      
	DECLARE @MinsToBeAdded INT = 0      
	DECLARE @ConversionFactor NUMERIC (10,2) = 1.0      
	DECLARE @DistanceCaptionPrefix VARCHAR(15)      
	DECLARE @SpeedCaptionPrefix VARCHAR(15)      
	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
			@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,        
			@DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Kms)' END,      
			@SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END      
	FROM	rvlfUserPreferences up 
	INNER	JOIN rvlfTimeZones tz ON	up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId          
          
	--SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))      
	--SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                 
    
	DECLARE @dtFDate DATETIME = @dtStartDate    
	DECLARE @dtEDate DATETIME = @dtEndDate
	  
	DECLARE @tblVehicles TABLE      
	(
		VehicleId bigint,
		VehicleDescription nvarchar(50),
		LicensePlate varchar(50),
		Vin varchar(50),
		Boxid bigint,
		NoofTrips int,
		Distance int,
		RunningTime INT,
		IdlingTime INT,
		DaysUtilizaed varchar(30),
		FleetName varchar(50),
		SpeedViolations		int,
		HarshAcceleration	int,
		ExtremeAcceleration	int,
		HarshBraking		int,
		ExtremeBraking		int,
		Temperature			int
	)
      
	DECLARE @tblMessageForProcessingTrip TABLE (      
		[ProcessorID] [bigint] identity(1,1) NOT NULL,
		[Boxid] [int] NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[IgnitionStatus] [bit] NULL,
		[CustomProp] [varchar](600) NULL,
		[TripId] [bigint] NULL
	)      

	INSERT	INTO @tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin,FleetName)      
	SELECT	VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin,f.FleetName  
	FROM	rvlfBoxId BI
	INNER	JOIN rvlfVehicleAssignment VA ON BI.BoxId=VA.BoxId       
	INNER	JOIN rvlfFleetVehicles FV ON FV.VehicleId =VA.VehicleId       
	INNER	JOIN rvlfFleet F ON FV.FleetId=F.FleetId       
	INNER	JOIN rvlfVehicle V ON FV.VehicleId=V.VehicleId       
	INNER	JOIN rvlfOrganization O ON O.OrganizationId =F.OrganizationId       
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR V.OrganizationId =@bigOrganizationID AND F.OrganizationId =@bigOrganizationID)      
	AND		(@FleetId IS NULL OR @FleetId='' OR F.FleetId=@FleetId)      
	AND		VA.BoxId IN (SELECT BOXID FROM @BoxIds)      
	ORDER	BY BI.BOXID             

	--GET THE TRIPS      
	DECLARE @tblTrips TABLE      
	(      
		ProcessId bigint identity(1,1),      
		Boxid int null,        
		TripTime datetime null,      
		TripStatus varchar(10)null      
	)       
       
	--GET THE TRIP DETAILS      
	DECLARE @tblTripDetails TABLE      
	(        
		TripId bigint identity(1,1),      
		Boxid int null,        
		StartTime datetime null,      
		EndTime datetime null,      
		TripInStatus varchar(5) null,      
		TripOutStatus varchar(5) null,      
		RunningTime int null,      
		IdlingTime int null       
	)        
      
	DECLARE @intBoxLoop int =(SELECT MIN(Boxid) FROM @tblVehicles)      
      
	WHILE @intBoxLoop IS NOT NULL      
	BEGIN       
		DELETE FROM @tblMessageForProcessingTrip        
		INSERT INTO @tblMessageForProcessingTrip(Boxid,OriginDateTime,BoxMsgInTypeId,IgnitionStatus,CustomProp)      
		SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,      
		CAST(SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,h.CustomProp             
		FROM rvlfMsgInHst h       
		INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                    
		WHERE m.OperationTypeID IN (SELECT p.OperationID  FROM rvlfPackageOperations p WHERE p.PackageId =       
		(SELECT op.PackageId FROM rvlfOrganizationPackage op WHERE op.OrganizationID = @bigOrganizationID      
		AND op.IsActive=1)      
		AND p.ModuleID = 26) and m.OperationTypeID IS NOT NULL                      
		AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
		AND h.BoxID = @intBoxLoop      
		ORDER BY h.origindatetime ASC        
          
		--CALCULATE THE DISTANCE
		UPDATE @tblVehicles SET Distance = (SELECT CEILING((MAX(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,1))) -      
				(CHARINDEX('Odometer=',CustomProp,1)+9)),0) AS BIGINT)) - MIN(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,      
				CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9)),0)AS BIGINT))) * @ConversionFactor)  AS DISTANCE      
				FROM @tblMessageForProcessingTrip M         
				WHERE  (M.BoxId= @intBoxLoop)      
				AND (M.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)      
				AND CustomProp LIKE '%Odometer%' AND BoxMsgInTypeId in(2,3)),
				SpeedViolations = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 4) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 14) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 15) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 16) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 17) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				Temperature = (SELECT COUNT(BoxMsgInTypeId) from @tblMessageForProcessingTrip where BoxId = @intBoxLoop and BoxMsgInTypeId = (CASE @TemperatureType WHEN 1 THEN 82 WHEN 2 THEN 86 WHEN 3 THEN 166 WHEN 4 THEN 171 ELSE 0 END))
		WHERE Boxid =@intBoxLoop AND Distance IS NULL      
        
		--CALCULATE THE UTILIZED DAYS
		UPDATE @tblVehicles SET DaysUtilizaed =(SELECT CASE WHEN COUNT(Actions)>CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) THEN CAST(COUNT(Actions)-1 as varchar) ELSE CAST(COUNT(Actions) as varchar) END  
												--+ ' out of '+CAST( CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) AS VARCHAR) 
												FROM (SELECT COUNT(BoxId) AS Actions       
		FROM @tblMessageForProcessingTrip        
		WHERE BoxId=@intBoxLoop AND    
		(OriginDateTime BETWEEN  dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtStartDate) AND dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtEndDate))    
		--(OriginDateTime BETWEEN DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtStartDate)) AND DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEndDate)))    
		AND BoxMsgInTypeId IN (2,3)      
		GROUP BY CONVERT(DATE,OriginDateTime))AS A)      
		WHERE Boxid =@intBoxLoop AND DaysUtilizaed IS NULL      
        
		--CALCULATE THE NOOFTRIPS,RUNNING TIME AND IDLING TIME
		DELETE FROM @tblTrips       
		DELETE FROM @tblTripDetails       
		INSERT INTO @tblTrips (Boxid,TripTime,TripStatus)      
		SELECT BoxId,OriginDateTime,CASE WHEN BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'START'       
		WHEN BoxMsgInTypeId =3 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'STOP' ELSE NULL END          
		FROM rvlfMsgInHst       
		WHERE Boxid =@intBoxLoop      
		AND BoxMsgInTypeId IN(2,3)                
		AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate        
		ORDER BY BoxId,OriginDateTime       
          
		INSERT INTO @tblTripDetails (Boxid,EndTime,TripOutStatus,StartTime,TripInStatus)      
		SELECT MT.Boxid,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus      
		FROM @tblTrips AS MT       
		LEFT OUTER JOIN @tblTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'START'       
         
		--DELETE THE INVALID TRIPS      
		DELETE FROM @tblTripDetails WHERE StartTime IS NULL OR TripInStatus=TripOutStatus        
         
		--CALCULATE THE RUNNING TIME AND IDLING TIME       
		UPDATE @tblTripDetails SET RunningTime =DATEDIFF(S,StartTime,EndTime),      
		IdlingTime=(SELECT SUM(ISNULL(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,      
		(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT),0))                   
		FROM @tblMessageForProcessingTrip  WHERE Boxid=@intBoxLoop AND BoxMsgInTypeId =9 AND OriginDateTime BETWEEN StartTime AND EndTime AND CustomProp NOT LIKE '%Idling:0;%')      
        
		--UPDATE THE DETAILS TO MAIN TABLE      
		UPDATE @tblVehicles SET NoofTrips =(SELECT COUNT(TripId) FROM @tblTripDetails),      
		RunningTime=(SELECT SUM(RunningTime) FROM @tblTripDetails),      
		IdlingTime=(SELECT SUM(IdlingTime) FROM @tblTripDetails)            
		WHERE Boxid=@intBoxLoop        
           
		SELECT @intBoxLoop = MIN(Boxid) FROM @tblVehicles WHERE Boxid >@intBoxLoop       
	END      
    
	--Fetching KPI Details
	DECLARE @intLoopi int = NULL
	SELECT	@intLoopi = MIN(BoxId) FROM @tblVehicles 
	
	DECLARE @vcDetailData VARCHAR(MAX) = ''
	DECLARE @tblDetailData TABLE(BoxId bigint primary key, VehicleDescription nvarchar(50),IdlingDuration nvarchar(10),IdlingPercentage numeric(18,2),
								 DistanceTraveled int,SpeedViolations int, ExtremeAcceleration int, ExtremeBraking int, VehicleUtilization nvarchar(10), TemperatureHigh int)

	WHILE @intLoopi IS NOT NULL
	BEGIN
		INSERT	INTO @tblDetailData 
		SELECT	BoxId, VehicleDescription,ISNULL(IdlingTime,0),CAST(ISNULL((IdlingTime*1.00)/CASE WHEN(ISNULL(RunningTime,0)*1.00) = 0 THEN 1 
											ELSE (ISNULL(RunningTime,0)*1.00) END *100,0) AS NUMERIC(8,2)),
											CASE WHEN ISNULL(Distance,0) = 0 THEN '-' ELSE CAST(Distance AS VARCHAR) END,
				--CASE WHEN	ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END 
				--FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)),0) = 0 THEN '-' 
				--ELSE CAST((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance 
				--ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)) AS VARCHAR) END,
				SpeedViolations, ExtremeAcceleration + HarshAcceleration, ExtremeBraking + HarshBraking, DaysUtilizaed, Temperature			-- Harsh and Extreme values combined for Acceleration & Braking on 22-01-2016 by AnbarasuE
		FROM	@tblVehicles  
		WHERE	Boxid = @intLoopi
				
		SELECT	@vcDetailData = @vcDetailData + 
					(CASE @KPIID 
					WHEN 1 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(dbo.rvlf_fn_GetHHMMSSFromSec(IdlingDuration) AS VARCHAR) + ' </td><td>' + CASE WHEN (IdlingDuration/3600 < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (IdlingDuration/3600 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 2 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(IdlingPercentage AS VARCHAR) + ' </td><td>' + CASE	WHEN (IdlingPercentage < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (IdlingPercentage > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (IdlingPercentage BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 3 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(DistanceTraveled AS VARCHAR) + ' </td><td>' + CASE	WHEN (DistanceTraveled < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (DistanceTraveled > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (DistanceTraveled BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 4 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(SpeedViolations AS VARCHAR) + ' </td><td>' + CASE	WHEN (SpeedViolations < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (SpeedViolations > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (SpeedViolations BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 5 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeAcceleration AS VARCHAR) + ' </td><td>' + CASE	WHEN (ExtremeAcceleration < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (ExtremeAcceleration > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (ExtremeAcceleration BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 6 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeBraking AS VARCHAR) + ' </td><td>' + CASE	WHEN (ExtremeBraking < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (ExtremeBraking > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (ExtremeBraking BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 7 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(VehicleUtilization AS VARCHAR)+ ' </td><td>'+ CASE	WHEN (VehicleUtilization < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (VehicleUtilization > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (VehicleUtilization BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 9 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,(DistanceTraveled * @CostKPIsValue)),3) + ' </td><td>' + CASE	WHEN ((DistanceTraveled * @CostKPIsValue) < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN ((DistanceTraveled * @CostKPIsValue) > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN ((DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 10 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,((IdlingDuration * @CostKPIsValue)/3600)),3) + ' </td><td>' + CASE	WHEN (((IdlingDuration * @CostKPIsValue)/3600) < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 11 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(TemperatureHigh AS VARCHAR)+ ' </td><td>'+ CASE	WHEN (TemperatureHigh < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (TemperatureHigh > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (TemperatureHigh BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					ELSE '<tr><td colspan="3">No data found.</td></tr>'
					END)
		FROM	@tblDetailData  
		WHERE	BoxId = @intLoopi
		
		SELECT @intLoopi = MIN(BoxId) FROM @tblVehicles WHERE Boxid > @intLoopi
	END

	--Fetching KPI Summary
	DECLARE @totIdlingTime			INT = NULL      
	DECLARE @totIdlingPercent		NUMERIC(18,2) = NULL
	DECLARE @totDistanceTraveled	INT = NULL      
	DECLARE @totDaysUtilized		INT = NULL
	DECLARE @totTemperatureHigh		INT = NULL

	SELECT	@totIdlingTime		= SUM(CAST(IdlingDuration AS INT)),
			@totIdlingPercent	= CEILING(AVG(IdlingPercentage)),
			@totDistanceTraveled= SUM(ISNULL(DistanceTraveled,0)),
			@totDaysUtilized	= CAST(ROUND(AVG(CAST(VehicleUtilization AS NUMERIC(18,2))),0)AS INT),
			@totTemperatureHigh = SUM(CAST(TemperatureHigh AS INT))
	FROM	@tblDetailData

	-- Fetching KPI Chart data
	DECLARE @intSafe		VARCHAR(5) = NULL
	DECLARE @intWarning		VARCHAR(5) = NULL
	DECLARE @intCritical	VARCHAR(5) = NULL

	
	-- Template replacing with KPI values based on KPI Type
	IF (@KPIID = 1) 
	BEGIN
		--SELECT	@CurrValue = (SUM(msg.duration)), @CurrValueFormatted = (dbo.rvlf_fn_GetTimeFromSeconds(SUM(msg.duration))) --CAST(dbo.rvlf_fn_GetParamValueWithIndex(msg.CustomProp,'Idling:',';') AS bigint)))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) --AND msg.BoxMsgInTypeId = 9 --AND CHARINDEX('Idling',CustomProp,0)>0
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		SELECT	@CurrValue = @totIdlingTime/3600, @CurrValueFormatted = dbo.rvlf_fn_GetHHMMSSFromSec(@totIdlingTime)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 > @MaxRange
	END
	ELSE IF (@KPIID = 2) 
	BEGIN	
		SELECT	@CurrValue = @totIdlingPercent, @CurrValueFormatted = @totIdlingPercent
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage > @MaxRange
	END
	ELSE IF (@KPIID = 3) 
	BEGIN	
		--SELECT	@CurrValue = (MAX(msg.odometer)-MIN(msg.odometer))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) AND msg.OriginDateTime Between @dtFDate and @dtEDate
		--GROUP BY msg.BoxId
		SELECT	@CurrValue = @totDistanceTraveled, @CurrValueFormatted = @totDistanceTraveled
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled > @MaxRange
	END
	ELSE IF (@KPIID = 4) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=4 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(SpeedViolations),0), @CurrValueFormatted = ISNULL(SUM(SpeedViolations),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations > @MaxRange
	END
	ELSE IF (@KPIID = 5) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=15 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeAcceleration),0), @CurrValueFormatted = ISNULL(SUM(ExtremeAcceleration),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration > @MaxRange
	END
	ELSE IF (@KPIID = 6) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=17 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeBraking),0), @CurrValueFormatted = ISNULL(SUM(ExtremeBraking),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking > @MaxRange
	END
	ELSE IF (@KPIID = 7) 
	BEGIN
		SELECT	@CurrValue = @totDaysUtilized, @CurrValueFormatted = @totDaysUtilized
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization > @MaxRange
		--SELECT	@CurrValue = COUNT(*) FROM rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) 
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		--AND		msg.BoxMsgInTypeId = 1
		--Group By msg.BoxId
	END
	ELSE IF(@KPIID = 9)
	BEGIN 
		SELECT	@CurrValue = (@totDistanceTraveled * @CostKPIsValue), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,(@totDistanceTraveled * @CostKPIsValue)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) > @MaxRange
	END
	ELSE IF(@KPIID = 10)
	BEGIN 
		SELECT	@CurrValue = ((@totIdlingTime * @CostKPIsValue)/3600), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,((@totIdlingTime * @CostKPIsValue)/3600)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange
	END			
	ELSE IF(@KPIID = 11)
	BEGIN 
		SELECT	@CurrValue = @totTemperatureHigh, @CurrValueFormatted = @totTemperatureHigh
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh > @MaxRange
	END
	ELSE 
	BEGIN
		SELECT @CurrValueFormatted = '15' 
	END
	
	SELECT	@UnitName = CurrencyName FROM rvlfCurrencyType CT
	INNER	JOIN rvlfOrganization O ON CT.CurrencyTypeId = O.CurrencyTypeId
	WHERE	OrganizationId = @bigOrganizationID	and @KPIID in (9,10)

	-- Add the T-SQL statements to compute the return value here
	SET	@Template	= REPLACE(@Template ,'$ChartScript$', 'google.setOnLoadCallback(drawChart_$Sno$);function drawChart_$Sno$() {
										var data = new google.visualization.arrayToDataTable([[''Bands'', ''No.of.Vehicles'', { role: ''style'' }],[''Safe'', '+ ISNULL(@intSafe,0) +', ''#04B713''],[''Warning'', '+ ISNULL(@intWarning,0) +', ''#FF7F00''],[''Critical'', '+ ISNULL(@intCritical,0) +', ''#FE0000''],]);
										var options = {width: 500,height: 400,colors: [''Red''],chartArea: { width: ''50%'' },hAxis: {title: ''KPI Status'',minValue: 0},vAxis: {title: ''No.of.Vehicles'',maxValue: 16,format: ''0'',gridlines: { count: 6 },minorGridlines: { count: 3 }}, legend: { position: "none" }};
										var chart = new google.visualization.ColumnChart(document.getElementById(''chart_div_$Sno$''));chart.draw(data, options);}')
	SET	@Template	= REPLACE(@Template ,'$Sno$', @Sno)
	SET	@Template	= REPLACE(@Template ,'$gridData$', '<thead><th>Vehicle</th><th>$KPICaption$</th><th>Status</th></thead><tbody>'+ @vcDetailData +'</tbody>')
	SET	@Template	= REPLACE(@Template ,'$AssignmentID$', @AssignmentID)
	SET	@Template	= REPLACE(@Template ,'$KPIUnitName$', @UnitName)

	DECLARE @KPIStatus nvarchar(10)
	SET @KPIStatus = CASE WHEN (@CurrValue < @MinRange) THEN 'safe' WHEN (@CurrValue > @MaxRange) THEN 'critical' WHEN (@CurrValue between @MinRange and @MaxRange) THEN 'warning' ELSE 'safe' END
	
	SET	@Template	= REPLACE(@Template ,'$TileImgName$', 'img-' + @KPIStatus + '-kpi')
	SET	@Template	= REPLACE(@Template ,'$KPIValue$', @CurrValueFormatted)
	--SET	@Template	= REPLACE(@Template ,'$PnlTableClass2$', @KPIStatus)
	SET	@Template	= REPLACE(@Template ,'$PnlTableClass1$', CASE @DisplayTypeID WHEN 1  THEN 'tiletable' WHEN 2 THEN 'gaugetable' WHEN 3 THEN 'progresstable' WHEN 4 THEN 'tiletable' WHEN 5 THEN 'gridtable' END)
	SET	@Template	= REPLACE(@Template ,'$PanelClass$', CASE @DisplayTypeID WHEN 1 THEN 'tilediv' WHEN 2 THEN 'gaugediv' WHEN 3 THEN 'progressdiv' WHEN 4 THEN 'chartsdiv' WHEN 5 THEN 'griddiv' END)
	
	DECLARE @CustomTitleLen int 
	SET @CustomTitleLen = CASE @DisplayTypeID WHEN 1 THEN 25 ELSE 55 END 
	SET	@Template	= REPLACE(@Template ,'$CustomTitle$', CASE WHEN LEN(@CustomTitle) > @CustomTitleLen THEN SUBSTRING(@CustomTitle, 0, @CustomTitleLen) + '...' ELSE @CustomTitle END)
	SET	@Template	= REPLACE(@Template ,'$Tooltip$', @CustomTitle)
	SET	@Template	= REPLACE(@Template ,'$dataSize-y$', CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 3 THEN 2 WHEN 4 THEN 3 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataSize-x$', CASE @DisplayTypeID WHEN 1 THEN 2 WHEN 2 THEN 2 WHEN 3 THEN 2 WHEN 4 THEN 4 WHEN 5 THEN 4 END)
	SET	@Template	= REPLACE(@Template ,'$dataRows$', CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 3 THEN 3 WHEN 4 THEN 4 WHEN 5 THEN 5 END)  --CASE @Sno WHEN 1 THEN 1 WHEN 1 THEN 1 WHEN 3 THEN 1 WHEN 4 THEN 1 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataCols$', CASE WHEN @Sno < 5 THEN @Sno ELSE 4 END)
	SET	@Template	= REPLACE(@Template ,'$KPICaption$', /*LOWER(@KPIName) + */ 'Value(' + @UnitName + ')')
	SET @Template	= REPLACE(@Template, '$TitleColor$', 'style="background-color: ' + CASE WHEN @TitleClrCode IS NOT NULL THEN '#457DC7' ELSE @TitleClrCode END + '"')

	DECLARE @FleetName nvarchar(250)
	SET @FleetName	= (SELECT FleetName FROM rvlfFleet WHERE FleetId = @FleetId)
	SET	@Template	= REPLACE(@Template ,'$Fleet$', @FleetName)

	--DECLARE @Vehicles Table(VehicleId bigint, VehicleDescription nvarchar(50))
	--INSERT INTO @Vehicles 
	--SELECT v.VehicleId,v.VehicleDescription FROM rvlfVehicle v 
	--INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId 
	--WHERE va.BoxId IN (SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI]	(@BoxId,','))

	--DECLARE @minVehicleId bigint
	--SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles
	--DECLARE @VehicleName nvarchar(1000)

	--WHILE @minVehicleId IS NOT NULL
	--BEGIN
	--	IF @VehicleName IS NOT NULL
	--	BEGIN
	--		SET @VehicleName = @VehicleName + ',' + (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	ELSE
	--	BEGIN
	--		SET @VehicleName = (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles WHERE VehicleId > @minVehicleId
	--END

	SET	@Template	= REPLACE(@Template ,'$Vehicles$',	CASE @BoxId	WHEN '0' THEN 'All' 
														ELSE STUFF((SELECT ', ' + VehicleDescription FROM @BoxIds FOR XML PATH('')), 1, 1, '') END)
	SET	@Template	= REPLACE(@Template ,'$RefreshFreq$', CAST(@RefFreq AS VARCHAR(5)) + ' Sec')
	SET	@Template	= REPLACE(@Template ,'$Duration$', 'Last ' + CASE	WHEN @Duration = 168	THEN ' 1 Week'
																		WHEN @Duration Between 48 and 168	THEN CAST(@Duration/24 AS Varchar(20)) + ' Days' 
																		ELSE CAST(@Duration AS Varchar(20)) + ' Hours' END)
	
	SET	@Template	= REPLACE(@Template ,'$Range$', ((CASE	WHEN @KPIID IN (9,10) THEN (CONVERT(VARCHAR,CONVERT(MONEY,@MinRange),3) + ' to ' + CONVERT(VARCHAR,CONVERT(MONEY,@MaxRange),3))
															ELSE (CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20))) END)  
															+ ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END))

	SET @Template	= @Template + '<input type="hidden" value="KPIStatus:' + @KPIStatus + '">'
		
	-- Return the result of the function	
	SET	@ChangedTemplate = @Template
	RETURN @ChangedTemplate
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplate_PhoneGap]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Anbarasue
-- Create date: 27-11-2015
-- Description:	To Fetch the KPI in HTML <li> format to display in the KPI Dashboard
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplate_PhoneGap]
(
	-- Add the parameters for the function here
	@Sno				int,
	@Template			nvarchar(MAX),
	@TitleClrCode		nvarchar(10),
	@AssignmentID		int,
	@CustomTitle		nvarchar(75),
	@KPIID				int,
	@KPIName			nvarchar(75),
	@DisplayTypeID		tinyint,
	@CostKPIsValue		decimal(18,2),
	@UnitName			nvarchar(10),
	@MinRange			int,
	@MaxRange			int,
	@FleetId			int,
	@BoxId				nvarchar(1000),
	@RefFreq			int,
	@Duration			int,
	@bigUserId			bigint,
	@bigOrganizationID	bigint
)				
RETURNS		nvarchar(MAX)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @BoxIds					TABLE (BOXID bigint,VehicleId INT,VehicleDescription nVarchar(150))
	DECLARE @ChangedTemplate		nvarchar(MAX)
	DECLARE @CurrValue				int
	DECLARE @CurrValueFormatted		nvarchar(50)
	DECLARE @intBoxID				int
	DECLARE @dtStartDate			datetime = NULL  
 	DECLARE @dtEndDate				datetime = NULL

	SET @dtStartDate = DATEADD(Hour,-@Duration,GETUTCDATE())
	SET @dtEndDate = GETUTCDATE()
	
	INSERT	INTO @BoxIds (BOXID,VehicleId,VehicleDescription)
	SELECT	va.BoxID,v.VehicleId,v.VehicleDescription FROM rvlfVehicleAssignment va
	INNER	JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
	INNER	JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
	WHERE	fv.FleetId = @FleetId AND (@BoxId IS NULL OR @BoxId = '0' OR @BoxId = '' or
    BoxId	in (select * from rvlf_fn_ConvertArrayToTable(@BoxId,','))) AND V.OrganizationId = @bigOrganizationID
    ORDER	BY BoxId
	
	--SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@BoxId,',')
		 
	DECLARE @Lang varchar(50)       
	SELECT @Lang=isnull(Lang,'LanguageEn') FROM rvlfUserPreferences WHERE UserId = @bigUserId

    DECLARE @DefaultDateFormat INT = 0     
	SELECT  @DefaultDateFormat=(CASE WHEN  isnull(up.DefaultDateFormat,0)= 0 THEN 106 ELSE up.DefaultDateFormat END)      
	FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId      
            
	IF @FleetId IS NULL      
	BEGIN      
		SELECT @FleetId=FleetID FROM rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1      
	END      
	DECLARE @HoursToBeAdded INT = 0      
	DECLARE @MinsToBeAdded INT = 0      
	DECLARE @ConversionFactor NUMERIC (10,2) = 1.0      
	DECLARE @DistanceCaptionPrefix VARCHAR(15)      
	DECLARE @SpeedCaptionPrefix VARCHAR(15)      
	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
			@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,        
			@DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Kms)' END,      
			@SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END      
	FROM	rvlfUserPreferences up 
	INNER	JOIN rvlfTimeZones tz ON	up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId          
          
	--SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))      
	--SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                 
    
	DECLARE @dtFDate DATETIME = @dtStartDate    
	DECLARE @dtEDate DATETIME = @dtEndDate
	  
	DECLARE @tblVehicles TABLE      
	(
		VehicleId bigint,
		VehicleDescription nvarchar(50),
		LicensePlate varchar(50),
		Vin varchar(50),
		Boxid bigint,
		NoofTrips int,
		Distance int,
		RunningTime INT,
		IdlingTime BIGINT,
		DaysUtilizaed varchar(30),
		FleetName varchar(50),
		SpeedViolations		int,
		HarshAcceleration	int,
		ExtremeAcceleration	int,
		HarshBraking		int,
		ExtremeBraking		int
	)
      
	DECLARE @tblMessageForProcessingTrip TABLE (      
		[ProcessorID] [bigint] identity(1,1) NOT NULL,
		[Boxid] [int] NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[IgnitionStatus] [bit] NULL,
		[CustomProp] [varchar](600) NULL,
		[TripId] [bigint] NULL
	)      

	INSERT	INTO @tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin,FleetName)      
	SELECT	VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin,f.FleetName  
	FROM	rvlfBoxId BI
	INNER	JOIN rvlfVehicleAssignment VA ON BI.BoxId=VA.BoxId       
	INNER	JOIN rvlfFleetVehicles FV ON FV.VehicleId =VA.VehicleId       
	INNER	JOIN rvlfFleet F ON FV.FleetId=F.FleetId       
	INNER	JOIN rvlfVehicle V ON FV.VehicleId=V.VehicleId       
	INNER	JOIN rvlfOrganization O ON O.OrganizationId =F.OrganizationId       
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR V.OrganizationId =@bigOrganizationID AND F.OrganizationId =@bigOrganizationID)      
	AND		(@FleetId IS NULL OR @FleetId='' OR F.FleetId=@FleetId)      
	AND		VA.BoxId IN (SELECT BOXID FROM @BoxIds)      
	ORDER	BY BI.BOXID             

	--GET THE TRIPS      
	DECLARE @tblTrips TABLE      
	(      
		ProcessId bigint identity(1,1),      
		Boxid int null,        
		TripTime datetime null,      
		TripStatus varchar(10)null      
	)       
       
	--GET THE TRIP DETAILS      
	DECLARE @tblTripDetails TABLE      
	(        
		TripId bigint identity(1,1),      
		Boxid int null,        
		StartTime datetime null,      
		EndTime datetime null,      
		TripInStatus varchar(5) null,      
		TripOutStatus varchar(5) null,      
		RunningTime int null,      
		IdlingTime int null       
	)        
      
	DECLARE @intBoxLoop int =(SELECT MIN(Boxid) FROM @tblVehicles)      
      
	WHILE @intBoxLoop IS NOT NULL      
	BEGIN       
		DELETE FROM @tblMessageForProcessingTrip        
		INSERT INTO @tblMessageForProcessingTrip(Boxid,OriginDateTime,BoxMsgInTypeId,IgnitionStatus,CustomProp)      
		SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,      
		CAST(SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,h.CustomProp             
		FROM rvlfMsgInHst h       
		INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                    
		WHERE m.OperationTypeID IN (SELECT p.OperationID  FROM rvlfPackageOperations p WHERE p.PackageId =       
		(SELECT op.PackageId FROM rvlfOrganizationPackage op WHERE op.OrganizationID = @bigOrganizationID      
		AND op.IsActive=1)      
		AND p.ModuleID = 26) and m.OperationTypeID IS NOT NULL                      
		AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
		AND h.BoxID = @intBoxLoop      
		ORDER BY h.origindatetime ASC        
          
		--CALCULATE THE DISTANCE
		--UPDATE @tblVehicles SET Distance = (SELECT CEILING((MAX(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,1))) -      
		--		(CHARINDEX('Odometer=',CustomProp,1)+9)),0) AS BIGINT)) - MIN(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,      
		--		CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9)),0)AS BIGINT))) * @ConversionFactor)  AS DISTANCE      
		--		FROM @tblMessageForProcessingTrip M         
		--		WHERE  (M.BoxId= @intBoxLoop)      
		--		AND (M.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)      
		--		AND CustomProp LIKE '%Odometer%' AND BoxMsgInTypeId in(2,3)),
		--		SpeedViolations = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 4) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		--		HarshAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 14) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		--		ExtremeAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 15) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		--		HarshBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 16) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		--		ExtremeBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 17) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate))
		--WHERE Boxid =@intBoxLoop AND Distance IS NULL      
        
		UPDATE	@tblVehicles SET		
				Distance = (Select Sum(ISNULL(DateDiff(Hour,StartDate,EndDate),0)) From [dbo].[adr_rvlfTripDetails] Where BoxId=@intBoxLoop),
				SpeedViolations = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 4) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 14) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 15) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				--ExtremeAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 15) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 16) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 17) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate))
		WHERE	Boxid = @intBoxLoop AND Distance IS NULL


		--CALCULATE THE UTILIZED DAYS
		UPDATE @tblVehicles SET DaysUtilizaed =(SELECT CASE WHEN COUNT(Actions)>CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) THEN CAST(COUNT(Actions)-1 as varchar) ELSE CAST(COUNT(Actions) as varchar) END  
												--+ ' out of '+CAST( CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) AS VARCHAR) 
												FROM (SELECT COUNT(BoxId) AS Actions       
		FROM @tblMessageForProcessingTrip        
		WHERE BoxId=@intBoxLoop AND    
		(OriginDateTime BETWEEN  dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtStartDate) AND dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtEndDate))    
		--(OriginDateTime BETWEEN DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtStartDate)) AND DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEndDate)))    
		AND BoxMsgInTypeId IN (2,3)      
		GROUP BY CONVERT(DATE,OriginDateTime))AS A)      
		WHERE Boxid =@intBoxLoop AND DaysUtilizaed IS NULL      
        
		--CALCULATE THE NOOFTRIPS,RUNNING TIME AND IDLING TIME
		DELETE FROM @tblTrips       
		DELETE FROM @tblTripDetails       
		INSERT INTO @tblTrips (Boxid,TripTime,TripStatus)      
		SELECT BoxId,OriginDateTime,CASE WHEN BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'START'       
		WHEN BoxMsgInTypeId =3 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'STOP' ELSE NULL END          
		FROM rvlfMsgInHst       
		WHERE Boxid =@intBoxLoop      
		AND BoxMsgInTypeId IN(2,3)                
		AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate        
		ORDER BY BoxId,OriginDateTime       
          
		INSERT INTO @tblTripDetails (Boxid,EndTime,TripOutStatus,StartTime,TripInStatus)      
		SELECT MT.Boxid,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus      
		FROM @tblTrips AS MT       
		LEFT OUTER JOIN @tblTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'START'       
         
		--DELETE THE INVALID TRIPS      
		DELETE FROM @tblTripDetails WHERE StartTime IS NULL OR TripInStatus=TripOutStatus        
         
		--CALCULATE THE RUNNING TIME AND IDLING TIME       
		UPDATE @tblTripDetails SET RunningTime =DATEDIFF(S,StartTime,EndTime),      
		IdlingTime=(SELECT SUM(ISNULL(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,      
		(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT),0))                   
		FROM @tblMessageForProcessingTrip  WHERE Boxid=@intBoxLoop AND BoxMsgInTypeId =9 AND OriginDateTime BETWEEN StartTime AND EndTime AND CustomProp NOT LIKE '%Idling:0;%')      
        
		--UPDATE THE DETAILS TO MAIN TABLE      
		UPDATE @tblVehicles SET NoofTrips =(SELECT COUNT(TripId) FROM @tblTripDetails),      
		RunningTime=(SELECT SUM(RunningTime) FROM @tblTripDetails),      
		IdlingTime=(SELECT SUM(IdlingTime) FROM @tblTripDetails)            
		WHERE Boxid=@intBoxLoop        
           
		--Declare @RunTime as bigint
		--Set @RunTime = (Select CAST(IsNull(DateDiff(ss,@dtStartDate,Max(A.LastReporteDateTime)),0) AS INT) From adrControllerMaster A INNER JOIN adr_rvlfTripDetails B 
		--						ON A.EquipmentId=B.BoxId Where B.BoxID=@intBoxLoop)

		--UPDATE @tblVehicles SET NoofTrips=12,RunningTime=12,IdlingTime=@RunTime WHERE Boxid=@intBoxLoop


		SELECT @intBoxLoop = MIN(Boxid) FROM @tblVehicles WHERE Boxid >@intBoxLoop       
	END      
    
	--Fetching KPI Details
	DECLARE @intLoopi int = NULL
	SELECT	@intLoopi = MIN(BoxId) FROM @tblVehicles 
	
	DECLARE @vcDetailData VARCHAR(MAX) = ''
	DECLARE @tblDetailData TABLE(BoxId bigint primary key, VehicleDescription nvarchar(50),IdlingDuration nvarchar(10),IdlingPercentage numeric(18,2),
								 DistanceTraveled int,SpeedViolations int, ExtremeAcceleration int, ExtremeBraking int, VehicleUtilization nvarchar(10))

	WHILE @intLoopi IS NOT NULL
	BEGIN
		INSERT	INTO @tblDetailData 
		SELECT	BoxId, VehicleDescription,ISNULL(IdlingTime,0),CAST(ISNULL((IdlingTime*1.00)/CASE WHEN(ISNULL(RunningTime,0)*1.00) = 0 THEN 1 
											ELSE (ISNULL(RunningTime,0)*1.00) END *100,0) AS NUMERIC(8,2)),
											CASE WHEN ISNULL(Distance,0) = 0 THEN '-' ELSE CAST(Distance AS VARCHAR) END,
				--CASE WHEN	ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END 
				--FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)),0) = 0 THEN '-' 
				--ELSE CAST((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance 
				--ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)) AS VARCHAR) END,
				SpeedViolations, ExtremeAcceleration + HarshAcceleration, ExtremeBraking + HarshBraking, DaysUtilizaed			-- Harsh and Extreme values combined for Acceleration & Braking on 22-01-2016 by AnbarasuE
		FROM	@tblVehicles  
		WHERE	Boxid = @intLoopi
				
		SELECT	@vcDetailData = @vcDetailData + 
					(CASE @KPIID 
					WHEN 1 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(dbo.rvlf_fn_GetHHMMSSFromSec(IdlingDuration) AS VARCHAR) + ' </td><td>' + CASE WHEN (IdlingDuration/3600 < @MinRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (IdlingDuration/3600 > @MaxRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 2 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(IdlingPercentage AS VARCHAR) + ' </td><td>' + CASE	WHEN (IdlingPercentage < @MinRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (IdlingPercentage > @MaxRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (IdlingPercentage BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 3 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(DistanceTraveled AS VARCHAR) + ' </td><td>' + CASE	WHEN (DistanceTraveled < @MinRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (DistanceTraveled > @MaxRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (DistanceTraveled BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 4 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(SpeedViolations AS VARCHAR) + ' </td><td>' + CASE	WHEN (SpeedViolations < @MinRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (SpeedViolations > @MaxRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (SpeedViolations BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 5 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeAcceleration AS VARCHAR) + ' </td><td>' + CASE	WHEN (ExtremeAcceleration < @MinRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (ExtremeAcceleration > @MaxRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (ExtremeAcceleration BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 6 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeBraking AS VARCHAR) + ' </td><td>' + CASE	WHEN (ExtremeBraking < @MinRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (ExtremeBraking > @MaxRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (ExtremeBraking BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 7 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(VehicleUtilization AS VARCHAR)+ ' </td><td>'+ CASE	WHEN (VehicleUtilization < @MinRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (VehicleUtilization > @MaxRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (VehicleUtilization BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 9 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,(DistanceTraveled * @CostKPIsValue)),3) + ' </td><td>' + CASE	WHEN ((DistanceTraveled * @CostKPIsValue) < @MinRange) THEN '<img src="image

s/kpi/1_.png" title="Safe">' 
																																		WHEN ((DistanceTraveled * @CostKPIsValue) > @MaxRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN ((DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 10 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,((IdlingDuration * @CostKPIsValue)/3600)),3) + ' </td><td>' + CASE	WHEN (((IdlingDuration * @CostKPIsValue)/3600) < @MinRange) THEN '<img

 src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					ELSE '<tr><td colspan="3">No data found.</td></tr>'
					END)
		FROM	@tblDetailData  
		WHERE	BoxId = @intLoopi
		
		SELECT @intLoopi = MIN(BoxId) FROM @tblVehicles WHERE Boxid > @intLoopi
	END

	--Fetching KPI Summary
	DECLARE @totIdlingTime			INT = NULL      
	DECLARE @totIdlingPercent		NUMERIC(18,2) = NULL
	DECLARE @totDistanceTraveled	INT = NULL      
	DECLARE @totDaysUtilized		INT = NULL

	SELECT	@totIdlingTime		= SUM(CAST(IdlingDuration AS INT)),
			@totIdlingPercent	= CEILING(AVG(IdlingPercentage)),
			@totDistanceTraveled= SUM(ISNULL(DistanceTraveled,0)),
			@totDaysUtilized	= CAST(ROUND(AVG(CAST(VehicleUtilization AS NUMERIC(18,2))),0)AS INT)
	FROM	@tblDetailData

	-- Fetching KPI Chart data
	DECLARE @intSafe		VARCHAR(5) = NULL
	DECLARE @intWarning		VARCHAR(5) = NULL
	DECLARE @intCritical	VARCHAR(5) = NULL

	
	-- Template replacing with KPI values based on KPI Type
	IF (@KPIID = 1) 
	BEGIN
		--SELECT	@CurrValue = (SUM(msg.duration)), @CurrValueFormatted = (dbo.rvlf_fn_GetTimeFromSeconds(SUM(msg.duration))) --CAST(dbo.rvlf_fn_GetParamValueWithIndex(msg.CustomProp,'Idling:',';') AS bigint)))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) --AND msg.BoxMsgInTypeId = 9 --AND CHARINDEX('Idling',CustomProp,0)>0
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		SELECT	@CurrValue = @totIdlingTime/3600, @CurrValueFormatted = dbo.rvlf_fn_GetHHMMSSFromSec(@totIdlingTime)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 > @MaxRange
	END
	ELSE IF (@KPIID = 2) 
	BEGIN	
		SELECT	@CurrValue = @totIdlingPercent, @CurrValueFormatted = @totIdlingPercent
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage > @MaxRange
	END
	ELSE IF (@KPIID = 3) 
	BEGIN	
		--SELECT	@CurrValue = (MAX(msg.odometer)-MIN(msg.odometer))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) AND msg.OriginDateTime Between @dtFDate and @dtEDate
		--GROUP BY msg.BoxId
		SELECT	@CurrValue = @totDistanceTraveled, @CurrValueFormatted = @totDistanceTraveled
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled > @MaxRange
	END
	ELSE IF (@KPIID = 4) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=4 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(SpeedViolations),0), @CurrValueFormatted = ISNULL(SUM(SpeedViolations),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations > @MaxRange
	END
	ELSE IF (@KPIID = 5) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=15 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeAcceleration),0), @CurrValueFormatted = ISNULL(SUM(ExtremeAcceleration),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration > @MaxRange
	END
	ELSE IF (@KPIID = 6) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=17 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeBraking),0), @CurrValueFormatted = ISNULL(SUM(ExtremeBraking),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking > @MaxRange
	END
	ELSE IF (@KPIID = 7) 
	BEGIN
		SELECT	@CurrValue = @totDaysUtilized, @CurrValueFormatted = @totDaysUtilized
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization > @MaxRange
		--SELECT	@CurrValue = COUNT(*) FROM rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) 
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		--AND		msg.BoxMsgInTypeId = 1
		--Group By msg.BoxId
	END
	ELSE IF(@KPIID = 9)
	BEGIN 
		SELECT	@CurrValue = (@totDistanceTraveled * @CostKPIsValue), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,(@totDistanceTraveled * @CostKPIsValue)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) > @MaxRange
	END
	ELSE IF(@KPIID = 10)
	BEGIN 
		SELECT	@CurrValue = ((@totIdlingTime * @CostKPIsValue)/3600), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,((@totIdlingTime * @CostKPIsValue)/3600)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange
	END			
	ELSE 
	BEGIN
		SELECT @CurrValueFormatted = '15' 
	END
	
	SELECT	@UnitName = CurrencyName FROM rvlfCurrencyType CT
	INNER	JOIN rvlfOrganization O ON CT.CurrencyTypeId = O.CurrencyTypeId
	WHERE	OrganizationId = @bigOrganizationID	and @KPIID in (9,10)

	-- Add the T-SQL statements to compute the return value here
	SET	@Template	= REPLACE(@Template ,'$ChartScript$', 'google.setOnLoadCallback(drawChart_$Sno$);function drawChart_$Sno$() {
										var data = new google.visualization.arrayToDataTable([[''Bands'', ''No.of.Vehicles'', { role: ''style'' }],[''Safe'', '+ 
										ISNULL(@intSafe,0) +', ''#04B713''],[''Warning'', '+ ISNULL(@intWarning,0) +', ''#FF7F00''],[''Critical'', '+ ISNULL(@intCritical,0) +', ''#FE0000''],]);
										var options = {width: 500,height: 400,colors: [''Red''],chartArea: { width: ''50%'' },hAxis: {title: ''KPI Status'',minValue: 0},
										vAxis: {title: ''No.of.Vehicles'',maxValue: 16,format: ''0'',gridlines: { count: 6 },minorGridlines: { count: 3 }},legend: { position: ''none'' }};
										var chart = new google.visualization.ColumnChart(document.getElementById(''chart_div_$Sno$''));chart.draw(data, options);}')
	SET	@Template	= REPLACE(@Template ,'$Sno$', @Sno)
	SET	@Template	= REPLACE(@Template ,'$gridData$', '<thead><th>Vehicle</th><th>$KPICaption$</th><th>Status</th></thead><tbody>'+ @vcDetailData +'</tbody>')
	SET	@Template	= REPLACE(@Template ,'$AssignmentID$', @AssignmentID)
	SET	@Template	= REPLACE(@Template ,'$KPIUnitName$', @UnitName)

	DECLARE @KPIStatus nvarchar(10)
	SET @KPIStatus = CASE WHEN (@CurrValue < @MinRange) THEN 'safe' WHEN (@CurrValue > @MaxRange) THEN 'critical' WHEN (@CurrValue between @MinRange and @MaxRange) THEN 'warning' ELSE 'safe' END
	
	SET	@Template	= REPLACE(@Template ,'$TileImgName$', 'img-' + @KPIStatus + '-kpi')
	SET	@Template	= REPLACE(@Template ,'$KPIValue$', @CurrValueFormatted)
	--SET	@Template	= REPLACE(@Template ,'$PnlTableClass2$', @KPIStatus)
	SET	@Template	= REPLACE(@Template ,'$PnlTableClass1$', CASE @DisplayTypeID WHEN 1  THEN 'tiletable' WHEN 2 THEN 'gaugetable' WHEN 3 THEN 'progresstable' WHEN 4 THEN 'tiletable' WHEN 5 THEN 'gridtable' END)
	SET	@Template	= REPLACE(@Template ,'$PanelClass$', CASE @DisplayTypeID WHEN 1 THEN 'tilediv' WHEN 2 THEN 'gaugediv' WHEN 3 THEN 'progressdiv' WHEN 4 THEN 'chartsdiv' WHEN 5 THEN 'griddiv' END)
	
	DECLARE @CustomTitleLen int 
	SET @CustomTitleLen = CASE @DisplayTypeID WHEN 1 THEN 25 ELSE 55 END 
	SET	@Template	= REPLACE(@Template ,'$CustomTitle$', CASE WHEN LEN(@CustomTitle) > @CustomTitleLen THEN SUBSTRING(@CustomTitle, 0, @CustomTitleLen) + '...' ELSE @CustomTitle END)
	SET	@Template	= REPLACE(@Template ,'$Tooltip$', @CustomTitle)
	SET	@Template	= REPLACE(@Template ,'$dataSize-y$', CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 3 THEN 2 WHEN 4 THEN 3 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataSize-x$', CASE @DisplayTypeID WHEN 1 THEN 2 WHEN 2 THEN 2 WHEN 3 THEN 2 WHEN 4 THEN 4 WHEN 5 THEN 4 END)
	SET	@Template	= REPLACE(@Template ,'$dataRows$', CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 3 THEN 3 WHEN 4 THEN 4 WHEN 5 THEN 5 END)  --CASE @Sno WHEN 1 THEN 1 WHEN 1 THEN 1 WHEN 3 THEN 1 WHEN 4 THEN 1 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataCols$', CASE WHEN @Sno < 5 THEN @Sno ELSE 4 END)
	SET	@Template	= REPLACE(@Template ,'$KPICaption$', /*LOWER(@KPIName) + */ 'Value(' + @UnitName + ')')
	SET @Template	= REPLACE(@Template, '$TitleColor$', 'style="background-color: ' + CASE WHEN @TitleClrCode IS NOT NULL THEN '#457DC7' ELSE @TitleClrCode END + '"')

	DECLARE @FleetName nvarchar(250)
	SET @FleetName	= (SELECT FleetName FROM rvlfFleet WHERE FleetId = @FleetId)
	SET	@Template	= REPLACE(@Template ,'$Fleet$', @FleetName)

	--DECLARE @Vehicles Table(VehicleId bigint, VehicleDescription nvarchar(50))
	--INSERT INTO @Vehicles 
	--SELECT v.VehicleId,v.VehicleDescription FROM rvlfVehicle v 
	--INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId 
	--WHERE va.BoxId IN (SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI]	(@BoxId,','))

	--DECLARE @minVehicleId bigint
	--SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles
	--DECLARE @VehicleName nvarchar(1000)

	--WHILE @minVehicleId IS NOT NULL
	--BEGIN
	--	IF @VehicleName IS NOT NULL
	--	BEGIN
	--		SET @VehicleName = @VehicleName + ',' + (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	ELSE
	--	BEGIN
	--		SET @VehicleName = (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles WHERE VehicleId > @minVehicleId
	--END

	SET	@Template	= REPLACE(@Template ,'$Vehicles$',	CASE @BoxId	WHEN '0' THEN 'All' 
														ELSE STUFF((SELECT ', ' + VehicleDescription FROM @BoxIds FOR XML PATH('')), 1, 1, '') END)
	SET	@Template	= REPLACE(@Template ,'$RefreshFreq$', CAST(@RefFreq AS VARCHAR(5)) + ' Sec')
	SET	@Template	= REPLACE(@Template ,'$Duration$', 'Last ' + CASE	WHEN @Duration = 168	THEN ' 1 Week'
																		WHEN @Duration Between 48 and 168	THEN CAST(@Duration/24 AS Varchar(20)) + ' Days' 
																		ELSE CAST(@Duration AS Varchar(20)) + ' Hours' END)
	
	SET	@Template	= REPLACE(@Template ,'$Range$', ((CASE	WHEN @KPIID IN (9,10) THEN (CONVERT(VARCHAR,CONVERT(MONEY,@MinRange),3) + ' to ' + CONVERT(VARCHAR,CONVERT(MONEY,@MaxRange),3))
															ELSE (CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20))) END)  
															+ ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END))

	SET @Template	= @Template 
		
	-- Return the result of the function	
	SET	@ChangedTemplate = @Template + 'Safe#' + @intSafe + ';Warning#' +  @intWarning +';Critical#' + @intCritical + ';'
	RETURN @ChangedTemplate
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplate_Responsive]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasue
-- Create date: 27-11-2015
-- Description:	To Fetch the KPI in HTML <li> format to display in the KPI Dashboard
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplate_Responsive]
(
	-- Add the parameters for the function here
	@Sno				int,
	@Template			nvarchar(MAX),
	@TitleClrCode		nvarchar(10),
	@AssignmentID		int,
	@CustomTitle		nvarchar(75),
	@KPIID				int,
	@KPIName			nvarchar(75),
	@DisplayTypeID		tinyint,
	@CostKPIsValue		decimal(18,2),
	@TemperatureType	tinyint,
	@UnitName			nvarchar(10),
	@MinRange			int,
	@MaxRange			int,
	@FleetId			int,
	@BoxId				nvarchar(1000),
	@RefFreq			int,
	@Duration			int,
	@bigUserId			bigint,
	@bigOrganizationID	bigint
	--@x					int,
	--@y					int
)				
RETURNS		nvarchar(MAX)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @BoxIds					TABLE (BOXID nvarchar(50),VehicleId INT,VehicleDescription nVarchar(150))
	DECLARE @ChangedTemplate		nvarchar(MAX)
	DECLARE @CurrValue				int
	DECLARE @CurrValueFormatted		nvarchar(50)
	DECLARE @intBoxID				int
	DECLARE @dtStartDate			datetime = NULL  
 	DECLARE @dtEndDate				datetime = NULL

	SET @dtStartDate = DATEADD(Hour,-@Duration,GETUTCDATE())
	SET @dtEndDate = GETUTCDATE()
	
	INSERT	INTO @BoxIds (BOXID,VehicleId,VehicleDescription)
	SELECT	va.BoxID,v.VehicleId,v.VehicleDescription FROM rvlfVehicleAssignment va
	INNER	JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
	INNER	JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
	WHERE	fv.FleetId = @FleetId AND (@BoxId IS NULL OR @BoxId = '0' OR @BoxId = '' or
    BoxId	in (select * from rvlf_fn_ConvertArrayToTable(@BoxId,','))) AND V.OrganizationId = @bigOrganizationID
    ORDER	BY BoxId
	
	--SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@BoxId,',')
		 
	DECLARE @Lang varchar(50)       
	SELECT @Lang=isnull(Lang,'LanguageEn') FROM rvlfUserPreferences WHERE UserId = @bigUserId

    DECLARE @DefaultDateFormat INT = 0     
	SELECT  @DefaultDateFormat=(CASE WHEN  isnull(up.DefaultDateFormat,0)= 0 THEN 106 ELSE up.DefaultDateFormat END)      
	FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId      
            
	IF @FleetId IS NULL      
	BEGIN      
		SELECT @FleetId=FleetID FROM rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1      
	END      
	DECLARE @HoursToBeAdded INT = 0      
	DECLARE @MinsToBeAdded INT = 0      
	DECLARE @ConversionFactor NUMERIC (10,2) = 1.0      
	DECLARE @DistanceCaptionPrefix VARCHAR(15)      
	DECLARE @SpeedCaptionPrefix VARCHAR(15)      
	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
			@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,        
			@DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Kms)' END,      
			@SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END      
	FROM	rvlfUserPreferences up 
	INNER	JOIN rvlfTimeZones tz ON	up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId          
          
	--SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))      
	--SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                 
    
	DECLARE @dtFDate DATETIME = @dtStartDate    
	DECLARE @dtEDate DATETIME = @dtEndDate
	  
	DECLARE @tblVehicles TABLE      
	(
	    Id bigint identity(1,1) NOT NULL,
		VehicleId bigint,
		VehicleDescription nvarchar(50),
		LicensePlate varchar(50),
		Vin varchar(50),
		Boxid varchar(50),
		NoofTrips int,
		Distance int,
		RunningTime INT,
		IdlingTime BIGINT,
		DaysUtilizaed varchar(30),
		FleetName varchar(50),
		SpeedViolations		int,
		HarshAcceleration	int,
		ExtremeAcceleration	int,
		HarshBraking		int,
		ExtremeBraking		int,
		Temperature			int
	)
      
	DECLARE @tblMessageForProcessingTrip TABLE (      
		[ProcessorID] [bigint] identity(1,1) NOT NULL,
		[Boxid] [varchar](50) NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[IgnitionStatus] [bit] NULL,
		[CustomProp] [varchar](600) NULL,
		[TripId] [bigint] NULL
	)      

	INSERT	INTO @tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin,FleetName)      
	SELECT	VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin,f.FleetName  
	FROM	rvlfBoxId BI
	INNER	JOIN rvlfVehicleAssignment VA ON BI.BoxId=VA.BoxId       
	INNER	JOIN rvlfFleetVehicles FV ON FV.VehicleId =VA.VehicleId       
	INNER	JOIN rvlfFleet F ON FV.FleetId=F.FleetId       
	INNER	JOIN rvlfVehicle V ON FV.VehicleId=V.VehicleId       
	INNER	JOIN rvlfOrganization O ON O.OrganizationId =F.OrganizationId       
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR V.OrganizationId = @bigOrganizationID AND F.OrganizationId = @bigOrganizationID)
	AND		(@FleetId IS NULL OR @FleetId = '' OR F.FleetId = @FleetId)
	AND		VA.BoxId IN (SELECT BOXID FROM @BoxIds)
	ORDER	BY BI.BOXID

	--GET THE TRIPS      
	DECLARE @tblTrips TABLE
	(
		ProcessId bigint identity(1,1),
		Boxid varchar(50) null,
		TripTime datetime null,
		TripStatus varchar(10) null
	)
       
	--GET THE TRIP DETAILS      
	DECLARE @tblTripDetails TABLE      
	(        
		TripId bigint identity(1,1),      
		Boxid varchar(50) null,        
		StartTime datetime null,      
		EndTime datetime null,      
		TripInStatus varchar(5) null,      
		TripOutStatus varchar(5) null,      
		RunningTime int null,      
		IdlingTime int null       
	)

	--GET TEMPERATURE PACKETS
	--DECLARE @tblTemperatureDetails TABLE      
	--(        
	--	MessageInId uniqueidentifier,
	--	BoxId bigint,
	--	BoxMsgInTypeId int,
	--	CustomProp varchar(600),
	--	TemperatureValue numeric(18,2)
	--)
      
	DECLARE @intBoxLoop varchar(50) =(SELECT MIN(Id) FROM @tblVehicles)      
      
	WHILE @intBoxLoop IS NOT NULL      
	BEGIN       
		DELETE FROM @tblMessageForProcessingTrip        
		INSERT INTO @tblMessageForProcessingTrip(Boxid,OriginDateTime,BoxMsgInTypeId,IgnitionStatus,CustomProp)      
		SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,      
		CAST(SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,h.CustomProp             
		FROM rvlfMsgInHst h       
		INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                    
		WHERE m.OperationTypeID IN (SELECT p.OperationID  FROM rvlfPackageOperations p WHERE p.PackageId =       
		(SELECT op.PackageId FROM rvlfOrganizationPackage op WHERE op.OrganizationID = @bigOrganizationID      
		AND op.IsActive=1)      
		AND p.ModuleID = 26) and m.OperationTypeID IS NOT NULL                      
		AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
		AND h.BoxID = @intBoxLoop      
		ORDER BY h.origindatetime ASC        
          
		--CALCULATE THE DISTANCE
		
		--Kalai Added
		--UPDATE	@tblVehicles SET
		--	Distance = (Select Sum(ISNULL(DateDiff(Hour,StartDate,EndDate),0)) From [dbo].[adr_rvlfTripDetails] Where BoxId=@intBoxLoop)
		--WHERE	Boxid = @intBoxLoop AND Distance IS NULL

		UPDATE	@tblVehicles 
		SET		
				Distance = (Select Sum(ISNULL(DateDiff(Hour,StartDate,EndDate),0)) From [dbo].[adr_rvlfTripDetails] Where BoxId=@intBoxLoop),
				--Distance =  (SELECT CEILING((MAX(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,1))) -      
				--			(CHARINDEX('Odometer=',CustomProp,1)+9)),0) AS BIGINT)) - MIN(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,      
				--			CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9)),0)AS BIGINT))) * @ConversionFactor)  AS DISTANCE
				--			FROM	@tblMessageForProcessingTrip M
				--			WHERE   (M.BoxId= @intBoxLoop) AND (M.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND CustomProp LIKE '%Odometer%' AND BoxMsgInTypeId in(2,3)),
				SpeedViolations = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 4) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 14) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 15) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				--ExtremeAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 15) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 16) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 17) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				Temperature = (SELECT COUNT(BoxMsgInTypeId) from @tblMessageForProcessingTrip where BoxId = @intBoxLoop and BoxMsgInTypeId = (CASE @TemperatureType WHEN 1 THEN 82 WHEN 2 THEN 86 WHEN 3 THEN 166 WHEN 4 THEN 171 ELSE 0 END))
		WHERE	Boxid = @intBoxLoop AND Distance IS NULL
        
		--CALCULATE THE UTILIZED DAYS
		UPDATE @tblVehicles SET DaysUtilizaed =(SELECT CASE WHEN COUNT(Actions)>CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) THEN CAST(COUNT(Actions)-1 as varchar) ELSE CAST(COUNT(Actions) as varchar) END  
												--+ ' out of '+CAST( CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) AS VARCHAR) 
												FROM (SELECT COUNT(BoxId) AS Actions       
		FROM @tblMessageForProcessingTrip        
		WHERE BoxId=@intBoxLoop AND    
		(OriginDateTime BETWEEN  dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtStartDate) AND dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtEndDate))    
		--(OriginDateTime BETWEEN DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtStartDate)) AND DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEndDate)))    
		AND BoxMsgInTypeId IN (2,3)      
		GROUP BY CONVERT(DATE,OriginDateTime))AS A)      
		WHERE Boxid =@intBoxLoop AND DaysUtilizaed IS NULL      
        
		--CALCULATE THE NOOFTRIPS,RUNNING TIME AND IDLING TIME
		DELETE FROM @tblTrips       
		DELETE FROM @tblTripDetails       
		INSERT INTO @tblTrips (Boxid,TripTime,TripStatus)      
		SELECT BoxId,OriginDateTime,CASE WHEN BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'START'       
		WHEN BoxMsgInTypeId =3 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'STOP' ELSE NULL END          
		FROM rvlfMsgInHst       
		WHERE Boxid =@intBoxLoop      
		AND BoxMsgInTypeId IN(2,3)                
		AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate        
		ORDER BY BoxId,OriginDateTime       
          
		INSERT INTO @tblTripDetails (Boxid,EndTime,TripOutStatus,StartTime,TripInStatus)      
		SELECT MT.Boxid,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus      
		FROM @tblTrips AS MT       
		LEFT OUTER JOIN @tblTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'START'       
         
		--DELETE THE INVALID TRIPS      
		DELETE FROM @tblTripDetails WHERE StartTime IS NULL OR TripInStatus=TripOutStatus        
         
		--CALCULATE THE RUNNING TIME AND IDLING TIME       
		--Added By Kalai
		--UPDATE @tblTripDetails 
		--	SET RunningTime =(Select IsNull(DateDiff(s,Max(B.StartDate),Max(A.LastReporteDateTime)),0) From adrControllerMaster A INNER JOIN adr_rvlfTripDetails B 
		--						ON A.EquipmentId=B.BoxId Where B.BoxID=@intBoxLoop),
		--		IdlingTime=(Select IsNull(DateDiff(s,Max(B.StartDate),Max(A.LastReporteDateTime)),0) From adrControllerMaster A INNER JOIN adr_rvlfTripDetails B 
		--						ON A.EquipmentId=B.BoxId Where B.BoxID=@intBoxLoop)

		--UPDATE @tblTripDetails SET RunningTime =DATEDIFF(S,StartTime,EndTime),      
		--IdlingTime=(SELECT SUM(ISNULL(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,      
		--(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT),0))                   
		--FROM @tblMessageForProcessingTrip  WHERE Boxid=@intBoxLoop AND BoxMsgInTypeId =9 AND OriginDateTime BETWEEN StartTime AND EndTime AND CustomProp NOT LIKE '%Idling:0;%')      

        --TEMPERATURE VALUES 
		--INSERT INTO @tblTemperatureDetails(MessageInID,BoxId,BoxMsgInTypeId,CustomProp,TemperatureValue)
		--SELECT MessageInID,BoxId,BoxMsgInTypeId,CustomProp,CAST(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Temperature Sensor-' + @TemperatureType + ' Value=','degree Celsius;') AS numeric(18,2))
		--FROM rvlfMsgInHst WHERE (BoxId = @intBoxLoop and BoxMsgInTypeId NOT IN (4,18,51,78,89,90)) AND (OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)

		--Commented by Kalai
		--UPDATE @tblVehicles SET 
		--NoofTrips   = (SELECT COUNT(TripId) FROM @tblTripDetails),
		--RunningTime = (SELECT SUM(RunningTime)+12 FROM @tblTripDetails),
		--IdlingTime  = (SELECT SUM(IdlingTime)+100 FROM @tblTripDetails)
		--WHERE Boxid = @intBoxLoop

		Declare @RunTime as bigint
		--Set @RunTime = (Select CAST(IsNull(DateDiff(ss,Max(B.StartDate),Max(A.LastReporteDateTime)),0) AS INT) From adrControllerMaster A INNER JOIN adr_rvlfTripDetails B 
		--						ON A.EquipmentId=B.BoxId Where B.BoxID=@intBoxLoop)  @dtStartDate,@dtEndDate

		Set @RunTime = (Select CAST(IsNull(DateDiff(ss,@dtStartDate,Max(A.LastReporteDateTime)),0) AS INT) From adrControllerMaster A INNER JOIN adr_rvlfTripDetails B 
								ON A.EquipmentId=B.BoxId Where B.BoxID=@intBoxLoop)

		UPDATE @tblVehicles SET NoofTrips=12,RunningTime=12,IdlingTime=@RunTime WHERE Boxid=@intBoxLoop

		SELECT @intBoxLoop = MIN(BoxId) FROM @tblVehicles WHERE Boxid > @intBoxLoop       
	END
    
	--FETCHING KPI DETAILS
	DECLARE @intLoopi int = NULL
	SELECT	@intLoopi = MIN(BoxId) FROM @tblVehicles 
	
	DECLARE @vcDetailData VARCHAR(MAX) = ''
	DECLARE @tblDetailData TABLE(BoxId bigint primary key, VehicleDescription nvarchar(50),IdlingDuration nvarchar(10),IdlingPercentage numeric(18,2),
								 DistanceTraveled int,SpeedViolations int, ExtremeAcceleration int, ExtremeBraking int, VehicleUtilization nvarchar(10), TemperatureHigh int)

	WHILE @intLoopi IS NOT NULL
	BEGIN
		INSERT	INTO @tblDetailData 
		SELECT	BoxId, VehicleDescription,ISNULL(IdlingTime,0),
				CAST(ISNULL((IdlingTime*1.00)/CASE WHEN(ISNULL(RunningTime,0)*1.00) = 0 THEN 1 ELSE (ISNULL(RunningTime,0)*1.00) END *100,0) AS NUMERIC(18,2)),
				CASE WHEN ISNULL(Distance,0) = 0 THEN '-' ELSE CAST(Distance AS VARCHAR) END,
				--CASE WHEN	ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END 
				--FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)),0) = 0 THEN '-' 
				--ELSE CAST((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance 
				--ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)) AS VARCHAR) END,
				SpeedViolations,ExtremeAcceleration + HarshAcceleration, ExtremeBraking + HarshBraking, DaysUtilizaed, Temperature			-- Harsh and Extreme values combined for Acceleration & Braking on 22-01-2016 by AnbarasuE
		FROM @tblVehicles  
		WHERE	Boxid = @intLoopi

		SELECT	@vcDetailData = @vcDetailData + 
					(CASE @KPIID 
					WHEN 1 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+
									 CAST(dbo.rvlf_fn_GetHHMMSSFromSec(IdlingDuration) AS VARCHAR) + ' </td><td>' + CASE WHEN (IdlingDuration/3600 < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
													WHEN (IdlingDuration/3600 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
					WHEN 2 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(IdlingPercentage AS VARCHAR) + ' </td><td>' + 
									CASE WHEN (IdlingPercentage < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
													WHEN (IdlingPercentage > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (IdlingPercentage BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
					WHEN 3 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(DistanceTraveled AS VARCHAR) + ' </td><td>' + 
									CASE WHEN (DistanceTraveled < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
													WHEN (DistanceTraveled > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (DistanceTraveled BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
					WHEN 4 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(SpeedViolations AS VARCHAR) + ' </td><td>' + 
									CASE WHEN (SpeedViolations < @MinRange) THEN '<img src="../images/1_.png" title="Safe">'
													WHEN (SpeedViolations > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (SpeedViolations BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">'
														END	+ '</td></tr>'
					WHEN 5 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeAcceleration AS VARCHAR) + ' </td><td>' + 
									CASE WHEN (ExtremeAcceleration < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
													WHEN (ExtremeAcceleration > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (ExtremeAcceleration BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
					WHEN 6 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeBraking AS VARCHAR) + ' </td><td>' + 
									CASE WHEN (ExtremeBraking < @MinRange) THEN '<img src="../images/1_.png" title="Safe">'
													WHEN (ExtremeBraking > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (ExtremeBraking BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
					WHEN 7 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(VehicleUtilization AS VARCHAR)+ ' </td><td>'+ 
									CASE WHEN (VehicleUtilization < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
													WHEN (VehicleUtilization > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (VehicleUtilization BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
					WHEN 9 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,(DistanceTraveled * @CostKPIsValue)),3) + ' </td><td>' + 
									CASE WHEN ((DistanceTraveled * @CostKPIsValue) < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
													WHEN ((DistanceTraveled * @CostKPIsValue) > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN ((DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
					WHEN 10 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,((IdlingDuration * @CostKPIsValue)/3600)),3) + ' </td><td>' + 
									CASE WHEN (((IdlingDuration * @CostKPIsValue)/3600) < @MinRange) THEN '<img src="../images/1_.png" title="Safe">' 
													WHEN (((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
					WHEN 11 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(TemperatureHigh AS VARCHAR)+ ' </td><td>'+
									CASE	WHEN (TemperatureHigh < @MinRange) THEN '<img src="../images/1_.png" title="Safe">'
													WHEN (TemperatureHigh > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (TemperatureHigh BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">'
														END	+ '</td></tr>'
						ELSE '<tr><td colspan="3">No data found.</td></tr>'
					END)
		FROM	@tblDetailData  
		WHERE	BoxId = @intLoopi
		
		SELECT @intLoopi = MIN(BoxId) FROM @tblVehicles WHERE Boxid > @intLoopi
	END

	--FETCHING KPI SUMMARY
	DECLARE @totIdlingTime			INT = NULL      
	DECLARE @totIdlingPercent		NUMERIC(18,2) = NULL
	DECLARE @totDistanceTraveled	INT = NULL      
	DECLARE @totDaysUtilized		INT = NULL
	DECLARE @totTemperatureHigh		INT = NULL

	SELECT	@totIdlingTime		= SUM(CAST(IdlingDuration AS INT)),
			@totIdlingPercent	= CEILING(AVG(IdlingPercentage)),
			@totDistanceTraveled= SUM(ISNULL(DistanceTraveled,0)),
			@totDaysUtilized	= CAST(ROUND(AVG(CAST(VehicleUtilization AS NUMERIC(18,2))),0)AS INT),
			@totTemperatureHigh = SUM(CAST(TemperatureHigh AS INT))
	FROM	@tblDetailData

	-- FETCHING KPI CHART DATA
	DECLARE @intSafe		VARCHAR(5) = NULL
	DECLARE @intWarning		VARCHAR(5) = NULL
	DECLARE @intCritical	VARCHAR(5) = NULL

	
	-- TEMPLATE REPLACING WITH KPI VALUES BASED ON KPI TYPE
	IF (@KPIID = 1) 
	BEGIN
		--SELECT	@CurrValue = (SUM(msg.duration)), @CurrValueFormatted = (dbo.rvlf_fn_GetTimeFromSeconds(SUM(msg.duration))) --CAST(dbo.rvlf_fn_GetParamValueWithIndex(msg.CustomProp,'Idling:',';') AS bigint)))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) --AND msg.BoxMsgInTypeId = 9 --AND CHARINDEX('Idling',CustomProp,0)>0
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		SELECT	@CurrValue = @totIdlingTime/3600, @CurrValueFormatted = dbo.rvlf_fn_GetHHMMSSFromSec(@totIdlingTime)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 > @MaxRange
	END
	ELSE IF (@KPIID = 2) 
	BEGIN	
		SELECT	@CurrValue = @totIdlingPercent, @CurrValueFormatted = @totIdlingPercent
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage > @MaxRange
	END
	ELSE IF (@KPIID = 3) 
	BEGIN	
		--SELECT	@CurrValue = (MAX(msg.odometer)-MIN(msg.odometer))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) AND msg.OriginDateTime Between @dtFDate and @dtEDate
		--GROUP BY msg.BoxId
		SELECT	@CurrValue = @totDistanceTraveled, @CurrValueFormatted = @totDistanceTraveled
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled > @MaxRange
	END
	ELSE IF (@KPIID = 4) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=4 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(SpeedViolations),0), @CurrValueFormatted = ISNULL(SUM(SpeedViolations),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations > @MaxRange
	END
	ELSE IF (@KPIID = 5) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=15 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeAcceleration),0), @CurrValueFormatted = ISNULL(SUM(ExtremeAcceleration),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration > @MaxRange
	END
	ELSE IF (@KPIID = 6) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=17 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeBraking),0), @CurrValueFormatted = ISNULL(SUM(ExtremeBraking),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking > @MaxRange
	END
	ELSE IF (@KPIID = 7) 
	BEGIN
		SELECT	@CurrValue = @totDaysUtilized, @CurrValueFormatted = @totDaysUtilized
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization > @MaxRange
		--SELECT	@CurrValue = COUNT(*) FROM rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) 
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		--AND		msg.BoxMsgInTypeId = 1
		--Group By msg.BoxId
	END
	ELSE IF(@KPIID = 9)
	BEGIN 
		SELECT	@CurrValue = (@totDistanceTraveled * @CostKPIsValue), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,(@totDistanceTraveled * @CostKPIsValue)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) > @MaxRange
	END
	ELSE IF(@KPIID = 10)
	BEGIN 
		SELECT	@CurrValue = ((@totIdlingTime * @CostKPIsValue)/3600), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,((@totIdlingTime * @CostKPIsValue)/3600)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange
	END
	ELSE IF(@KPIID = 11)
	BEGIN 
		SELECT	@CurrValue = @totTemperatureHigh, @CurrValueFormatted = @totTemperatureHigh
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh > @MaxRange
	END
	ELSE 
	BEGIN
		SELECT @CurrValueFormatted = '15' 
	END
	
	SELECT	@UnitName = CurrencyName FROM rvlfCurrencyType CT
	INNER	JOIN rvlfOrganization O ON CT.CurrencyTypeId = O.CurrencyTypeId
	WHERE	OrganizationId = @bigOrganizationID	and @KPIID in (9,10)

	-- Add the T-SQL statements to compute the return value here
	SET	@Template	= REPLACE(@Template ,'$ChartScript$', 'google.setOnLoadCallback(drawChart_$Sno$);function drawChart_$Sno$() {
										var data = new google.visualization.arrayToDataTable([[''Bands'', ''No.of.Vehicles'', { role: ''style'' }],[''Safe'', '+ ISNULL(@intSafe,0) +', ''#04B713''],[''Warning'', '+ ISNULL(@intWarning,0) +', ''#FF7F00''],[''Critical'', '+ 
										ISNULL(@intCritical,0) +', ''#FE0000''],]);
										var options = {width: 330,height: 400,colors: [''Red''],chartArea: { width: ''50%'' },hAxis: {title: ''KPI Status'',minValue: 0},vAxis: {title: ''No.of.Vehicles'',maxValue: 16,format: ''0'',gridlines: { count: 6 },minorGridlines: { count: 3 }},




 
legend: { position: "none" }};
										var chart = new google.visualization.ColumnChart(document.getElementById(''chart_div_$Sno$''));chart.draw(data, options);}')
	SET	@Template	= REPLACE(@Template ,'$Sno$', @Sno)
	SET	@Template	= REPLACE(@Template ,'$data-gs-id$', @AssignmentID)
	SET	@Template	= REPLACE(@Template ,'$gridData$', '<thead><th>ESP</th><th>$KPICaption$</th><th>Status</th></thead><tbody>'+ @vcDetailData +'</tbody>')
	SET	@Template	= REPLACE(@Template ,'$AssignmentID$', @AssignmentID)
	SET	@Template	= REPLACE(@Template ,'$KPIUnitName$', @UnitName)

	DECLARE @KPIStatus nvarchar(10)
	SET @KPIStatus = CASE WHEN (@CurrValue < @MinRange) THEN 'safe' WHEN (@CurrValue > @MaxRange) THEN 'critical' WHEN (@CurrValue between @MinRange and @MaxRange) THEN 'warning' ELSE 'safe' END
	
	SET	@Template	= REPLACE(@Template ,'$TileImgName$', 'img-' + @KPIStatus + '-kpi')
	SET	@Template	= REPLACE(@Template ,'$KPIValue$', @CurrValueFormatted)
	--SET	@Template	= REPLACE(@Template ,'$PnlTableClass2$', @KPIStatus)
	SET	@Template	= REPLACE(@Template ,'$PnlTableClass1$', CASE @DisplayTypeID WHEN 1  THEN 'tiletable' WHEN 2 THEN 'gaugetable' WHEN 3 THEN 'progresstable' WHEN 4 THEN 'tiletable' WHEN 5 THEN 'gridtable' END)
	SET	@Template	= REPLACE(@Template ,'$PanelClass$', CASE @DisplayTypeID WHEN 1 THEN 'tilediv' WHEN 2 THEN 'gaugediv' WHEN 3 THEN 'progressdiv' WHEN 4 THEN 'chartsdiv' WHEN 5 THEN 'griddiv' END)
	
	DECLARE @CustomTitleLen int 
	SET @CustomTitleLen = CASE @DisplayTypeID WHEN 1 THEN 25 ELSE 55 END 
	SET	@Template	= REPLACE(@Template ,'$CustomTitle$', CASE WHEN LEN(@CustomTitle) > @CustomTitleLen THEN SUBSTRING(@CustomTitle, 0, @CustomTitleLen) + '...' ELSE @CustomTitle END)
	SET	@Template	= REPLACE(@Template ,'$Tooltip$', @CustomTitle)
		
	DECLARE @PosX TINYINT, @PosY TINYINT
	SELECT @PosX = x, @PosY = y FROM rvlfKPIGridPosition POS
	RIGHT JOIN RVLFKPIUSERASSIGNMENT KUA ON POS.AssignmentId = KUA.ASSIGNMENTID
	WHERE KUA.AssignmentId = @AssignmentID

	SET	@Template	= REPLACE(@Template ,'$dataRows$', CASE WHEN @PosX IS NULL THEN 0 ELSE @PosX END)	
	--CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 3 THEN 3 WHEN 4 THEN 4 WHEN 5 THEN 5 END)  --CASE @Sno WHEN 1 THEN 1 WHEN 1 THEN 1 WHEN 3 THEN 1 WHEN 4 THEN 1 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataCols$', CASE WHEN @PosY IS NULL THEN 0 ELSE @PosY END)	--CASE WHEN @Sno < 5 THEN @Sno ELSE 4 END)

	SET	@Template	= REPLACE(@Template ,'$dataSize-y$', CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 1 WHEN 3 THEN 1 WHEN 4 THEN 3 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataSize-x$', CASE @DisplayTypeID WHEN 1 THEN 3 WHEN 2 THEN 3 WHEN 3 THEN 3 WHEN 4 THEN 4 WHEN 5 THEN 4 END)
	SET	@Template	= REPLACE(@Template ,'$KPICaption$', /*LOWER(@KPIName) + */ 'Value(' + @UnitName + ')')
	SET @Template	= REPLACE(@Template, '$TitleColor$', 'style="background-color: ' + CASE WHEN @TitleClrCode IS NOT NULL THEN '#457DC7' ELSE @TitleClrCode END + '"')

	DECLARE @FleetName nvarchar(250)
	SET @FleetName	= (SELECT FleetName FROM rvlfFleet WHERE FleetId = @FleetId)
	SET	@Template	= REPLACE(@Template ,'$Fleet$', @FleetName)

	--DECLARE @Vehicles Table(VehicleId bigint, VehicleDescription nvarchar(50))
	--INSERT INTO @Vehicles 
	--SELECT v.VehicleId,v.VehicleDescription FROM rvlfVehicle v 
	--INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId 
	--WHERE va.BoxId IN (SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI]	(@BoxId,','))

	--DECLARE @minVehicleId bigint
	--SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles
	--DECLARE @VehicleName nvarchar(1000)

	--WHILE @minVehicleId IS NOT NULL
	--BEGIN
	--	IF @VehicleName IS NOT NULL
	--	BEGIN
	--		SET @VehicleName = @VehicleName + ',' + (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	ELSE
	--	BEGIN
	--		SET @VehicleName = (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles WHERE VehicleId > @minVehicleId
	--END

	SET	@Template	= REPLACE(@Template ,'$Vehicles$',	CASE @BoxId	WHEN '0' THEN 'All' 
														ELSE STUFF((SELECT ', ' + VehicleDescription FROM @BoxIds FOR XML PATH('')), 1, 1, '') END)
	SET	@Template	= REPLACE(@Template ,'$RefreshFreq$', CAST(@RefFreq AS VARCHAR(5)) + ' Sec')
	SET	@Template	= REPLACE(@Template ,'$Duration$', 'Last ' + CASE	WHEN @Duration = 336	THEN ' 2 Weeks'
																		WHEN @Duration Between 168	and 336 THEN ' 1 Week'
																		WHEN @Duration Between 48	and 168	THEN CAST(@Duration/24 AS Varchar(20)) + ' Days' 
																		ELSE CAST(@Duration AS Varchar(20)) + ' Hours' END)
	
	SET	@Template	= REPLACE(@Template ,'$Range$', ((CASE	WHEN @KPIID IN (9,10) THEN (CONVERT(VARCHAR,CONVERT(MONEY,@MinRange),3) + ' to ' + CONVERT(VARCHAR,CONVERT(MONEY,@MaxRange),3))
															ELSE (CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20))) END)  
															+ ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END))

	SET @Template	= @Template + '<input type="hidden" value="KPIStatus:' + @KPIStatus + '">'
		
	-- Return the result of the function	
	SET	@ChangedTemplate = @Template
	RETURN @ChangedTemplate
END
GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplate_Responsive_Test]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasue
-- Create date: 27-11-2015
-- Description:	To Fetch the KPI in HTML <li> format to display in the KPI Dashboard
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplate_Responsive_Test]
(
	-- Add the parameters for the function here
	@Sno				int,
	@Template			nvarchar(MAX),
	@TitleClrCode		nvarchar(10),
	@AssignmentID		int,
	@CustomTitle		nvarchar(75),
	@KPIID				int,
	@KPIName			nvarchar(75),
	@DisplayTypeID		tinyint,
	@CostKPIsValue		decimal(18,2),
	@TemperatureType	tinyint,
	@UnitName			nvarchar(10),
	@MinRange			int,
	@MaxRange			int,
	@FleetId			int,
	@BoxId				nvarchar(1000),
	@RefFreq			int,
	@Duration			int,
	@bigUserId			bigint,
	@bigOrganizationID	bigint,
	@VehType tinyint,
	@CurEnergytype INT =0
	--@x					int,
	--@y					int
)				
RETURNS		nvarchar(MAX)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @BoxIds					TABLE (BOXID Varchar(Max),VehicleId INT,VehicleDescription nVarchar(150),Vehicletype Varchar(50))
	DECLARE @ChangedTemplate		nvarchar(MAX)
	DECLARE @CurrValue				int
	DECLARE @CurrValueFormatted		nvarchar(50)
	DECLARE @intBoxID				int
	DECLARE @dtStartDate			datetime = NULL  
 	DECLARE @dtEndDate				datetime = NULL



	SET @dtStartDate = DATEADD(Hour,-@Duration,GETUTCDATE())
	SET @dtEndDate = GETUTCDATE()
	
	INSERT	INTO @BoxIds (BOXID,VehicleId,VehicleDescription,Vehicletype)
	SELECT	va.BoxID,v.VehicleId,v.VehicleDescription,VT.VehicleTypeName FROM rvlfVehicleAssignment va
	INNER	JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
	Inner   Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
	INNER	JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
	INNER	JOIN rvlfVehicleType VT ON VT.VehicleTypeId = v.VehicleTypeId
	WHERE	fv.FleetId = @FleetId AND (@BoxId IS NULL OR @BoxId = '0' OR @BoxId = '' or
    va.BoxId	in (select * from rvlf_fn_ConvertArrayToTable(@BoxId,','))) AND V.OrganizationId = @bigOrganizationID AND VT.VehicleTypeId = @VehType
    ORDER	BY BoxId	
	
	--SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@BoxId,',')
		 
	DECLARE @Lang varchar(50)       
	SELECT @Lang=isnull(Lang,'LanguageEn') FROM rvlfUserPreferences WHERE UserId = @bigUserId

    DECLARE @DefaultDateFormat INT = 0     
	SELECT  @DefaultDateFormat=(CASE WHEN  isnull(up.DefaultDateFormat,0)= 0 THEN 106 ELSE up.DefaultDateFormat END)      
	FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId      
            
	IF @FleetId IS NULL      
	BEGIN      
		SELECT @FleetId=FleetID FROM rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1      
	END      
	------------------Get VehicleType use SPark per minutes--------------------------------------------
	DECLARE @vehicleType INT 	
	  SELECT @vehicleType= t.VehicleTypeId FROM rvlfVehicleAssignment va
	    INNER	JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
	    INNER	JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
	    INNER   JOIN rvlfVehicleType t On t.VehicleTypeId = v.VehicleTypeId 
	  WHERE	fv.FleetId = @FleetId AND (@BoxId IS NULL OR @BoxId = '0' OR @BoxId = '' or
        BoxId	in (select * from rvlf_fn_ConvertArrayToTable(@BoxId,','))) AND V.OrganizationId = @bigOrganizationID
     GROUP	BY t.VehicleTypeId 
 ------------------------------------------------------------------------- 

	DECLARE @HoursToBeAdded INT = 0      
	DECLARE @MinsToBeAdded INT = 0      
	DECLARE @ConversionFactor NUMERIC (10,2) = 1.0      
	DECLARE @DistanceCaptionPrefix VARCHAR(15)      
	DECLARE @SpeedCaptionPrefix VARCHAR(15)      
	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
			@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,        
			@DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Kms)' END,      
			@SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END      
	FROM	rvlfUserPreferences up 
	INNER	JOIN rvlfTimeZones tz ON	up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId          
          
	--SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))      
	--SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                 
    
	DECLARE @dtFDate DATETIME = @dtStartDate    
	DECLARE @dtEDate DATETIME = @dtEndDate
	  
	DECLARE @tblVehicles TABLE      
	(
	    Id bigint Identity(1,1),
		VehicleId bigint,
		VehicleDescription nvarchar(50),
		LicensePlate varchar(50),
		Vin varchar(50),
		Boxid Varchar(Max),
		NoofTrips int,
		Distance int,
		RunningTime INT,
		IdlingTime BIGINT,
		DaysUtilizaed varchar(30),
		FleetName varchar(50),
		SpeedViolations		int,
		HarshAcceleration	int,
		ExtremeAcceleration	int,
		HarshBraking		int,
		ExtremeBraking		int,
		Temperature			int,
		SparkPMmaxval INT,
		SPMmaxcount INT,
		[Current] INT,
	    Energy  INT,
		[Power] INT,
		T1 INT,T2 INT,T3 INT,T4 INT,P1 INT,
		P2 INT,P3 INT, P4 INT,DPp INT,
		DPp1 INT, DPps INT, P5 INT, P6 INT, P7 INT, P8 INT, P9 INT, P10 INT, P11 INT	
	)
      
	DECLARE @tblMessageForProcessingTrip TABLE (      
		[ProcessorID] [bigint] identity(1,1) NOT NULL,
		[Boxid] [varchar](250) NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[IgnitionStatus] [bit] NULL,
		[CustomProp] [varchar](max) NULL,
		[TripId] [bigint] NULL,
		[Current] INT,
	    Energy  INT,
		[Power]  NUMERIC(4,1),
		T1 INT,T2 INT,T3 INT,T4 INT,P1 INT,
		P2 INT,P3 INT, P4 INT,DPp INT,DPp1 INT, DPps INT,P5 INT, P6 INT, P7 INT, P8 INT, P9 INT, P10 INT, P11 INT
	)      

	INSERT	INTO @tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin,FleetName)      
	SELECT	VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin,f.FleetName
	FROM	rvlfBoxId BI
	INNER	JOIN rvlfVehicleAssignment VA ON BI.BoxId=VA.BoxId       
	INNER	JOIN rvlfFleetVehicles FV ON FV.VehicleId =VA.VehicleId       
	INNER	JOIN rvlfFleet F ON FV.FleetId=F.FleetId       
	INNER	JOIN rvlfVehicle V ON FV.VehicleId=V.VehicleId  	     
	INNER	JOIN rvlfOrganization O ON O.OrganizationId =F.OrganizationId       
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR V.OrganizationId = @bigOrganizationID AND F.OrganizationId = @bigOrganizationID)
	AND		(@FleetId IS NULL OR @FleetId = '' OR F.FleetId = @FleetId)
	AND		VA.BoxId IN (SELECT BOXID FROM @BoxIds)
	ORDER	BY BI.BOXID

	--GET THE TRIPS      
	DECLARE @tblTrips TABLE
	(
		ProcessId bigint identity(1,1),
		Boxid varchar(250) null,
		TripTime datetime null,
		TripStatus varchar(10) null
	)
       
	--GET THE TRIP DETAILS      
	DECLARE @tblTripDetails TABLE      
	(        
		TripId bigint identity(1,1),      
		Boxid varchar(250) null,        
		StartTime datetime null,      
		EndTime datetime null,      
		TripInStatus varchar(5) null,      
		TripOutStatus varchar(5) null,      
		RunningTime int null,      
		IdlingTime int null       
	)	

	DECLARE @TblSpm Table
	(
	  SPMId bigint identity(1,1),
	  Origindatetime datetime NULL,
	  SPMvalues INT NULL,
	  Boxid varchar(250) NULL
	)
	--IF(@vehicleType=1)
	-- BEGIN
	--   INSERT INTO @TblSpm
	--   SELECT Origindatetime,spark_rate,boxid FROM rvlfmsginhstparam_piii WHERE  BoxId IN (SELECT BOXID FROM @BoxIds) AND  Spark_Rate is not null AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)
	-- END
	--  ELSE
	--    BEGIN
	--	   INSERT INTO @TblSpm
	--	   SELECT Origindatetime,Spark_Per_Minute,boxid FROM rvlfmsginhstparam_pR WHERE BoxId IN (SELECT BOXID FROM @BoxIds) AND  Spark_Rate is not null AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)
	--	END

	--GET TEMPERATURE PACKETS		
	--DECLARE @tblTemperatureDetails TABLE      
	--(        
	--	MessageInId uniqueidentifier,
	--	BoxId bigint,
	--	BoxMsgInTypeId int,
	--	CustomProp varchar(600),
	--	TemperatureValue numeric(18,2)
	--)
	      
	--DECLARE @intBoxLoop bigint =(SELECT MIN(Boxid) FROM @tblVehicles)      
      DECLARE @intBoxLoop bigint =(SELECT MIN(Id) FROM @tblVehicles)  
	  Declare @BoxIdd varchar(50);
	WHILE @intBoxLoop IS NOT NULL      
	BEGIN       
	    SELECT @BoxIdd =Boxid FROM @tblVehicles WHERE Id=@intBoxLoop
		DELETE FROM @tblMessageForProcessingTrip        
		INSERT INTO @tblMessageForProcessingTrip(Boxid,OriginDateTime,BoxMsgInTypeId,IgnitionStatus,CustomProp,[Current],Energy,[Power],T1,T2,T3,T4
		,P1,P2,P3,P4,DPps,DPp,DPp1,P5,P6,P7,P8,P9,P10,P11)      
		SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,      
		CAST(SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,h.CustomProp,
		--CASE WHEN h.CustomProp like '%CR1=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'CR1=',';'),'0') END,
		CASE WHEN @CurEnergytype = 1 THEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'CR1_R=',';'),'0') 
		     WHEN @CurEnergytype = 2 THEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'CR2_R=',';'),'0')
			 WHEN @CurEnergytype = 3 THEN ISNULL(S.CR3_R,'0') 
			 WHEN @CurEnergytype= 4  THEN ISNULL(S.CR4_R,'0')   WHEN @CurEnergytype =5  THEN ISNULL(S.CR5_R,'0')   WHEN @CurEnergytype = 6  THEN ISNULL(PR.CR6_R,'0')
			 WHEN @CurEnergytype= 7  THEN ISNULL(PR.CR7_R,'0')  WHEN @CurEnergytype =8  THEN ISNULL(PR.CR8_R,'0')  WHEN @CurEnergytype = 9  THEN ISNULL(PR.CR9_R,'0')
			 WHEN @CurEnergytype= 10 THEN ISNULL(PR.CR10_R,'0')WHEN @CurEnergytype =11 THEN ISNULL(PR.CR11_R,'0') WHEN @CurEnergytype = 12 THEN ISNULL(FC.CR12_R,'0')			 
			 WHEN @CurEnergytype= 13 THEN ISNULL(FC.CR13_R,'0')WHEN @CurEnergytype =14 THEN ISNULL(FC.CR14_R,'0') WHEN @CurEnergytype = 15 THEN ISNULL(FC.CR15_R,'0')
			 WHEN @CurEnergytype= 16 THEN ISNULL(FC.CR16_R,'0')WHEN @CurEnergytype =17 THEN ISNULL(FC.CR17_R,'0') WHEN @CurEnergytype = 18 THEN ISNULL(FC.CR18_R,'0')
			 WHEN @CurEnergytype= 19 THEN ISNULL(FC.CR19_R,'0')ELSE '0' END,
		--dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'CR1_R=',';'),		
		--CASE WHEN h.CustomProp like '%WH1=NaN%' THEN '0' 		    
		--ELSE CASE WHEN @CurEnergytype = 1 THEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'WH1=',';'),'0') END END,
		CASE WHEN @CurEnergytype = 1 THEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'WH1=',';'),'0') 
		     WHEN @CurEnergytype = 2 THEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'WH2=',';'),'0')
			 WHEN @CurEnergytype = 3 THEN ISNULL(S.WH3,'0') 
			 WHEN @CurEnergytype= 4  THEN ISNULL(S.WH4,'0')   WHEN @CurEnergytype =5  THEN ISNULL(S.WH5,'0')   WHEN @CurEnergytype = 6  THEN ISNULL(PR.WH6,'0')
			 WHEN @CurEnergytype= 7  THEN ISNULL(PR.WH7,'0')  WHEN @CurEnergytype =8  THEN ISNULL(PR.WH8,'0')  WHEN @CurEnergytype = 9  THEN ISNULL(PR.WH9,'0')
			 WHEN @CurEnergytype= 10 THEN ISNULL(PR.WH10,'0')WHEN @CurEnergytype =11 THEN ISNULL(PR.WH11,'0') WHEN @CurEnergytype = 12 THEN ISNULL(FC.WH12,'0')			 
			 WHEN @CurEnergytype= 13 THEN ISNULL(FC.WH13,'0')WHEN @CurEnergytype =14 THEN ISNULL(FC.WH14,'0') WHEN @CurEnergytype = 15 THEN ISNULL(FC.WH15,'0')
			 WHEN @CurEnergytype= 16 THEN ISNULL(FC.WH16,'0')WHEN @CurEnergytype =17 THEN ISNULL(FC.WH17,'0') WHEN @CurEnergytype = 18 THEN ISNULL(FC.WH18,'0')
			 WHEN @CurEnergytype= 19 THEN ISNULL(FC.WH19,'0')ELSE '0' END,
		CASE WHEN h.CustomProp like '%PO1=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'PO1=',';'),'0') END,
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'T1_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'T2_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'T3_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'T4_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'P1_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'P2_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'P3_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'P4_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'DPps_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'DPp_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'DPp1_R=',';'),
		ISNULL(S.P5_R,'0'),ISNULL(PR.P6_R,'0'),ISNULL(PR.P7_R,'0'),ISNULL(FC.P8_R,'0'),
		ISNULL(FC.P9_R,'0'),ISNULL(FC.P10_R,'0'),ISNULL(FC.P11_R,'0')                
		FROM rvlfMsgInHst h 
		INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
		LEFT OUTER JOIN rvlfMsgInHst_Primary PR ON PR.MessageInID = h.MessageInID
		LEFT OUTER JOIN rvlfMsgInHst_Secondary S ON S.MessageInID = h.MessageInID
		LEFT OUTER JOIN rvlfMsgInHst_FibreCompactor FC ON FC.MessageInID = h.MessageInID                  
		WHERE m.OperationTypeID IN (SELECT p.OperationID  FROM rvlfPackageOperations p WHERE p.PackageId =       
		(SELECT op.PackageId FROM rvlfOrganizationPackage op WHERE op.OrganizationID = @bigOrganizationID      
		AND op.IsActive=1)      
		AND p.ModuleID = 26) and m.OperationTypeID IS NOT NULL                      
		AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
		AND h.BoxID = @BoxIdd  AND h.BoxMsgInTypeId NOT IN(8)		
		ORDER BY h.origindatetime ASC 
		UPDATE	@tblVehicles 
		SET		
		   [Current] = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip  WHERE (BoxId = @BoxIdd  AND [Current] = 1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),	
		   --[Current] = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip  WHERE (BoxId = @BoxIdd ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND [Current] > @MaxRange),	
		   Energy = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip  WHERE (BoxId = @BoxIdd ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND Energy > @MaxRange),	
		   [Power] = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip  WHERE (BoxId = @BoxIdd ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND [Power] > @MaxRange),	
		   T1 = (SELECT COUNT(*) from @tblMessageForProcessingTrip  WHERE (BoxId = @BoxIdd AND T1=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   T2 = (SELECT COUNT(*) from @tblMessageForProcessingTrip  WHERE (BoxId = @BoxIdd AND T2=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   T3 = (SELECT COUNT(*) from @tblMessageForProcessingTrip  WHERE (BoxId = @BoxIdd AND T3=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   T4 = (SELECT COUNT(*) from @tblMessageForProcessingTrip  WHERE (BoxId = @BoxIdd AND T4=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P1 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND P1=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P2 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND P2=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P3 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND P3=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P4 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND P4=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   DPps = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND DPps=1)AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   DPp1 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND DPp1=1)AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   DPp = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND DPp=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P5 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND P5=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P6 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND P6=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P7 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND P7=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P8 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND P8=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P9 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND P9=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P10 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND P10=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P11 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @BoxIdd AND P11=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate))
		WHERE	Boxid = @BoxIdd AND Distance IS NULL
        
		--CALCULATE THE UTILIZED DAYS
		UPDATE @tblVehicles SET DaysUtilizaed =(SELECT CASE WHEN COUNT(Actions)>CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) THEN CAST(COUNT(Actions)-1 as varchar) ELSE CAST(COUNT(Actions) as varchar) END  
												--+ ' out of '+CAST( CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) AS VARCHAR) 
												FROM (SELECT COUNT(BoxId) AS Actions       
		FROM @tblMessageForProcessingTrip        
		WHERE BoxId=@BoxIdd AND    
		(OriginDateTime BETWEEN  dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtStartDate) AND dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtEndDate))    
		--(OriginDateTime BETWEEN DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtStartDate)) AND DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEndDate)))    
		AND BoxMsgInTypeId IN (2,3)      
		GROUP BY CONVERT(DATE,OriginDateTime))AS A)      
		WHERE Boxid =@BoxIdd AND DaysUtilizaed IS NULL      
        
		--CALCULATE THE NOOFTRIPS,RUNNING TIME AND IDLING TIME
		DELETE FROM @tblTrips       
		DELETE FROM @tblTripDetails       
		INSERT INTO @tblTrips (Boxid,TripTime,TripStatus)      
		SELECT BoxId,OriginDateTime,CASE WHEN BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'START'       
		WHEN BoxMsgInTypeId =3 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'STOP' ELSE NULL END          
		FROM rvlfMsgInHst       
		WHERE Boxid =@BoxIdd      
		AND BoxMsgInTypeId IN(2,3)                
		AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate        
		ORDER BY BoxId,OriginDateTime       
          
		INSERT INTO @tblTripDetails (Boxid,EndTime,TripOutStatus,StartTime,TripInStatus)      
		SELECT MT.Boxid,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus      
		FROM @tblTrips AS MT       
		LEFT OUTER JOIN @tblTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'START'       
         
		--DELETE THE INVALID TRIPS      
		DELETE FROM @tblTripDetails WHERE StartTime IS NULL OR TripInStatus=TripOutStatus          
	
		Declare @RunTime as bigint
		--Set @RunTime = (Select CAST(IsNull(DateDiff(ss,Max(B.StartDate),Max(A.LastReporteDateTime)),0) AS INT) From adrControllerMaster A INNER JOIN adr_rvlfTripDetails B 
		--						ON A.EquipmentId=B.BoxId Where B.BoxID=@intBoxLoop)  @dtStartDate,@dtEndDate

		Set @RunTime = (Select CAST(IsNull(DateDiff(ss,@dtStartDate,Max(A.LastReporteDateTime)),0) AS INT) From adrControllerMaster A 
		--INNER JOIN adr_rvlfTripDetails B  A.EquipmentId=B.BoxId 
		Where A.EquipmentId=@BoxIdd)

		IF(@RunTime < 0)
		BEGIN
		 SET @RunTime =0
		END 

		UPDATE @tblVehicles SET NoofTrips=12,RunningTime=12,IdlingTime=@RunTime WHERE Boxid = @BoxIdd

		SELECT @intBoxLoop = MIN(Id) FROM @tblVehicles WHERE Id > @intBoxLoop        
	END
    
	--FETCHING KPI DETAILS
	DECLARE @intLoopi bigint = NULL
	Declare @Box varchar(50);
	SELECT  @intLoopi = MIN(Id) FROM @tblVehicles
	
	DECLARE @vcDetailData VARCHAR(MAX) = ''
	DECLARE @tblDetailData TABLE(TId BIGINT IDENTITY(1,1) PRIMARY KEY, BoxId VARCHAR(100), VehicleDescription nvarchar(50),T1 INT, T2 INT, T3 INT,T4 INT, [Current] NUMERIC(18,2),
								 Energy INT,[Power]  INT,P1 INT,P2 INT,P3 INT, P4 INT,DPp INT,DPp1 INT, DPps INT,P5 INT, P6 INT, P7 INT, P8 INT, P9 INT, P10 INT, P11 INT )

	WHILE @intLoopi IS NOT NULL
	BEGIN
	    SELECT @Box =Boxid FROM @tblVehicles WHERE Id=@intLoopi			
		INSERT	INTO @tblDetailData
		SELECT	BoxId, VehicleDescription,T1,T2,T3,T4,[Current],Energy,[Power],			
				P1,P2,P3,P4,DPp,DPp1,DPps,P5,P6,P7,P8,P9,P10,P11
		FROM @tblVehicles  
		WHERE	Boxid = @Box


		SELECT	@vcDetailData = @vcDetailData + 
					(CASE @KPIID 					
			   WHEN 1 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST([Current] AS VARCHAR) + ' </td><td>' + 
									CASE WHEN ([Current] < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN ([Current] > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN ([Current] BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'	
               WHEN 2 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(Energy AS VARCHAR) + ' </td><td>' + 
									CASE WHEN (Energy < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN (Energy > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (Energy BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
			  WHEN 3 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(T1 AS VARCHAR) + ' </td><td>' + 
									CASE WHEN (T1 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN (T1 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (T1 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
			 WHEN 4 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(T2 AS VARCHAR) + ' </td><td>' + 
									CASE WHEN (T2 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">'
													WHEN (T2 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (T2 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">'
												    END	+ '</td></tr>'
		    WHEN 5 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(T3 AS VARCHAR) + ' </td><td>' + 
			 					CASE WHEN (T3 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
			 									WHEN (T3 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
			 									WHEN (T3 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
			 									END	+ '</td></tr>'
		    WHEN 6 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(T4 AS VARCHAR) + ' </td><td>' + 
			 					CASE WHEN (T4 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">'
			 									WHEN (T4 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
			 									WHEN (T4 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
			 										END	+ '</td></tr>'
			WHEN 7 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(P1 AS VARCHAR) + ' </td><td>'+ 
			 					CASE WHEN (P1 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
			 									WHEN (P1 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
			 									WHEN (P1 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
			 										END	+ '</td></tr>'
            WHEN 8 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(P2 AS VARCHAR) + ' </td><td>'+ 
			 					CASE WHEN (P2 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
			 									WHEN (P2 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
			 									WHEN (P2 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
			 										END	+ '</td></tr>'
            WHEN 9 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(P3 AS VARCHAR) + ' </td><td>'+ 
			 			 		CASE WHEN (P3 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
			 									WHEN (P3 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
			 									WHEN (P3 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
			  										END	+ '</td></tr>'
           WHEN 10 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(P4 AS VARCHAR) + ' </td><td>'+ 
			 			 		CASE WHEN (P4 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN (P4 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (P4 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
           WHEN 11 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(DPps AS VARCHAR) + ' </td><td>'+ 
							 		CASE WHEN (DPps < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN (DPps > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (DPps BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
          WHEN 12 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(DPp AS VARCHAR) + ' </td><td>'+ 
							 		CASE WHEN (DPp < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN (DPp > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (DPp BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
          WHEN 13 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(DPp1 AS VARCHAR) + ' </td><td>'+ 
							 		CASE WHEN (DPp1 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN (DPp1 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (DPp1 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'
         WHEN 15 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST([Power] AS VARCHAR) + ' </td><td>'+ 
							 		CASE WHEN ([Power] < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN ([Power] > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN ([Power] BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'	

       WHEN 16 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(P5 AS VARCHAR) + ' </td><td>'+ 
							 		CASE WHEN (P5 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN (P5 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (P5 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'	
       WHEN 17 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(P6 AS VARCHAR) + ' </td><td>'+ 
							 		CASE WHEN (P6 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN (P6 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (P6 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'																													
	   WHEN 18 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(P7 AS VARCHAR) + ' </td><td>'+ 
							 		CASE WHEN (P7 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN (P7 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (P7 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'	
       WHEN 19 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(P8 AS VARCHAR) + ' </td><td>'+ 
							 		CASE WHEN (P8 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN (P8 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (P8 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'	
       WHEN 20 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(P9 AS VARCHAR) + ' </td><td>'+ 
							 		CASE WHEN (P9 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN (P9 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (P9 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'	
       WHEN 21 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(P10 AS VARCHAR) + ' </td><td>'+ 
							 		CASE WHEN (P10 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN (P10 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (P10 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'	
      WHEN 22 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(P11 AS VARCHAR) + ' </td><td>'+ 
							 		CASE WHEN (P11 < @MinRange) THEN '<img src="../images/GreenKPI.png" title="Safe">' 
													WHEN (P11 > @MaxRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
													WHEN (P11 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
														END	+ '</td></tr>'																																																																						
						ELSE '<tr><td colspan="3">No data found.</td></tr>'
					END)
		FROM	@tblDetailData  
		WHERE	TId = @intLoopi
		
		SELECT @intLoopi = MIN(Id) FROM @tblVehicles WHERE Id > @intLoopi
	END

	DECLARE @TotalT1                INT =NULL
	DECLARE @TotalT2                INT =NULL
	DECLARE @TotalT3                INT =NULL,@TotalP4 INT = NULL, @TotalDPps INT = NULL, @TotalDPp INT = NULL,@TotalDPp1 INT = NULL
	DECLARE @TotalT4                INT =NULL,@TotalCurrent INT = NULL, @TotalEnergy INT = NULL, @TotalPower INT = NULL, @TotalP1 INT = NULL, 
	                                          @TotalP2 INT = NULL, @TotalP3 INT = NULL,@TotalP5 INT, @TotalP6 INT, @TotalP7 INT, @TotalP8 INT,
											  @TotalP9 INT, @TotalP10 INT, @TotalP11 INT
    DECLARE @KPICurrSts  varchar(20) =NULL,@KPIP3Sts  varchar(20) =NULL,@KPIP5Sts varchar(20) ,@KPIP6Sts varchar(20) , @KPIP7Sts varchar(20) , @KPIP8Sts varchar(20) 
    DECLARE @KPIT1Sts  varchar(20) =NULL,  @KPIP4Sts  varchar(20) =NULL,@KPIP9Sts varchar(20) ,@KPIP10Sts varchar(20) ,@KPIP11Sts varchar(20) 
	DECLARE @KPIT2Sts  varchar(20) =NULL,  @KPIDPpsSts  varchar(20) =NULL
	DECLARE @KPIT3Sts  varchar(20) =NULL,  @KPIDPpSts  varchar(20) =NULL 
	DECLARE @KPIT4Sts  varchar(20) =NULL,  @KPIDPp1Sts  varchar(20) =NULL
	DECLARE @KPIP1Sts  varchar(20) =NULL
	DECLARE @KPIP2Sts  varchar(20) =NULL
	
	SELECT				
			-------------------------------- Total Count KPI's --------------------------------------------------------------------------
			@TotalT1 = CASE WHEN T1 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T1 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T1 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T1 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T1 BETWEEN @MinRange AND @MaxRange) END 
			           END,		
			@TotalT2 = CASE WHEN T2 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T2 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T2 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T2 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T2 BETWEEN @MinRange AND @MaxRange) END 
			           END,			
			@TotalT3 = CASE WHEN T3 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T3 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T3 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T3 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T3 BETWEEN @MinRange AND @MaxRange) END 
			           END,			
			@TotalT4 = CASE WHEN T4 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T4 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T4 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T4 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T4 BETWEEN @MinRange AND @MaxRange) END 
			           END,			
			@TotalCurrent = CASE WHEN [Current] > @MaxRange THEN Count(VehicleDescription) ELSE 
			                CASE WHEN 
			                (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE [Current] < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE [Current] BETWEEN @MinRange AND @MaxRange) 
			                THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE [Current] < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE [Current] BETWEEN @MinRange AND @MaxRange) END 
			                END, 
			@TotalEnergy = SUM(CAST(Energy AS INT)), @TotalPower = SUM(CAST([Power] AS INT)),			
			@TotalP1 = CASE WHEN P1 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) END 
			           END,			
			@TotalP2 = CASE WHEN P2 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P2 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P2 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P2 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P2 BETWEEN @MinRange AND @MaxRange) END 
			           END,			
			@TotalP3 = CASE WHEN P3 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P3 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P3 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P3 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P3 BETWEEN @MinRange AND @MaxRange) END 
			           END,			
			@TotalP4 = CASE WHEN P4 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P4 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P4 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P4 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P4 BETWEEN @MinRange AND @MaxRange) END 
			           END,			
			@TotalDPp =CASE WHEN DPp > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp BETWEEN @MinRange AND @MaxRange) END 
			           END,			
			@TotalDPps =CASE WHEN DPps > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps BETWEEN @MinRange AND @MaxRange) END 
			           END,			
			@TotalDPp1 = CASE WHEN DPp1 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp1 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp1 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp1 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp1 BETWEEN @MinRange AND @MaxRange) END 
			           END,
            @TotalP5 = CASE WHEN P5 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P5 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P5 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) END 
			           END,
            @TotalP6 = CASE WHEN P6 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P6 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P6 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
          	@TotalP7 = CASE WHEN P7 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P7 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P7 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
           @TotalP8 = CASE WHEN P8 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P8 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P8 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) END 
			           END,
           @TotalP9 = CASE WHEN P9 > @MaxRange THEN Count(VehicleDescription) ELSE 
		 	           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P9 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P9 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) END 
			           END,		
           @TotalP10 = CASE WHEN P10 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P10 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P10 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
           @TotalP11 = CASE WHEN P11 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P11 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P11 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) END 
			           END,						   					   				   						   				   							   			
			---------------------- KPI Status -----------------------------------------
			@KPICurrSts = CASE WHEN [Current] > @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE [Current] < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE [Current] BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIT1Sts = CASE WHEN T1 > @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T1 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T1 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIT2Sts = CASE WHEN T2 > @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T2 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T2 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,	
			 @KPIT3Sts = CASE WHEN T3 > @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T3 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T3 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,	
			 @KPIT4Sts = CASE WHEN T4 > @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T4 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T4 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,	
			 @KPIP1Sts = CASE WHEN P1> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			  @KPIP2Sts = CASE WHEN P2> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P2 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P2 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIP3Sts = CASE WHEN P3> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P3 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P3 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIP4Sts =CASE WHEN P4> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P4 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P4 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIDPpSts =CASE WHEN DPp> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIDPpsSts =CASE WHEN DPps> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIDPpsSts =CASE WHEN DPps> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIDPp1Sts =CASE WHEN DPp1> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp1 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp1 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIP5Sts = CASE WHEN P5> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P5 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P5 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			  @KPIP6Sts = CASE WHEN P6> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P6 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P6 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			  @KPIP7Sts = CASE WHEN P7> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P7 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P7 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			  @KPIP8Sts = CASE WHEN P8> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P8 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P8 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			  @KPIP9Sts = CASE WHEN P9> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P9 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P9 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			  @KPIP10Sts = CASE WHEN P10> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P10 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P10 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			  @KPIP11Sts = CASE WHEN P11> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P11 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P11 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END
	FROM	@tblDetailData Group by T1,T2,T3,T4,[Current],P1,P2,P3,P4,DPp,DPp1,DPps,P5,P6,P7,P8,P9,P10,P11

	

	-- FETCHING KPI CHART DATA
	DECLARE @intSafe		VARCHAR(5) = NULL
	DECLARE @intWarning		VARCHAR(5) = NULL
	DECLARE @intCritical	VARCHAR(5) = NULL

	-- TEMPLATE REPLACING WITH KPI VALUES BASED ON KPI TYPE
	IF (@KPIID = 1) 
	BEGIN		
		SELECT	@CurrValue = @TotalCurrent, @CurrValueFormatted = @TotalCurrent
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE [Current] BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE [Current] < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE [Current] > @MaxRange		
	END
	ELSE IF (@KPIID = 2) 
	BEGIN	
		SELECT	@CurrValue = @TotalEnergy, @CurrValueFormatted = @TotalEnergy
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE Energy BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE Energy < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE Energy > @MaxRange
	END
	ELSE IF (@KPIID = 3) 
	BEGIN		
		SELECT	@CurrValue = @TotalT1, @CurrValueFormatted = @TotalT1
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE T1 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE T1 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE T1 > @MaxRange
	END
	ELSE IF (@KPIID = 4) 
	BEGIN
		SELECT	@CurrValue = @TotalT2, @CurrValueFormatted = @TotalT2
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE T2 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE T2 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE T2 > @MaxRange
	END
	ELSE IF (@KPIID = 5) 
	BEGIN
		SELECT	@CurrValue = @TotalT3, @CurrValueFormatted = @TotalT3
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE T3 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE T3 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE T3 > @MaxRange
	END
	ELSE IF (@KPIID = 6) 
	BEGIN
		SELECT	@CurrValue = @TotalT4, @CurrValueFormatted = @TotalT4
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE T4 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE T4 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE T4 > @MaxRange
	END
	ELSE IF (@KPIID = 7) 
	BEGIN
	     
		SELECT	@CurrValue = @TotalP1, @CurrValueFormatted = @TotalP1
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE P1 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE P1 > @MaxRange		
	END
	ELSE IF(@KPIID = 8)
	BEGIN 
	    SELECT	@CurrValue = @TotalP2, @CurrValueFormatted = @TotalP2
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE P2 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE P2 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE P2 > @MaxRange		
	END
	ELSE IF(@KPIID = 9)
	BEGIN 
	    SELECT	@CurrValue = @TotalP3, @CurrValueFormatted = @TotalP3
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE P3 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE P3 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE P3 > @MaxRange		
	END
	ELSE IF(@KPIID = 10)
	BEGIN 
		SELECT	@CurrValue = @TotalP4, @CurrValueFormatted = @TotalP4
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE T4 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE T4 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE T4 > @MaxRange
	END
	ELSE IF(@KPIID = 11)
	BEGIN 
		SELECT	@CurrValue = @TotalDPps, @CurrValueFormatted = @TotalDPps
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE DPps BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE DPps < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE DPps > @MaxRange
	END
	ELSE IF(@KPIID = 12)
	BEGIN 
		SELECT	@CurrValue = @TotalDPp, @CurrValueFormatted = @TotalDPp
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE DPp BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE DPp < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE DPp > @MaxRange
	END
	ELSE IF(@KPIID = 13)
	BEGIN 
		SELECT	@CurrValue = @TotalDPp1, @CurrValueFormatted = @TotalDPp1
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE DPp1 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE DPp1 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE DPp1 > @MaxRange
	END
	ELSE IF(@KPIID = 15)
	BEGIN 
		SELECT	@CurrValue = @TotalPower, @CurrValueFormatted = @TotalPower
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE [Power] BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE [Power] < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE [Power] > @MaxRange
	END
	ELSE IF(@KPIID = 16)
	BEGIN 
	    SELECT	@CurrValue = @TotalP5, @CurrValueFormatted = @TotalP5
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE P5 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE P5 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE P5 > @MaxRange		
	END
	ELSE IF(@KPIID = 17)
	BEGIN 
	    SELECT	@CurrValue = @TotalP6, @CurrValueFormatted = @TotalP6
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE P6 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE P6 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE P6 > @MaxRange		
	END
	ELSE IF(@KPIID = 18)
	BEGIN 
	    SELECT	@CurrValue = @TotalP7, @CurrValueFormatted = @TotalP7
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE P7 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE P7 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE P7 > @MaxRange		
	END
	ELSE IF(@KPIID = 19)
	BEGIN 
	    SELECT	@CurrValue = @TotalP8, @CurrValueFormatted = @TotalP8
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE P8 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE P8 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE P8 > @MaxRange		
	END
	ELSE IF(@KPIID = 20)
	BEGIN 
	    SELECT	@CurrValue = @TotalP9, @CurrValueFormatted = @TotalP9
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE P9 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE P9 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE P9 > @MaxRange		
	END
	ELSE IF(@KPIID =21)
	BEGIN 
	    SELECT	@CurrValue = @TotalP10, @CurrValueFormatted = @TotalP10
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE P10 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE P10 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE P10 > @MaxRange		
	END
	ELSE IF(@KPIID = 22)
	BEGIN 
	    SELECT	@CurrValue = @TotalP11, @CurrValueFormatted = @TotalP11
		SELECT	@intWarning = COUNT(TId) FROM @tblDetailData WHERE P11 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(TId) FROM @tblDetailData WHERE P11 < @MinRange 
		SELECT	@intCritical = COUNT(TId) FROM @tblDetailData WHERE P11 > @MaxRange		
	END
	ELSE 
	BEGIN
		SELECT @CurrValueFormatted = '15' 
	END
	
	SELECT	@UnitName = CurrencyName FROM rvlfCurrencyType CT
	INNER	JOIN rvlfOrganization O ON CT.CurrencyTypeId = O.CurrencyTypeId
	WHERE	OrganizationId = @bigOrganizationID	and @KPIID in (9,10)

	-- Add the T-SQL statements to compute the return value here
	SET	@Template	= REPLACE(@Template ,'$ChartScript$', 'google.setOnLoadCallback(drawChart_$Sno$);function drawChart_$Sno$() {
										var data = new google.visualization.arrayToDataTable([[''Bands'', ''No.of.Devices(s)'', { role: ''style'' }],[''Safe'', '+ ISNULL(@intSafe,0) +', ''#04B713''],[''Warning'', '+ ISNULL(@intWarning,0) +', ''#FF7F00''],[''Critical'', '+ 
										ISNULL(@intCritical,0) +', ''#FE0000''],]);
										var options = {width: 330,height: 400,colors: [''Red''],chartArea: { width: ''50%'' },hAxis: {title: ''KPI Status'',minValue: 0},vAxis: {title: ''No.of.Devices(s)'',maxValue: 16,format: ''0'',gridlines: { count: 6 },minorGridlines: { count: 3 }},






 
legend: { position: "none" }};
										var chart = new google.visualization.ColumnChart(document.getElementById(''chart_div_$Sno$''));chart.draw(data, options);}')
	SET	@Template	= REPLACE(@Template ,'$Sno$', @Sno)
	SET	@Template	= REPLACE(@Template ,'$data-gs-id$', @AssignmentID)
	SET	@Template	= REPLACE(@Template ,'$gridData$', '<thead><th>Device</th><th>$KPICaption$</th><th>Status</th></thead><tbody>'+ @vcDetailData +'</tbody>')
	SET	@Template	= REPLACE(@Template ,'$AssignmentID$', @AssignmentID)
	SET	@Template	= REPLACE(@Template ,'$KPIUnitName$', 'Device(s)') --@UnitName

	DECLARE @KPIStatus nvarchar(10)
	--IF @KPIID =1
	--BEGIN
	--SET @KPIStatus = 'safe'
	--END
	--ELSE IF @KPIID = 3
	--BEGIN 
	--SET @KPIStatus = @KPIT1Sts
	----CASE WHEN (@CurrValue < @MinRange) THEN 'critical' WHEN (@CurrValue > @MaxRange) THEN 'safe' WHEN (@CurrValue between @MinRange and @MaxRange) THEN 'warning' ELSE 'safe' END
	--END
	IF @KPIID IN(2,15)
	BEGIN	
	SET @KPIStatus = CASE WHEN (@CurrValue < @MinRange) THEN 'safe' WHEN (@CurrValue > @MaxRange) THEN 'critical' WHEN (@CurrValue between @MinRange and @MaxRange) THEN 'warning' ELSE 'safe' END
	END
     ELSE
	   BEGIN
	  SET @KPIStatus = CASE WHEN @KPIID = 1 THEN @KPICurrSts WHEN @KPIID = 6 THEN @KPIT4Sts   WHEN @KPIID =10 THEN @KPIP4Sts
	                        WHEN @KPIID = 7 THEN @KPIP1Sts   WHEN @KPIID =11 THEN @KPIDPpsSts WHEN @KPIID =12 THEN @KPIDPpSts
						    WHEN @KPIID = 3 THEN @KPIT1Sts   WHEN @KPIID = 8 THEN @KPIP2Sts   WHEN @KPIID =13 THEN @KPIDPp1Sts
						    WHEN @KPIID = 4 THEN @KPIT2Sts   WHEN @KPIID = 9 THEN @KPIP3Sts   WHEN @KPIID = 16 THEN @KPIP5Sts 
						    WHEN @KPIID = 5 THEN @KPIT3Sts   WHEN @KPIID = 17 THEN @KPIP6Sts  WHEN @KPIID = 18 THEN @KPIP7Sts 
							WHEN @KPIID = 19 THEN @KPIP8Sts   WHEN @KPIID = 20 THEN @KPIP9Sts WHEN @KPIID = 21 THEN @KPIP10Sts 
							WHEN @KPIID = 22 THEN @KPIP11Sts  ELSE 'safe' END
	END
	SET	@Template	= REPLACE(@Template ,'$TileImgName$', 'img-' + @KPIStatus + '-kpi')
	SET	@Template	= REPLACE(@Template ,'$KPIValue$', @CurrValueFormatted)
	--SET	@Template	= REPLACE(@Template ,'$PnlTableClass2$', @KPIStatus)
	SET	@Template	= REPLACE(@Template ,'$PnlTableClass1$', CASE @DisplayTypeID WHEN 1  THEN 'tiletable' WHEN 2 THEN 'gaugetable' WHEN 3 THEN 'progresstable' WHEN 4 THEN 'tiletable' WHEN 5 THEN 'gridtable' END)
	SET	@Template	= REPLACE(@Template ,'$PanelClass$', CASE @DisplayTypeID WHEN 1 THEN 'tilediv' WHEN 2 THEN 'gaugediv' WHEN 3 THEN 'progressdiv' WHEN 4 THEN 'chartsdiv' WHEN 5 THEN 'griddiv' END)
	
	DECLARE @CustomTitleLen int 
	SET @CustomTitleLen = CASE @DisplayTypeID WHEN 1 THEN 25 ELSE 55 END 
	SET	@Template	= REPLACE(@Template ,'$CustomTitle$', CASE WHEN LEN(@CustomTitle) > @CustomTitleLen THEN SUBSTRING(@CustomTitle, 0, @CustomTitleLen) + '...' ELSE @CustomTitle END)
	SET	@Template	= REPLACE(@Template ,'$Tooltip$', @CustomTitle)
		
	DECLARE @PosX TINYINT, @PosY TINYINT
	SELECT @PosX = x, @PosY = y FROM rvlfKPIGridPosition POS
	RIGHT JOIN RVLFKPIUSERASSIGNMENT KUA ON POS.AssignmentId = KUA.ASSIGNMENTID
	WHERE KUA.AssignmentId = @AssignmentID

	SET	@Template	= REPLACE(@Template ,'$dataRows$', CASE WHEN @PosX IS NULL THEN 0 ELSE @PosX END)	
	--CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 3 THEN 3 WHEN 4 THEN 4 WHEN 5 THEN 5 END)  --CASE @Sno WHEN 1 THEN 1 WHEN 1 THEN 1 WHEN 3 THEN 1 WHEN 4 THEN 1 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataCols$', CASE WHEN @PosY IS NULL THEN 0 ELSE @PosY END)	--CASE WHEN @Sno < 5 THEN @Sno ELSE 4 END)

	SET	@Template	= REPLACE(@Template ,'$dataSize-y$', CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 1 WHEN 3 THEN 1 WHEN 4 THEN 3 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataSize-x$', CASE @DisplayTypeID WHEN 1 THEN 3 WHEN 2 THEN 3 WHEN 3 THEN 3 WHEN 4 THEN 4 WHEN 5 THEN 4 END)
	SET	@Template	= REPLACE(@Template ,'$KPICaption$', /*LOWER(@KPIName) + */ CASE WHEN @KPIID=7 THEN 'Value(' + @UnitName + ')' ELSE'Value(' + @UnitName + ')' END)
	SET @Template	= REPLACE(@Template, '$TitleColor$', 'style="background: ' + CASE WHEN @TitleClrCode IS NOT NULL THEN 'linear-gradient(to bottom, rgba(255,255,255,1) 1%,rgba(196,22,28,1) 50%); line-height: 17px; font-size: 12px; padding: 5px 30px;' ELSE @TitleClrCode END + '"')

	DECLARE @FleetName nvarchar(250)
	SET @FleetName	= (SELECT FleetName FROM rvlfFleet WHERE FleetId = @FleetId)
	SET	@Template	= REPLACE(@Template ,'$Fleet$', @FleetName)	
	SET @Template   = REPLACE(@Template, '$ESPType$',(SELECT DISTINCT Vehicletype FROM @BoxIds))
	SET	@Template	= REPLACE(@Template ,'$Vehicles$',	CASE @BoxId	WHEN '0' THEN 'All' 
														ELSE STUFF((SELECT ', ' + VehicleDescription FROM @BoxIds FOR XML PATH('')), 1, 1, '') END)
	SET	@Template	= REPLACE(@Template ,'$RefreshFreq$', CAST(@RefFreq AS VARCHAR(5)) + ' Sec')
	SET	@Template	= REPLACE(@Template ,'$Duration$', 'Last ' + CASE	WHEN @Duration = 336	THEN ' 2 Weeks'
																		WHEN @Duration Between 168	and 336 THEN ' 1 Week'
																		WHEN @Duration Between 48	and 168	THEN CAST(@Duration/24 AS Varchar(20)) + ' Days' 
																		ELSE CAST(@Duration AS Varchar(20)) + ' Hours' END)   
	
	SET	@Template	= REPLACE(@Template ,'$Range$', ((CASE	WHEN @KPIID IN (9,10) THEN (CONVERT(VARCHAR,CONVERT(MONEY,@MinRange),3) + ' to ' + CONVERT(VARCHAR,CONVERT(MONEY,@MaxRange),3))
															ELSE (CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20))) END)  
															+ ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END))

	SET @Template	= @Template + '<input type="hidden" value="KPIStatus:' + @KPIStatus + '">'
		
	-- Return the result of the function	
	SET	@ChangedTemplate = @Template
	RETURN @ChangedTemplate
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplateReversed]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasue
-- Create date: 21-01-2016
-- Description:	
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplateReversed]
(
	-- Add the parameters for the function here
	@Sno				int,
	@Template			nvarchar(MAX),
	@TitleClrCode		nvarchar(10),
	@AssignmentID		int,
	@CustomTitle		nvarchar(75),
	@KPIID				int,
	@KPIName			nvarchar(75),
	@DisplayTypeID		tinyint,
	@CostKPIsValue		decimal(18,2),
	@TemperatureType	tinyint,
	@UnitName			nvarchar(10),
	@MinRange			int,
	@MaxRange			int,
	@FleetId			int,
	@BoxId				nvarchar(1000),
	@RefFreq			int,
	@Duration			int,
	@bigUserId			bigint,
	@bigOrganizationID	bigint
)				
RETURNS		nvarchar(MAX)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @BoxIds					TABLE (BOXID bigint,VehicleId INT,VehicleDescription nVarchar(150))
	DECLARE @ChangedTemplate		nvarchar(MAX)
	DECLARE @CurrValue				int
	DECLARE @CurrValueFormatted		nvarchar(50)
	DECLARE @intBoxID				int
	DECLARE @dtStartDate			datetime = NULL  
 	DECLARE @dtEndDate				datetime = NULL

	SET @dtStartDate = DATEADD(Hour,-@Duration,GETUTCDATE())
	SET @dtEndDate = GETUTCDATE()
	
	INSERT	INTO @BoxIds (BOXID,VehicleId,VehicleDescription)
	SELECT	va.BoxID,v.VehicleId,v.VehicleDescription FROM rvlfVehicleAssignment va
	INNER	JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
	INNER	JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
	WHERE	fv.FleetId = @FleetId AND (@BoxId IS NULL OR @BoxId = '0' OR @BoxId = '' or
    BoxId	in (select * from rvlf_fn_ConvertArrayToTable(@BoxId,','))) AND V.OrganizationId = @bigOrganizationID
    ORDER	BY BoxId
	
	--SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@BoxId,',')
		 
	DECLARE @Lang varchar(50)       
	SELECT @Lang=isnull(Lang,'LanguageEn') FROM rvlfUserPreferences WHERE UserId = @bigUserId

    DECLARE @DefaultDateFormat INT = 0     
	SELECT  @DefaultDateFormat=(CASE WHEN  isnull(up.DefaultDateFormat,0)= 0 THEN 106 ELSE up.DefaultDateFormat END)      
	FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId      
        
        
	IF @FleetId IS NULL      
	BEGIN      
		SELECT @FleetId=FleetID FROM rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1      
	END      
	DECLARE @HoursToBeAdded INT = 0      
	DECLARE @MinsToBeAdded INT = 0      
	DECLARE @ConversionFactor NUMERIC (10,2) = 1.0      
	DECLARE @DistanceCaptionPrefix VARCHAR(15)      
	DECLARE @SpeedCaptionPrefix VARCHAR(15)      
	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
			@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,        
			@DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Kms)' END,      
			@SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END      
	FROM	rvlfUserPreferences up 
	INNER	JOIN rvlfTimeZones tz ON	up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId          
          
	--SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))      
	--SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                 
    
	DECLARE @dtFDate DATETIME = @dtStartDate    
	DECLARE @dtEDate DATETIME = @dtEndDate
	  
	DECLARE @tblVehicles TABLE      
	(
		VehicleId bigint,
		VehicleDescription nvarchar(50),
		LicensePlate varchar(50),
		Vin varchar(50),
		Boxid bigint,
		NoofTrips int,
		Distance int,
		RunningTime INT,
		IdlingTime INT,
		DaysUtilizaed varchar(30),
		FleetName varchar(50),
		SpeedViolations		int,
		HarshAcceleration	int,
		ExtremeAcceleration	int,
		HarshBraking		int,
		ExtremeBraking		int,
		Temperature			int
	)
      
	DECLARE @tblMessageForProcessingTrip TABLE (      
		[ProcessorID] [bigint] identity(1,1) NOT NULL,
		[Boxid] [int] NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[IgnitionStatus] [bit] NULL,
		[CustomProp] [varchar](600) NULL,
		[TripId] [bigint] NULL
	)      

	INSERT	INTO @tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin,FleetName)      
	SELECT	VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin,f.FleetName  
	FROM	rvlfBoxId BI
	INNER	JOIN rvlfVehicleAssignment VA ON BI.BoxId=VA.BoxId       
	INNER	JOIN rvlfFleetVehicles FV ON FV.VehicleId =VA.VehicleId       
	INNER	JOIN rvlfFleet F ON FV.FleetId=F.FleetId       
	INNER	JOIN rvlfVehicle V ON FV.VehicleId=V.VehicleId       
	INNER	JOIN rvlfOrganization O ON O.OrganizationId =F.OrganizationId       
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR V.OrganizationId =@bigOrganizationID AND F.OrganizationId =@bigOrganizationID)      
	AND		(@FleetId IS NULL OR @FleetId='' OR F.FleetId=@FleetId)      
	AND		VA.BoxId IN (SELECT BOXID FROM @BoxIds)      
	ORDER	BY BI.BOXID             

	--GET THE TRIPS      
	DECLARE @tblTrips TABLE      
	(      
		ProcessId bigint identity(1,1),      
		Boxid int null,        
		TripTime datetime null,      
		TripStatus varchar(10)null      
	)       
       
	--GET THE TRIP DETAILS      
	DECLARE @tblTripDetails TABLE      
	(        
		TripId bigint identity(1,1),      
		Boxid int null,        
		StartTime datetime null,      
		EndTime datetime null,      
		TripInStatus varchar(5) null,      
		TripOutStatus varchar(5) null,      
		RunningTime int null,      
		IdlingTime int null       
	)        
      
	DECLARE @intBoxLoop int =(SELECT MIN(Boxid) FROM @tblVehicles)      
      
	WHILE @intBoxLoop IS NOT NULL      
	BEGIN       
		DELETE FROM @tblMessageForProcessingTrip        
		INSERT INTO @tblMessageForProcessingTrip(Boxid,OriginDateTime,BoxMsgInTypeId,IgnitionStatus,CustomProp)      
		SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,      
		CAST(SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,h.CustomProp             
		FROM rvlfMsgInHst h       
		INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                    
		WHERE m.OperationTypeID IN (SELECT p.OperationID  FROM rvlfPackageOperations p WHERE p.PackageId =       
		(SELECT op.PackageId FROM rvlfOrganizationPackage op WHERE op.OrganizationID = @bigOrganizationID      
		AND op.IsActive=1)      
		AND p.ModuleID = 26) and m.OperationTypeID IS NOT NULL                      
		AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
		AND h.BoxID = @intBoxLoop      
		ORDER BY h.origindatetime ASC        
          
		--CALCULATE THE DISTANCE
		UPDATE @tblVehicles SET Distance = (SELECT CEILING((MAX(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,1))) -      
				(CHARINDEX('Odometer=',CustomProp,1)+9)),0) AS BIGINT)) - MIN(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,      
				CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9)),0)AS BIGINT))) * @ConversionFactor)  AS DISTANCE      
				FROM @tblMessageForProcessingTrip M         
				WHERE  (M.BoxId= @intBoxLoop)      
				AND (M.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)      
				AND CustomProp LIKE '%Odometer%' AND BoxMsgInTypeId in(2,3)),
				SpeedViolations = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 4) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 14) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 15) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 16) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 17) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				Temperature = (SELECT COUNT(BoxMsgInTypeId) from @tblMessageForProcessingTrip where BoxId = @intBoxLoop and BoxMsgInTypeId = (CASE @TemperatureType WHEN 1 THEN 82 WHEN 2 THEN 86 WHEN 3 THEN 166 WHEN 4 THEN 171 ELSE 0 END))
		WHERE Boxid =@intBoxLoop AND Distance IS NULL      
        
		--CALCULATE THE UTILIZED DAYS
		UPDATE @tblVehicles SET DaysUtilizaed =(SELECT CASE WHEN COUNT(Actions)>CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) THEN CAST(COUNT(Actions)-1 as varchar) ELSE CAST(COUNT(Actions) as varchar) END  
												--+ ' out of '+CAST( CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) AS VARCHAR) 
												FROM (SELECT COUNT(BoxId) AS Actions       
		FROM @tblMessageForProcessingTrip        
		WHERE BoxId=@intBoxLoop AND    
		(OriginDateTime BETWEEN  dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtStartDate) AND dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtEndDate))    
		--(OriginDateTime BETWEEN DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtStartDate)) AND DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEndDate)))    
		AND BoxMsgInTypeId IN (2,3)      
		GROUP BY CONVERT(DATE,OriginDateTime))AS A)      
		WHERE Boxid =@intBoxLoop AND DaysUtilizaed IS NULL      
        
		--CALCULATE THE NOOFTRIPS,RUNNING TIME AND IDLING TIME
		DELETE FROM @tblTrips       
		DELETE FROM @tblTripDetails       
		INSERT INTO @tblTrips (Boxid,TripTime,TripStatus)      
		SELECT BoxId,OriginDateTime,CASE WHEN BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'START'       
		WHEN BoxMsgInTypeId =3 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'STOP' ELSE NULL END          
		FROM rvlfMsgInHst       
		WHERE Boxid =@intBoxLoop      
		AND BoxMsgInTypeId IN(2,3)                
		AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate        
		ORDER BY BoxId,OriginDateTime       
          
		INSERT INTO @tblTripDetails (Boxid,EndTime,TripOutStatus,StartTime,TripInStatus)      
		SELECT MT.Boxid,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus      
		FROM @tblTrips AS MT       
		LEFT OUTER JOIN @tblTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'START'       
         
		--DELETE THE INVALID TRIPS      
		DELETE FROM @tblTripDetails WHERE StartTime IS NULL OR TripInStatus=TripOutStatus        
         
		--CALCULATE THE RUNNING TIME AND IDLING TIME       
		UPDATE @tblTripDetails SET RunningTime =DATEDIFF(S,StartTime,EndTime),      
		IdlingTime=(SELECT SUM(ISNULL(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,      
		(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT),0))                   
		FROM @tblMessageForProcessingTrip  WHERE Boxid=@intBoxLoop AND BoxMsgInTypeId =9 AND OriginDateTime BETWEEN StartTime AND EndTime AND CustomProp NOT LIKE '%Idling:0;%')      
        
		--UPDATE THE DETAILS TO MAIN TABLE      
		UPDATE @tblVehicles SET NoofTrips =(SELECT COUNT(TripId) FROM @tblTripDetails),      
		RunningTime=(SELECT SUM(RunningTime) FROM @tblTripDetails),      
		IdlingTime=(SELECT SUM(IdlingTime) FROM @tblTripDetails)            
		WHERE Boxid=@intBoxLoop        
           
		SELECT @intBoxLoop = MIN(Boxid) FROM @tblVehicles WHERE Boxid >@intBoxLoop       
	END      
    
	--Fetching KPI Details
	DECLARE @intLoopi int = NULL
	SELECT	@intLoopi = MIN(BoxId) FROM @tblVehicles 
	
	DECLARE @vcDetailData VARCHAR(MAX) = ''
	DECLARE @tblDetailData TABLE(BoxId bigint primary key, VehicleDescription nvarchar(50),IdlingDuration nvarchar(10),IdlingPercentage numeric(18,2),
								 DistanceTraveled int,SpeedViolations int, ExtremeAcceleration int, ExtremeBraking int, VehicleUtilization nvarchar(10), TemperatureHigh int)

	WHILE @intLoopi IS NOT NULL
	BEGIN
		INSERT	INTO @tblDetailData 
		SELECT	BoxId, VehicleDescription,ISNULL(IdlingTime,0),CAST(ISNULL((IdlingTime*1.00)/CASE WHEN(ISNULL(RunningTime,0)*1.00) = 0 THEN 1 
											ELSE (ISNULL(RunningTime,0)*1.00) END *100,0) AS NUMERIC(8,2)),
											CASE WHEN ISNULL(Distance,0) = 0 THEN '-' ELSE CAST(Distance AS VARCHAR) END,
				--CASE WHEN	ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END 
				--FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)),0) = 0 THEN '-' 
				--ELSE CAST((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance 
				--ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)) AS VARCHAR) END,
				SpeedViolations, ExtremeAcceleration + HarshAcceleration, ExtremeBraking + HarshBraking, DaysUtilizaed, Temperature			-- Harsh and Extreme values combined for Acceleration & Braking on 22-01-2016 by AnbarasuE
		FROM	@tblVehicles  
		WHERE	Boxid = @intLoopi
				
		SELECT	@vcDetailData = @vcDetailData + 
					(CASE @KPIID 
					WHEN 1 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(dbo.rvlf_fn_GetHHMMSSFromSec(IdlingDuration) AS VARCHAR) + ' </td><td>' + CASE WHEN (IdlingDuration/3600 < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (IdlingDuration/3600 > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">'
																																		WHEN (IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 2 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(IdlingPercentage AS VARCHAR) + ' </td><td>' + CASE	WHEN (IdlingPercentage < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (IdlingPercentage > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (IdlingPercentage BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 3 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(DistanceTraveled AS VARCHAR) + ' </td><td>' + CASE	WHEN (DistanceTraveled < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (DistanceTraveled > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (DistanceTraveled BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 4 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(SpeedViolations AS VARCHAR) + ' </td><td>' + CASE	WHEN (SpeedViolations < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (SpeedViolations > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (SpeedViolations BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 5 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeAcceleration AS VARCHAR) + ' </td><td>' + CASE	WHEN (ExtremeAcceleration < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (ExtremeAcceleration > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (ExtremeAcceleration BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 6 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeBraking AS VARCHAR) + ' </td><td>' + CASE	WHEN (ExtremeBraking < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (ExtremeBraking > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (ExtremeBraking BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 7 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(VehicleUtilization AS VARCHAR)+ ' </td><td>'+ CASE	WHEN (VehicleUtilization < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (VehicleUtilization > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (VehicleUtilization BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 9 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,(DistanceTraveled * @CostKPIsValue)),3) + ' </td><td>' + CASE	WHEN ((DistanceTraveled * @CostKPIsValue) < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN ((DistanceTraveled * @CostKPIsValue) > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN ((DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 10 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,((IdlingDuration * @CostKPIsValue)/3600)),3) + ' </td><td>' + CASE	WHEN (((IdlingDuration * @CostKPIsValue)/3600) < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 11 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(TemperatureHigh AS VARCHAR)+ ' </td><td>'+ CASE	WHEN (TemperatureHigh < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (TemperatureHigh > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">'
																																		WHEN (TemperatureHigh BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					ELSE '<tr><td colspan="3">No data found.</td></tr>'
					END)
		FROM	@tblDetailData  
		WHERE	BoxId = @intLoopi
		
		SELECT @intLoopi = MIN(BoxId) FROM @tblVehicles WHERE Boxid > @intLoopi
	END

	--Fetching KPI Summary
	DECLARE @totIdlingTime			INT = NULL      
	DECLARE @totIdlingPercent		NUMERIC(18,2) = NULL
	DECLARE @totDistanceTraveled	INT = NULL      
	DECLARE @totDaysUtilized		INT = NULL
	DECLARE @totTemperatureHigh		INT = NULL

	SELECT	@totIdlingTime		= SUM(CAST(IdlingDuration AS INT)),
			@totIdlingPercent	= CEILING(AVG(IdlingPercentage)),
			@totDistanceTraveled= SUM(ISNULL(DistanceTraveled,0)),
			@totDaysUtilized	= CAST(ROUND(AVG(CAST(VehicleUtilization AS NUMERIC(18,2))),0)AS INT),
			@totTemperatureHigh = SUM(CAST(TemperatureHigh AS INT))
	FROM	@tblDetailData

	-- Fetching KPI Chart data
	DECLARE @intSafe		VARCHAR(5) = NULL
	DECLARE @intWarning		VARCHAR(5) = NULL
	DECLARE @intCritical	VARCHAR(5) = NULL

	
	-- Template replacing with KPI values based on KPI Type
	IF (@KPIID = 1) 
	BEGIN
		--SELECT	@CurrValue = (SUM(msg.duration)), @CurrValueFormatted = (dbo.rvlf_fn_GetTimeFromSeconds(SUM(msg.duration))) --CAST(dbo.rvlf_fn_GetParamValueWithIndex(msg.CustomProp,'Idling:',';') AS bigint)))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) --AND msg.BoxMsgInTypeId = 9 --AND CHARINDEX('Idling',CustomProp,0)>0
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		SELECT	@CurrValue = @totIdlingTime/3600, @CurrValueFormatted = dbo.rvlf_fn_GetHHMMSSFromSec(@totIdlingTime)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical= COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 < @MinRange 
		SELECT	@intSafe  = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 > @MaxRange
	END
	ELSE IF (@KPIID = 2) 
	BEGIN	
		SELECT	@CurrValue = @totIdlingPercent, @CurrValueFormatted = @totIdlingPercent
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage > @MaxRange
	END
	ELSE IF (@KPIID = 3) 
	BEGIN	
		--SELECT	@CurrValue = (MAX(msg.odometer)-MIN(msg.odometer))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) AND msg.OriginDateTime Between @dtFDate and @dtEDate
		--GROUP BY msg.BoxId
		SELECT	@CurrValue = @totDistanceTraveled, @CurrValueFormatted = @totDistanceTraveled
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled > @MaxRange
	END
	ELSE IF (@KPIID = 4) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=4 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(SpeedViolations),0), @CurrValueFormatted = ISNULL(SUM(SpeedViolations),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations > @MaxRange
	END
	ELSE IF (@KPIID = 5) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=15 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeAcceleration),0), @CurrValueFormatted = ISNULL(SUM(ExtremeAcceleration),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration > @MaxRange
	END
	ELSE IF (@KPIID = 6) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=17 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeBraking),0), @CurrValueFormatted = ISNULL(SUM(ExtremeBraking),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking > @MaxRange
	END
	ELSE IF (@KPIID = 7) 
	BEGIN
		SELECT	@CurrValue = @totDaysUtilized, @CurrValueFormatted = @totDaysUtilized
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization > @MaxRange
		--SELECT	@CurrValue = COUNT(*) FROM rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) 
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		--AND		msg.BoxMsgInTypeId = 1
		--Group By msg.BoxId
	END		
	ELSE IF(@KPIID = 9)
	BEGIN 
		SELECT	@CurrValue = (@totDistanceTraveled * @CostKPIsValue), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,(@totDistanceTraveled * @CostKPIsValue)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) > @MaxRange
	END
	ELSE IF(@KPIID = 10)
	BEGIN 
		SELECT	@CurrValue = ((@totIdlingTime * @CostKPIsValue)/3600), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,((@totIdlingTime * @CostKPIsValue)/3600)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange
	END	
	ELSE IF(@KPIID = 11)
	BEGIN 
		SELECT	@CurrValue = @totTemperatureHigh, @CurrValueFormatted = @totTemperatureHigh
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh > @MaxRange
	END
	ELSE 
	BEGIN
		SELECT @CurrValueFormatted = '15' 
	END
	
	SELECT	@UnitName = CurrencyName FROM rvlfCurrencyType CT
	INNER	JOIN rvlfOrganization O ON CT.CurrencyTypeId = O.CurrencyTypeId
	WHERE	OrganizationId = @bigOrganizationID	and @KPIID in (9,10)

	-- Add the T-SQL statements to compute the return value here
	SET	@Template	= REPLACE(@Template ,'$ChartScript$', 'google.setOnLoadCallback(drawChart_$Sno$);function drawChart_$Sno$() {
										var data = new google.visualization.arrayToDataTable([[''Bands'', ''No.of.Vehicles'', { role: ''style'' }],[''Safe'', '+ ISNULL(@intSafe,0) +', ''#04B713''],[''Warning'', '+ ISNULL(@intWarning,0) +', ''#FF7F00''],[''Critical'', '+ ISNULL(@intCritical,0) +', ''#FE0000''],]);
										var options = {width: 500,height: 400,colors: [''Red''],chartArea: { width: ''50%'' },hAxis: {title: ''KPI Status'',minValue: 0},vAxis: {title: ''No.of.Vehicles'',maxValue: 16,format: ''0'',gridlines: { count: 6 },minorGridlines: { count: 3 }}, legend: { position: "none" }};
										var chart = new google.visualization.ColumnChart(document.getElementById(''chart_div_$Sno$''));chart.draw(data, options);}')
	SET	@Template	= REPLACE(@Template ,'$Sno$', @Sno)
	SET	@Template	= REPLACE(@Template ,'$gridData$', '<thead><th>Vehicle</th><th>$KPICaption$</th><th>Status</th></thead><tbody>'+ @vcDetailData +'</tbody>')
	SET	@Template	= REPLACE(@Template ,'$AssignmentID$', @AssignmentID)
	SET	@Template	= REPLACE(@Template ,'$KPIUnitName$', @UnitName)

	DECLARE @KPIStatus nvarchar(10)
	SET @KPIStatus = CASE WHEN (@CurrValue < @MinRange) THEN 'critical' WHEN (@CurrValue > @MaxRange) THEN 'safe' WHEN (@CurrValue between @MinRange and @MaxRange) THEN 'warning' ELSE 'safe' END
	
	SET	@Template	= REPLACE(@Template ,'$TileImgName$', 'img-' + @KPIStatus + '-kpi')
	SET	@Template	= REPLACE(@Template ,'$KPIValue$', @CurrValueFormatted)
	--SET	@Template	= REPLACE(@Template ,'$PnlTableClass2$', @KPIStatus)
	SET	@Template	= REPLACE(@Template ,'$PnlTableClass1$', CASE @DisplayTypeID WHEN 1  THEN 'tiletable' WHEN 2 THEN 'gaugetable' WHEN 3 THEN 'progresstable' WHEN 4 THEN 'tiletable' WHEN 5 THEN 'gridtable' END)
	SET	@Template	= REPLACE(@Template ,'$PanelClass$', CASE @DisplayTypeID WHEN 1 THEN 'tilediv' WHEN 2 THEN 'gaugediv' WHEN 3 THEN 'progressdiv' WHEN 4 THEN 'chartsdiv' WHEN 5 THEN 'griddiv' END)
	
	DECLARE @CustomTitleLen int 
	SET @CustomTitleLen = CASE @DisplayTypeID WHEN 1 THEN 25 ELSE 55 END 
	SET	@Template	= REPLACE(@Template ,'$CustomTitle$', CASE WHEN LEN(@CustomTitle) > @CustomTitleLen THEN SUBSTRING(@CustomTitle, 0, @CustomTitleLen) + '...' ELSE @CustomTitle END)
	SET	@Template	= REPLACE(@Template ,'$Tooltip$', @CustomTitle)
	SET	@Template	= REPLACE(@Template ,'$dataSize-y$', CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 3 THEN 2 WHEN 4 THEN 3 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataSize-x$', CASE @DisplayTypeID WHEN 1 THEN 2 WHEN 2 THEN 2 WHEN 3 THEN 2 WHEN 4 THEN 4 WHEN 5 THEN 4 END)
	SET	@Template	= REPLACE(@Template ,'$dataRows$', CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 3 THEN 3 WHEN 4 THEN 4 WHEN 5 THEN 5 END)  --CASE @Sno WHEN 1 THEN 1 WHEN 1 THEN 1 WHEN 3 THEN 1 WHEN 4 THEN 1 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataCols$', CASE WHEN @Sno < 5 THEN @Sno ELSE 4 END)
	SET	@Template	= REPLACE(@Template ,'$KPICaption$', /*LOWER(@KPIName) + */ 'Value(' + @UnitName + ')')
	SET @Template	= REPLACE(@Template, '$TitleColor$', 'style="background-color: ' + CASE WHEN @TitleClrCode IS NOT NULL THEN '#457DC7' ELSE @TitleClrCode END + '"')

	DECLARE @FleetName nvarchar(250)
	SET @FleetName	= (SELECT FleetName FROM rvlfFleet WHERE FleetId = @FleetId)
	SET	@Template	= REPLACE(@Template ,'$Fleet$', @FleetName)

	--DECLARE @Vehicles Table(VehicleId bigint, VehicleDescription nvarchar(50))
	--INSERT INTO @Vehicles 
	--SELECT v.VehicleId,v.VehicleDescription FROM rvlfVehicle v 
	--INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId 
	--WHERE va.BoxId IN (SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI]	(@BoxId,','))

	--DECLARE @minVehicleId bigint
	--SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles
	--DECLARE @VehicleName nvarchar(1000)

	--WHILE @minVehicleId IS NOT NULL
	--BEGIN
	--	IF @VehicleName IS NOT NULL
	--	BEGIN
	--		SET @VehicleName = @VehicleName + ',' + (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	ELSE
	--	BEGIN
	--		SET @VehicleName = (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles WHERE VehicleId > @minVehicleId
	--END

	SET	@Template	= REPLACE(@Template ,'$Vehicles$',	CASE @BoxId	WHEN '0' THEN 'All' 
														ELSE STUFF((SELECT ', ' + VehicleDescription FROM @BoxIds FOR XML PATH('')), 1, 1, '') END)
	SET	@Template	= REPLACE(@Template ,'$RefreshFreq$', CAST(@RefFreq AS VARCHAR(5)) + ' Sec')
	SET	@Template	= REPLACE(@Template ,'$Duration$', 'Last ' + CASE	WHEN @Duration = 168	THEN ' 1 Week'
																		WHEN @Duration Between 48 and 168	THEN CAST(@Duration/24 AS Varchar(20)) + ' Days' 
																		ELSE CAST(@Duration AS Varchar(20)) + ' Hours' END)
	
	
	SET	@Template	= REPLACE(@Template ,'$Range$', ((CASE	WHEN @KPIID IN (9,10) THEN (CONVERT(VARCHAR,CONVERT(MONEY,@MinRange),3) + ' to ' + CONVERT(VARCHAR,CONVERT(MONEY,@MaxRange),3))
															ELSE (CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20))) END)  
															+ ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END))

	--SET	@Template	= REPLACE(@Template ,'$Range$', CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20)) + ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END)
	SET @Template	= @Template + '<input type="hidden" value="KPIStatus:' + @KPIStatus + '">'
		
	-- Return the result of the function	
	SET	@ChangedTemplate = @Template
	RETURN @ChangedTemplate
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplateReversed_PhoneGap]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Anbarasue
-- Create date: 21-01-2016
-- Description:	
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplateReversed_PhoneGap]
(
	-- Add the parameters for the function here
	@Sno				int,
	@Template			nvarchar(MAX),
	@TitleClrCode		nvarchar(10),
	@AssignmentID		int,
	@CustomTitle		nvarchar(75),
	@KPIID				int,
	@KPIName			nvarchar(75),
	@DisplayTypeID		tinyint,
	@CostKPIsValue		decimal(18,2),
	@UnitName			nvarchar(10),
	@MinRange			int,
	@MaxRange			int,
	@FleetId			int,
	@BoxId				nvarchar(1000),
	@RefFreq			int,
	@Duration			int,
	@bigUserId			bigint,
	@bigOrganizationID	bigint
)				
RETURNS		nvarchar(MAX)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @BoxIds					TABLE (BOXID bigint,VehicleId INT,VehicleDescription nVarchar(150))
	DECLARE @ChangedTemplate		nvarchar(MAX)
	DECLARE @CurrValue				int
	DECLARE @CurrValueFormatted		nvarchar(50)
	DECLARE @intBoxID				int
	DECLARE @dtStartDate			datetime = NULL  
 	DECLARE @dtEndDate				datetime = NULL

	SET @dtStartDate = DATEADD(Hour,-@Duration,GETUTCDATE())
	SET @dtEndDate = GETUTCDATE()
	
	INSERT	INTO @BoxIds (BOXID,VehicleId,VehicleDescription)
	SELECT	va.BoxID,v.VehicleId,v.VehicleDescription FROM rvlfVehicleAssignment va
	INNER	JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
	INNER	JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
	WHERE	fv.FleetId = @FleetId AND (@BoxId IS NULL OR @BoxId = '0' OR @BoxId = '' or
    BoxId	in (select * from rvlf_fn_ConvertArrayToTable(@BoxId,','))) AND V.OrganizationId = @bigOrganizationID
    ORDER	BY BoxId
	
	--SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@BoxId,',')
		 
	DECLARE @Lang varchar(50)       
	SELECT @Lang=isnull(Lang,'LanguageEn') FROM rvlfUserPreferences WHERE UserId = @bigUserId

    DECLARE @DefaultDateFormat INT = 0     
	SELECT  @DefaultDateFormat=(CASE WHEN  isnull(up.DefaultDateFormat,0)= 0 THEN 106 ELSE up.DefaultDateFormat END)      
	FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId      
        
        
	IF @FleetId IS NULL      
	BEGIN      
		SELECT @FleetId=FleetID FROM rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1      
	END      
	DECLARE @HoursToBeAdded INT = 0      
	DECLARE @MinsToBeAdded INT = 0      
	DECLARE @ConversionFactor NUMERIC (10,2) = 1.0      
	DECLARE @DistanceCaptionPrefix VARCHAR(15)      
	DECLARE @SpeedCaptionPrefix VARCHAR(15)      
	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
			@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,        
			@DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Kms)' END,      
			@SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END      
	FROM	rvlfUserPreferences up 
	INNER	JOIN rvlfTimeZones tz ON	up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId          
          
	--SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))      
	--SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                 
    
	DECLARE @dtFDate DATETIME = @dtStartDate    
	DECLARE @dtEDate DATETIME = @dtEndDate
	  
	DECLARE @tblVehicles TABLE      
	(
		VehicleId bigint,
		VehicleDescription nvarchar(50),
		LicensePlate varchar(50),
		Vin varchar(50),
		Boxid bigint,
		NoofTrips int,
		Distance int,
		RunningTime INT,
		IdlingTime INT,
		DaysUtilizaed varchar(30),
		FleetName varchar(50),
		SpeedViolations		int,
		HarshAcceleration	int,
		ExtremeAcceleration	int,
		HarshBraking		int,
		ExtremeBraking		int
	)
      
	DECLARE @tblMessageForProcessingTrip TABLE (      
		[ProcessorID] [bigint] identity(1,1) NOT NULL,
		[Boxid] [int] NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[IgnitionStatus] [bit] NULL,
		[CustomProp] [varchar](600) NULL,
		[TripId] [bigint] NULL
	)      

	INSERT	INTO @tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin,FleetName)      
	SELECT	VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin,f.FleetName  
	FROM	rvlfBoxId BI
	INNER	JOIN rvlfVehicleAssignment VA ON BI.BoxId=VA.BoxId       
	INNER	JOIN rvlfFleetVehicles FV ON FV.VehicleId =VA.VehicleId       
	INNER	JOIN rvlfFleet F ON FV.FleetId=F.FleetId       
	INNER	JOIN rvlfVehicle V ON FV.VehicleId=V.VehicleId       
	INNER	JOIN rvlfOrganization O ON O.OrganizationId =F.OrganizationId       
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR V.OrganizationId =@bigOrganizationID AND F.OrganizationId =@bigOrganizationID)      
	AND		(@FleetId IS NULL OR @FleetId='' OR F.FleetId=@FleetId)      
	AND		VA.BoxId IN (SELECT BOXID FROM @BoxIds)      
	ORDER	BY BI.BOXID             

	--GET THE TRIPS      
	DECLARE @tblTrips TABLE      
	(      
		ProcessId bigint identity(1,1),      
		Boxid int null,        
		TripTime datetime null,      
		TripStatus varchar(10)null      
	)       
       
	--GET THE TRIP DETAILS      
	DECLARE @tblTripDetails TABLE      
	(        
		TripId bigint identity(1,1),      
		Boxid int null,        
		StartTime datetime null,      
		EndTime datetime null,      
		TripInStatus varchar(5) null,      
		TripOutStatus varchar(5) null,      
		RunningTime int null,      
		IdlingTime int null       
	)        
      
	DECLARE @intBoxLoop int =(SELECT MIN(Boxid) FROM @tblVehicles)      
      
	WHILE @intBoxLoop IS NOT NULL      
	BEGIN       
		DELETE FROM @tblMessageForProcessingTrip        
		INSERT INTO @tblMessageForProcessingTrip(Boxid,OriginDateTime,BoxMsgInTypeId,IgnitionStatus,CustomProp)      
		SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,      
		CAST(SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,h.CustomProp             
		FROM rvlfMsgInHst h       
		INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                    
		WHERE m.OperationTypeID IN (SELECT p.OperationID  FROM rvlfPackageOperations p WHERE p.PackageId =       
		(SELECT op.PackageId FROM rvlfOrganizationPackage op WHERE op.OrganizationID = @bigOrganizationID      
		AND op.IsActive=1)      
		AND p.ModuleID = 26) and m.OperationTypeID IS NOT NULL                      
		AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
		AND h.BoxID = @intBoxLoop      
		ORDER BY h.origindatetime ASC        
          
		--CALCULATE THE DISTANCE
		UPDATE @tblVehicles SET Distance = (SELECT CEILING((MAX(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,1))) -      
				(CHARINDEX('Odometer=',CustomProp,1)+9)),0) AS BIGINT)) - MIN(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,      
				CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9)),0)AS BIGINT))) * @ConversionFactor)  AS DISTANCE      
				FROM @tblMessageForProcessingTrip M         
				WHERE  (M.BoxId= @intBoxLoop)      
				AND (M.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)      
				AND CustomProp LIKE '%Odometer%' AND BoxMsgInTypeId in(2,3)),
				SpeedViolations = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 4) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 14) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 15) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 16) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 17) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate))
		WHERE Boxid =@intBoxLoop AND Distance IS NULL      
        
		--CALCULATE THE UTILIZED DAYS
		UPDATE @tblVehicles SET DaysUtilizaed =(SELECT CASE WHEN COUNT(Actions)>CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) THEN CAST(COUNT(Actions)-1 as varchar) ELSE CAST(COUNT(Actions) as varchar) END  
												--+ ' out of '+CAST( CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) AS VARCHAR) 
												FROM (SELECT COUNT(BoxId) AS Actions       
		FROM @tblMessageForProcessingTrip        
		WHERE BoxId=@intBoxLoop AND    
		(OriginDateTime BETWEEN  dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtStartDate) AND dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtEndDate))    
		--(OriginDateTime BETWEEN DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtStartDate)) AND DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEndDate)))    
		AND BoxMsgInTypeId IN (2,3)      
		GROUP BY CONVERT(DATE,OriginDateTime))AS A)      
		WHERE Boxid =@intBoxLoop AND DaysUtilizaed IS NULL      
        
		--CALCULATE THE NOOFTRIPS,RUNNING TIME AND IDLING TIME
		DELETE FROM @tblTrips       
		DELETE FROM @tblTripDetails       
		INSERT INTO @tblTrips (Boxid,TripTime,TripStatus)      
		SELECT BoxId,OriginDateTime,CASE WHEN BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'START'       
		WHEN BoxMsgInTypeId =3 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'STOP' ELSE NULL END          
		FROM rvlfMsgInHst       
		WHERE Boxid =@intBoxLoop      
		AND BoxMsgInTypeId IN(2,3)                
		AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate        
		ORDER BY BoxId,OriginDateTime       
          
		INSERT INTO @tblTripDetails (Boxid,EndTime,TripOutStatus,StartTime,TripInStatus)      
		SELECT MT.Boxid,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus      
		FROM @tblTrips AS MT       
		LEFT OUTER JOIN @tblTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'START'       
         
		--DELETE THE INVALID TRIPS      
		DELETE FROM @tblTripDetails WHERE StartTime IS NULL OR TripInStatus=TripOutStatus        
         
		--CALCULATE THE RUNNING TIME AND IDLING TIME       
		UPDATE @tblTripDetails SET RunningTime =DATEDIFF(S,StartTime,EndTime),      
		IdlingTime=(SELECT SUM(ISNULL(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,      
		(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT),0))                   
		FROM @tblMessageForProcessingTrip  WHERE Boxid=@intBoxLoop AND BoxMsgInTypeId =9 AND OriginDateTime BETWEEN StartTime AND EndTime AND CustomProp NOT LIKE '%Idling:0;%')      
        
		--UPDATE THE DETAILS TO MAIN TABLE      
		UPDATE @tblVehicles SET NoofTrips =(SELECT COUNT(TripId) FROM @tblTripDetails),      
		RunningTime=(SELECT SUM(RunningTime) FROM @tblTripDetails),      
		IdlingTime=(SELECT SUM(IdlingTime) FROM @tblTripDetails)            
		WHERE Boxid=@intBoxLoop        
           
		SELECT @intBoxLoop = MIN(Boxid) FROM @tblVehicles WHERE Boxid >@intBoxLoop       
	END      
    
	--Fetching KPI Details
	DECLARE @intLoopi int = NULL
	SELECT	@intLoopi = MIN(BoxId) FROM @tblVehicles 
	
	DECLARE @vcDetailData VARCHAR(MAX) = ''
	DECLARE @tblDetailData TABLE(BoxId bigint primary key, VehicleDescription nvarchar(50),IdlingDuration nvarchar(10),IdlingPercentage numeric(18,2),
								 DistanceTraveled int,SpeedViolations int, ExtremeAcceleration int, ExtremeBraking int, VehicleUtilization nvarchar(10))

	WHILE @intLoopi IS NOT NULL
	BEGIN
		INSERT	INTO @tblDetailData 
		SELECT	BoxId, VehicleDescription,ISNULL(IdlingTime,0),CAST(ISNULL((IdlingTime*1.00)/CASE WHEN(ISNULL(RunningTime,0)*1.00) = 0 THEN 1 
											ELSE (ISNULL(RunningTime,0)*1.00) END *100,0) AS NUMERIC(8,2)),
											CASE WHEN ISNULL(Distance,0) = 0 THEN '-' ELSE CAST(Distance AS VARCHAR) END,
				--CASE WHEN	ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END 
				--FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)),0) = 0 THEN '-' 
				--ELSE CAST((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance 
				--ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)) AS VARCHAR) END,
				SpeedViolations, ExtremeAcceleration + HarshAcceleration, ExtremeBraking + HarshBraking, DaysUtilizaed			-- Harsh and Extreme values combined for Acceleration & Braking on 22-01-2016 by AnbarasuE
		FROM	@tblVehicles  
		WHERE	Boxid = @intLoopi
				
		SELECT	@vcDetailData = @vcDetailData + 
					(CASE @KPIID 
					WHEN 1 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(dbo.rvlf_fn_GetHHMMSSFromSec(IdlingDuration) AS VARCHAR) + ' </td><td>' + CASE WHEN (IdlingDuration/3600 < @MinRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (IdlingDuration/3600 > @MaxRange) THEN '<img src="images/kpi/1_.png" title="Safe">'
																																		WHEN (IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 2 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(IdlingPercentage AS VARCHAR) + ' </td><td>' + CASE	WHEN (IdlingPercentage < @MinRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (IdlingPercentage > @MaxRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (IdlingPercentage BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 3 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(DistanceTraveled AS VARCHAR) + ' </td><td>' + CASE	WHEN (DistanceTraveled < @MinRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (DistanceTraveled > @MaxRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (DistanceTraveled BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 4 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(SpeedViolations AS VARCHAR) + ' </td><td>' + CASE	WHEN (SpeedViolations < @MinRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (SpeedViolations > @MaxRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (SpeedViolations BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 5 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeAcceleration AS VARCHAR) + ' </td><td>' + CASE	WHEN (ExtremeAcceleration < @MinRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (ExtremeAcceleration > @MaxRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (ExtremeAcceleration BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 6 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeBraking AS VARCHAR) + ' </td><td>' + CASE	WHEN (ExtremeBraking < @MinRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (ExtremeBraking > @MaxRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (ExtremeBraking BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 7 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(VehicleUtilization AS VARCHAR)+ ' </td><td>'+ CASE	WHEN (VehicleUtilization < @MinRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (VehicleUtilization > @MaxRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (VehicleUtilization BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 9 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,(DistanceTraveled * @CostKPIsValue)),3) + ' </td><td>' + CASE	WHEN ((DistanceTraveled * @CostKPIsValue) < @MinRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN ((DistanceTraveled * @CostKPIsValue) > @MaxRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN ((DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 10 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,((IdlingDuration * @CostKPIsValue)/3600)),3) + ' </td><td>' + CASE	WHEN (((IdlingDuration * @CostKPIsValue)/3600) < @MinRange) THEN '<img src="images/kpi/fuellow-1_.png" title="Critical">'
																																		WHEN (((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange) THEN '<img src="images/kpi/1_.png" title="Safe">' 
																																		WHEN (((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange) THEN '<img src="images/kpi/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					ELSE '<tr><td colspan="3">No data found.</td></tr>'
					END)
		FROM	@tblDetailData  
		WHERE	BoxId = @intLoopi
		
		SELECT @intLoopi = MIN(BoxId) FROM @tblVehicles WHERE Boxid > @intLoopi
	END

	--Fetching KPI Summary
	DECLARE @totIdlingTime			INT = NULL      
	DECLARE @totIdlingPercent		NUMERIC(18,2) = NULL
	DECLARE @totDistanceTraveled	INT = NULL      
	DECLARE @totDaysUtilized		INT = NULL

	SELECT	@totIdlingTime		= SUM(CAST(IdlingDuration AS INT)),
			@totIdlingPercent	= CEILING(AVG(IdlingPercentage)),
			@totDistanceTraveled= SUM(ISNULL(DistanceTraveled,0)),
			@totDaysUtilized	= CAST(ROUND(AVG(CAST(VehicleUtilization AS NUMERIC(18,2))),0)AS INT)
	FROM	@tblDetailData

	-- Fetching KPI Chart data
	DECLARE @intSafe		VARCHAR(5) = NULL
	DECLARE @intWarning		VARCHAR(5) = NULL
	DECLARE @intCritical	VARCHAR(5) = NULL

	
	-- Template replacing with KPI values based on KPI Type
	IF (@KPIID = 1) 
	BEGIN
		--SELECT	@CurrValue = (SUM(msg.duration)), @CurrValueFormatted = (dbo.rvlf_fn_GetTimeFromSeconds(SUM(msg.duration))) --CAST(dbo.rvlf_fn_GetParamValueWithIndex(msg.CustomProp,'Idling:',';') AS bigint)))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) --AND msg.BoxMsgInTypeId = 9 --AND CHARINDEX('Idling',CustomProp,0)>0
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		SELECT	@CurrValue = @totIdlingTime/3600, @CurrValueFormatted = dbo.rvlf_fn_GetHHMMSSFromSec(@totIdlingTime)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical= COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 < @MinRange 
		SELECT	@intSafe  = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 > @MaxRange
	END
	ELSE IF (@KPIID = 2) 
	BEGIN	
		SELECT	@CurrValue = @totIdlingPercent, @CurrValueFormatted = @totIdlingPercent
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage > @MaxRange
	END
	ELSE IF (@KPIID = 3) 
	BEGIN	
		--SELECT	@CurrValue = (MAX(msg.odometer)-MIN(msg.odometer))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) AND msg.OriginDateTime Between @dtFDate and @dtEDate
		--GROUP BY msg.BoxId
		SELECT	@CurrValue = @totDistanceTraveled, @CurrValueFormatted = @totDistanceTraveled
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled > @MaxRange
	END
	ELSE IF (@KPIID = 4) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=4 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(SpeedViolations),0), @CurrValueFormatted = ISNULL(SUM(SpeedViolations),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations > @MaxRange
	END
	ELSE IF (@KPIID = 5) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=15 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeAcceleration),0), @CurrValueFormatted = ISNULL(SUM(ExtremeAcceleration),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration > @MaxRange
	END
	ELSE IF (@KPIID = 6) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=17 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeBraking),0), @CurrValueFormatted = ISNULL(SUM(ExtremeBraking),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking > @MaxRange
	END
	ELSE IF (@KPIID = 7) 
	BEGIN
		SELECT	@CurrValue = @totDaysUtilized, @CurrValueFormatted = @totDaysUtilized
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization > @MaxRange
		--SELECT	@CurrValue = COUNT(*) FROM rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) 
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		--AND		msg.BoxMsgInTypeId = 1
		--Group By msg.BoxId
	END		
	ELSE IF(@KPIID = 9)
	BEGIN 
		SELECT	@CurrValue = (@totDistanceTraveled * @CostKPIsValue), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,(@totDistanceTraveled * @CostKPIsValue)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) > @MaxRange
	END
	ELSE IF(@KPIID = 10)
	BEGIN 
		SELECT	@CurrValue = ((@totIdlingTime * @CostKPIsValue)/3600), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,((@totIdlingTime * @CostKPIsValue)/3600)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange
	END	
	ELSE 
	BEGIN
		SELECT @CurrValueFormatted = '15' 
	END
	
	SELECT	@UnitName = CurrencyName FROM rvlfCurrencyType CT
	INNER	JOIN rvlfOrganization O ON CT.CurrencyTypeId = O.CurrencyTypeId
	WHERE	OrganizationId = @bigOrganizationID	and @KPIID in (9,10)

	-- Add the T-SQL statements to compute the return value here
	SET	@Template	= REPLACE(@Template ,'$ChartScript$', 'google.setOnLoadCallback(drawChart_$Sno$);function drawChart_$Sno$() {
										var data = new google.visualization.arrayToDataTable([[''Bands'', ''No.of.Vehicles'', { role: ''style'' }],[''Safe'', '+ ISNULL(@intSafe,0) +', ''#04B713''],[''Warning'', '+ ISNULL(@intWarning,0) +', ''#FF7F00''],[''Critical'', '+ ISNULL(@intCritical,0) +', ''#FE0000''],]);
										var options = {width: 500,height: 400,colors: [''Red''],chartArea: { width: ''50%'' },hAxis: {title: ''KPI Status'',minValue: 0},vAxis: {title: ''No.of.Vehicles'',maxValue: 16,format: ''0'',gridlines: { count: 6 },minorGridlines: { count: 3 }}, legend: { position: ''none''}};
										var chart = new google.visualization.ColumnChart(document.getElementById(''chart_div_$Sno$''));chart.draw(data, options);}')
	SET	@Template	= REPLACE(@Template ,'$Sno$', @Sno)
	SET	@Template	= REPLACE(@Template ,'$gridData$', '<thead><th>Vehicle</th><th>$KPICaption$</th><th>Status</th></thead><tbody>'+ @vcDetailData +'</tbody>')
	SET	@Template	= REPLACE(@Template ,'$AssignmentID$', @AssignmentID)
	SET	@Template	= REPLACE(@Template ,'$KPIUnitName$', @UnitName)

	DECLARE @KPIStatus nvarchar(10)
	SET @KPIStatus = CASE WHEN (@CurrValue < @MinRange) THEN 'critical' WHEN (@CurrValue > @MaxRange) THEN 'safe' WHEN (@CurrValue between @MinRange and @MaxRange) THEN 'warning' ELSE 'safe' END
	
	SET	@Template	= REPLACE(@Template ,'$TileImgName$', 'img-' + @KPIStatus + '-kpi')
	SET	@Template	= REPLACE(@Template ,'$KPIValue$', @CurrValueFormatted)
	--SET	@Template	= REPLACE(@Template ,'$PnlTableClass2$', @KPIStatus)
	SET	@Template	= REPLACE(@Template ,'$PnlTableClass1$', CASE @DisplayTypeID WHEN 1  THEN 'tiletable' WHEN 2 THEN 'gaugetable' WHEN 3 THEN 'progresstable' WHEN 4 THEN 'tiletable' WHEN 5 THEN 'gridtable' END)
	SET	@Template	= REPLACE(@Template ,'$PanelClass$', CASE @DisplayTypeID WHEN 1 THEN 'tilediv' WHEN 2 THEN 'gaugediv' WHEN 3 THEN 'progressdiv' WHEN 4 THEN 'chartsdiv' WHEN 5 THEN 'griddiv' END)
	
	DECLARE @CustomTitleLen int 
	SET @CustomTitleLen = CASE @DisplayTypeID WHEN 1 THEN 25 ELSE 55 END 
	SET	@Template	= REPLACE(@Template ,'$CustomTitle$', CASE WHEN LEN(@CustomTitle) > @CustomTitleLen THEN SUBSTRING(@CustomTitle, 0, @CustomTitleLen) + '...' ELSE @CustomTitle END)
	SET	@Template	= REPLACE(@Template ,'$Tooltip$', @CustomTitle)
	SET	@Template	= REPLACE(@Template ,'$dataSize-y$', CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 3 THEN 2 WHEN 4 THEN 3 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataSize-x$', CASE @DisplayTypeID WHEN 1 THEN 2 WHEN 2 THEN 2 WHEN 3 THEN 2 WHEN 4 THEN 4 WHEN 5 THEN 4 END)
	SET	@Template	= REPLACE(@Template ,'$dataRows$', CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 3 THEN 3 WHEN 4 THEN 4 WHEN 5 THEN 5 END)  --CASE @Sno WHEN 1 THEN 1 WHEN 1 THEN 1 WHEN 3 THEN 1 WHEN 4 THEN 1 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataCols$', CASE WHEN @Sno < 5 THEN @Sno ELSE 4 END)
	SET	@Template	= REPLACE(@Template ,'$KPICaption$', /*LOWER(@KPIName) + */ 'Value(' + @UnitName + ')')
	SET @Template	= REPLACE(@Template, '$TitleColor$', 'style="background-color: ' + CASE WHEN @TitleClrCode IS NOT NULL THEN '#457DC7' ELSE @TitleClrCode END + '"')

	DECLARE @FleetName nvarchar(250)
	SET @FleetName	= (SELECT FleetName FROM rvlfFleet WHERE FleetId = @FleetId)
	SET	@Template	= REPLACE(@Template ,'$Fleet$', @FleetName)

	--DECLARE @Vehicles Table(VehicleId bigint, VehicleDescription nvarchar(50))
	--INSERT INTO @Vehicles 
	--SELECT v.VehicleId,v.VehicleDescription FROM rvlfVehicle v 
	--INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId 
	--WHERE va.BoxId IN (SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI]	(@BoxId,','))

	--DECLARE @minVehicleId bigint
	--SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles
	--DECLARE @VehicleName nvarchar(1000)

	--WHILE @minVehicleId IS NOT NULL
	--BEGIN
	--	IF @VehicleName IS NOT NULL
	--	BEGIN
	--		SET @VehicleName = @VehicleName + ',' + (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	ELSE
	--	BEGIN
	--		SET @VehicleName = (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles WHERE VehicleId > @minVehicleId
	--END

	SET	@Template	= REPLACE(@Template ,'$Vehicles$',	CASE @BoxId	WHEN '0' THEN 'All' 
														ELSE STUFF((SELECT ', ' + VehicleDescription FROM @BoxIds FOR XML PATH('')), 1, 1, '') END)
	SET	@Template	= REPLACE(@Template ,'$RefreshFreq$', CAST(@RefFreq AS VARCHAR(5)) + ' Sec')
	SET	@Template	= REPLACE(@Template ,'$Duration$', 'Last ' + CASE	WHEN @Duration = 168	THEN ' 1 Week'
																		WHEN @Duration Between 48 and 168	THEN CAST(@Duration/24 AS Varchar(20)) + ' Days' 
																		ELSE CAST(@Duration AS Varchar(20)) + ' Hours' END)
	
	
	SET	@Template	= REPLACE(@Template ,'$Range$', ((CASE	WHEN @KPIID IN (9,10) THEN (CONVERT(VARCHAR,CONVERT(MONEY,@MinRange),3) + ' to ' + CONVERT(VARCHAR,CONVERT(MONEY,@MaxRange),3))
															ELSE (CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20))) END)  
															+ ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END))

	--SET	@Template	= REPLACE(@Template ,'$Range$', CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20)) + ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END)
	SET @Template	= @Template 
		
	-- Return the result of the function	
	SET	@ChangedTemplate = @Template + 'Safe#' + @intSafe + ';Warning#' +  @intWarning +';Critical#' + @intCritical + ';'

	RETURN @ChangedTemplate
END


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplateReversed_Responsive]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasue
-- Create date: 30-09-2016
-- Description:	For RWD KPIs 
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplateReversed_Responsive]
(
	-- Add the parameters for the function here
	@Sno				int,
	@Template			nvarchar(MAX),
	@TitleClrCode		nvarchar(10),
	@AssignmentID		int,
	@CustomTitle		nvarchar(75),
	@KPIID				int,
	@KPIName			nvarchar(75),
	@DisplayTypeID		tinyint,
	@CostKPIsValue		decimal(18,2),
	@TemperatureType	tinyint,
	@UnitName			nvarchar(10),
	@MinRange			int,
	@MaxRange			int,
	@FleetId			int,
	@BoxId				nvarchar(1000),
	@RefFreq			int,
	@Duration			int,
	@bigUserId			bigint,
	@bigOrganizationID	bigint
)				
RETURNS		nvarchar(MAX)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @BoxIds					TABLE (BOXID bigint,VehicleId INT,VehicleDescription nVarchar(150))
	DECLARE @ChangedTemplate		nvarchar(MAX)
	DECLARE @CurrValue				int
	DECLARE @CurrValueFormatted		nvarchar(50)
	DECLARE @intBoxID				int
	DECLARE @dtStartDate			datetime = NULL  
 	DECLARE @dtEndDate				datetime = NULL

	SET @dtStartDate = DATEADD(Hour,-@Duration,GETUTCDATE())
	SET @dtEndDate = GETUTCDATE()
	
	INSERT	INTO @BoxIds (BOXID,VehicleId,VehicleDescription)
	SELECT	va.BoxID,v.VehicleId,v.VehicleDescription FROM rvlfVehicleAssignment va
	INNER	JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
	INNER	JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
	WHERE	fv.FleetId = @FleetId AND (@BoxId IS NULL OR @BoxId = '0' OR @BoxId = '' or
    BoxId	in (select * from rvlf_fn_ConvertArrayToTable(@BoxId,','))) AND V.OrganizationId = @bigOrganizationID
    ORDER	BY BoxId
	
	--SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@BoxId,',')
		 
	DECLARE @Lang varchar(50)       
	SELECT @Lang=isnull(Lang,'LanguageEn') FROM rvlfUserPreferences WHERE UserId = @bigUserId

    DECLARE @DefaultDateFormat INT = 0     
	SELECT  @DefaultDateFormat=(CASE WHEN  isnull(up.DefaultDateFormat,0)= 0 THEN 106 ELSE up.DefaultDateFormat END)      
	FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId      
        
        
	IF @FleetId IS NULL      
	BEGIN      
		SELECT @FleetId=FleetID FROM rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1      
	END      
	DECLARE @HoursToBeAdded INT = 0      
	DECLARE @MinsToBeAdded INT = 0      
	DECLARE @ConversionFactor NUMERIC (10,2) = 1.0      
	DECLARE @DistanceCaptionPrefix VARCHAR(15)      
	DECLARE @SpeedCaptionPrefix VARCHAR(15)      
	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
			@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,        
			@DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Kms)' END,      
			@SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END      
	FROM	rvlfUserPreferences up 
	INNER	JOIN rvlfTimeZones tz ON	up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId          
          
	--SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))      
	--SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                 
    
	DECLARE @dtFDate DATETIME = @dtStartDate    
	DECLARE @dtEDate DATETIME = @dtEndDate
	  
	DECLARE @tblVehicles TABLE      
	(
		VehicleId bigint,
		VehicleDescription nvarchar(50),
		LicensePlate varchar(50),
		Vin varchar(50),
		Boxid bigint,
		NoofTrips int,
		Distance int,
		RunningTime INT,
		IdlingTime INT,
		DaysUtilizaed varchar(30),
		FleetName varchar(50),
		SpeedViolations		int,
		HarshAcceleration	int,
		ExtremeAcceleration	int,
		HarshBraking		int,
		ExtremeBraking		int,
		Temperature			int
	)
      
	DECLARE @tblMessageForProcessingTrip TABLE (      
		[ProcessorID] [bigint] identity(1,1) NOT NULL,
		[Boxid] [int] NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[IgnitionStatus] [bit] NULL,
		[CustomProp] [varchar](600) NULL,
		[TripId] [bigint] NULL
	)      

	INSERT	INTO @tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin,FleetName)      
	SELECT	VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin,f.FleetName  
	FROM	rvlfBoxId BI
	INNER	JOIN rvlfVehicleAssignment VA ON BI.BoxId=VA.BoxId       
	INNER	JOIN rvlfFleetVehicles FV ON FV.VehicleId =VA.VehicleId       
	INNER	JOIN rvlfFleet F ON FV.FleetId=F.FleetId       
	INNER	JOIN rvlfVehicle V ON FV.VehicleId=V.VehicleId       
	INNER	JOIN rvlfOrganization O ON O.OrganizationId =F.OrganizationId       
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR V.OrganizationId =@bigOrganizationID AND F.OrganizationId =@bigOrganizationID)      
	AND		(@FleetId IS NULL OR @FleetId='' OR F.FleetId=@FleetId)      
	AND		VA.BoxId IN (SELECT BOXID FROM @BoxIds)      
	ORDER	BY BI.BOXID             

	--GET THE TRIPS      
	DECLARE @tblTrips TABLE      
	(      
		ProcessId bigint identity(1,1),      
		Boxid int null,        
		TripTime datetime null,      
		TripStatus varchar(10)null      
	)       
       
	--GET THE TRIP DETAILS      
	DECLARE @tblTripDetails TABLE      
	(        
		TripId bigint identity(1,1),      
		Boxid int null,        
		StartTime datetime null,      
		EndTime datetime null,      
		TripInStatus varchar(5) null,      
		TripOutStatus varchar(5) null,      
		RunningTime int null,      
		IdlingTime int null       
	)        
      
	DECLARE @intBoxLoop int =(SELECT MIN(Boxid) FROM @tblVehicles)      
      
	WHILE @intBoxLoop IS NOT NULL      
	BEGIN       
		DELETE FROM @tblMessageForProcessingTrip        
		INSERT INTO @tblMessageForProcessingTrip(Boxid,OriginDateTime,BoxMsgInTypeId,IgnitionStatus,CustomProp)      
		SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,      
		CAST(SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,h.CustomProp             
		FROM rvlfMsgInHst h       
		INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                    
		WHERE m.OperationTypeID IN (SELECT p.OperationID  FROM rvlfPackageOperations p WHERE p.PackageId =       
		(SELECT op.PackageId FROM rvlfOrganizationPackage op WHERE op.OrganizationID = @bigOrganizationID      
		AND op.IsActive=1)      
		AND p.ModuleID = 26) and m.OperationTypeID IS NOT NULL                      
		AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
		AND h.BoxID = @intBoxLoop      
		ORDER BY h.origindatetime ASC        
          
		--CALCULATE THE DISTANCE
		UPDATE @tblVehicles SET Distance = (SELECT CEILING((MAX(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,1))) -      
				(CHARINDEX('Odometer=',CustomProp,1)+9)),0) AS BIGINT)) - MIN(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,      
				CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9)),0)AS BIGINT))) * @ConversionFactor)  AS DISTANCE      
				FROM @tblMessageForProcessingTrip M         
				WHERE  (M.BoxId= @intBoxLoop)      
				AND (M.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)      
				AND CustomProp LIKE '%Odometer%' AND BoxMsgInTypeId in(2,3)),
				SpeedViolations = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 4) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 14) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 15) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 16) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 17) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				Temperature = (SELECT COUNT(BoxMsgInTypeId) from @tblMessageForProcessingTrip where BoxId = @intBoxLoop and BoxMsgInTypeId = (CASE @TemperatureType WHEN 1 THEN 82 WHEN 2 THEN 86 WHEN 3 THEN 166 WHEN 4 THEN 171 ELSE 0 END))
		WHERE Boxid =@intBoxLoop AND Distance IS NULL      
        
		--CALCULATE THE UTILIZED DAYS
		UPDATE @tblVehicles SET DaysUtilizaed =(SELECT CASE WHEN COUNT(Actions)>CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) THEN CAST(COUNT(Actions)-1 as varchar) ELSE CAST(COUNT(Actions) as varchar) END  
												--+ ' out of '+CAST( CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) AS VARCHAR) 
												FROM (SELECT COUNT(BoxId) AS Actions       
		FROM @tblMessageForProcessingTrip        
		WHERE BoxId=@intBoxLoop AND    
		(OriginDateTime BETWEEN  dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtStartDate) AND dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtEndDate))    
		--(OriginDateTime BETWEEN DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtStartDate)) AND DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEndDate)))    
		AND BoxMsgInTypeId IN (2,3)      
		GROUP BY CONVERT(DATE,OriginDateTime))AS A)      
		WHERE Boxid =@intBoxLoop AND DaysUtilizaed IS NULL      
        
		--CALCULATE THE NOOFTRIPS,RUNNING TIME AND IDLING TIME
		DELETE FROM @tblTrips       
		DELETE FROM @tblTripDetails       
		INSERT INTO @tblTrips (Boxid,TripTime,TripStatus)      
		SELECT BoxId,OriginDateTime,CASE WHEN BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'START'       
		WHEN BoxMsgInTypeId =3 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'STOP' ELSE NULL END          
		FROM rvlfMsgInHst       
		WHERE Boxid =@intBoxLoop      
		AND BoxMsgInTypeId IN(2,3)                
		AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate        
		ORDER BY BoxId,OriginDateTime       
          
		INSERT INTO @tblTripDetails (Boxid,EndTime,TripOutStatus,StartTime,TripInStatus)      
		SELECT MT.Boxid,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus      
		FROM @tblTrips AS MT       
		LEFT OUTER JOIN @tblTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'START'       
         
		--DELETE THE INVALID TRIPS      
		DELETE FROM @tblTripDetails WHERE StartTime IS NULL OR TripInStatus=TripOutStatus        
         
		--CALCULATE THE RUNNING TIME AND IDLING TIME       
		UPDATE @tblTripDetails SET RunningTime =DATEDIFF(S,StartTime,EndTime),      
		IdlingTime=(SELECT SUM(ISNULL(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,      
		(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT),0))                   
		FROM @tblMessageForProcessingTrip  WHERE Boxid=@intBoxLoop AND BoxMsgInTypeId =9 AND OriginDateTime BETWEEN StartTime AND EndTime AND CustomProp NOT LIKE '%Idling:0;%')      
        
		--UPDATE THE DETAILS TO MAIN TABLE      
		UPDATE @tblVehicles SET NoofTrips =(SELECT COUNT(TripId) FROM @tblTripDetails),      
		RunningTime=(SELECT SUM(RunningTime) FROM @tblTripDetails),      
		IdlingTime=(SELECT SUM(IdlingTime) FROM @tblTripDetails)            
		WHERE Boxid=@intBoxLoop        
           
		SELECT @intBoxLoop = MIN(Boxid) FROM @tblVehicles WHERE Boxid >@intBoxLoop       
	END      
    
	--Fetching KPI Details
	DECLARE @intLoopi int = NULL
	SELECT	@intLoopi = MIN(BoxId) FROM @tblVehicles 
	
	DECLARE @vcDetailData VARCHAR(MAX) = ''
	DECLARE @tblDetailData TABLE(BoxId bigint primary key, VehicleDescription nvarchar(50),IdlingDuration nvarchar(10),IdlingPercentage numeric(18,2),
								 DistanceTraveled int,SpeedViolations int, ExtremeAcceleration int, ExtremeBraking int, VehicleUtilization nvarchar(10), TemperatureHigh int)

	WHILE @intLoopi IS NOT NULL
	BEGIN
		INSERT	INTO @tblDetailData 
		SELECT	BoxId, VehicleDescription,ISNULL(IdlingTime,0),CAST(ISNULL((IdlingTime*1.00)/CASE WHEN(ISNULL(RunningTime,0)*1.00) = 0 THEN 1 
											ELSE (ISNULL(RunningTime,0)*1.00) END *100,0) AS NUMERIC(8,2)),
											CASE WHEN ISNULL(Distance,0) = 0 THEN '-' ELSE CAST(Distance AS VARCHAR) END,
				--CASE WHEN	ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END 
				--FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)),0) = 0 THEN '-' 
				--ELSE CAST((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance 
				--ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)) AS VARCHAR) END,
				SpeedViolations, ExtremeAcceleration + HarshAcceleration, ExtremeBraking + HarshBraking, DaysUtilizaed, Temperature			-- Harsh and Extreme values combined for Acceleration & Braking on 22-01-2016 by AnbarasuE
		FROM	@tblVehicles  
		WHERE	Boxid = @intLoopi
				
		SELECT	@vcDetailData = @vcDetailData + 
					(CASE @KPIID 
					WHEN 1 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(dbo.rvlf_fn_GetHHMMSSFromSec(IdlingDuration) AS VARCHAR) + ' </td><td>' + CASE WHEN (IdlingDuration/3600 < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (IdlingDuration/3600 > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">'
																																		WHEN (IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 2 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(IdlingPercentage AS VARCHAR) + ' </td><td>' + CASE	WHEN (IdlingPercentage < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (IdlingPercentage > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (IdlingPercentage BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 3 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(DistanceTraveled AS VARCHAR) + ' </td><td>' + CASE	WHEN (DistanceTraveled < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (DistanceTraveled > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (DistanceTraveled BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 4 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(SpeedViolations AS VARCHAR) + ' </td><td>' + CASE	WHEN (SpeedViolations < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (SpeedViolations > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (SpeedViolations BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 5 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeAcceleration AS VARCHAR) + ' </td><td>' + CASE	WHEN (ExtremeAcceleration < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (ExtremeAcceleration > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (ExtremeAcceleration BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 6 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeBraking AS VARCHAR) + ' </td><td>' + CASE	WHEN (ExtremeBraking < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (ExtremeBraking > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (ExtremeBraking BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 7 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(VehicleUtilization AS VARCHAR)+ ' </td><td>'+ CASE	WHEN (VehicleUtilization < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (VehicleUtilization > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (VehicleUtilization BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 9 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,(DistanceTraveled * @CostKPIsValue)),3) + ' </td><td>' + CASE	WHEN ((DistanceTraveled * @CostKPIsValue) < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN ((DistanceTraveled * @CostKPIsValue) > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN ((DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 10 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,((IdlingDuration * @CostKPIsValue)/3600)),3) + ' </td><td>' + CASE	WHEN (((IdlingDuration * @CostKPIsValue)/3600) < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 11 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(TemperatureHigh AS VARCHAR)+ ' </td><td>'+ CASE	WHEN (TemperatureHigh < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (TemperatureHigh > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">'
																																		WHEN (TemperatureHigh BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					ELSE '<tr><td colspan="3">No data found.</td></tr>'
					END)
		FROM	@tblDetailData  
		WHERE	BoxId = @intLoopi
		
		SELECT @intLoopi = MIN(BoxId) FROM @tblVehicles WHERE Boxid > @intLoopi
	END

	--Fetching KPI Summary
	DECLARE @totIdlingTime			INT = NULL      
	DECLARE @totIdlingPercent		NUMERIC(18,2) = NULL
	DECLARE @totDistanceTraveled	INT = NULL      
	DECLARE @totDaysUtilized		INT = NULL
	DECLARE @totTemperatureHigh		INT = NULL

	SELECT	@totIdlingTime		= SUM(CAST(IdlingDuration AS INT)),
			@totIdlingPercent	= CEILING(AVG(IdlingPercentage)),
			@totDistanceTraveled= SUM(ISNULL(DistanceTraveled,0)),
			@totDaysUtilized	= CAST(ROUND(AVG(CAST(VehicleUtilization AS NUMERIC(18,2))),0)AS INT),
			@totTemperatureHigh = SUM(CAST(TemperatureHigh AS INT))
	FROM	@tblDetailData

	-- Fetching KPI Chart data
	DECLARE @intSafe		VARCHAR(5) = NULL
	DECLARE @intWarning		VARCHAR(5) = NULL
	DECLARE @intCritical	VARCHAR(5) = NULL

	
	-- Template replacing with KPI values based on KPI Type
	IF (@KPIID = 1) 
	BEGIN
		--SELECT	@CurrValue = (SUM(msg.duration)), @CurrValueFormatted = (dbo.rvlf_fn_GetTimeFromSeconds(SUM(msg.duration))) --CAST(dbo.rvlf_fn_GetParamValueWithIndex(msg.CustomProp,'Idling:',';') AS bigint)))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) --AND msg.BoxMsgInTypeId = 9 --AND CHARINDEX('Idling',CustomProp,0)>0
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		SELECT	@CurrValue = @totIdlingTime/3600, @CurrValueFormatted = dbo.rvlf_fn_GetHHMMSSFromSec(@totIdlingTime)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical= COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 < @MinRange 
		SELECT	@intSafe  = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 > @MaxRange
	END
	ELSE IF (@KPIID = 2) 
	BEGIN	
		SELECT	@CurrValue = @totIdlingPercent, @CurrValueFormatted = @totIdlingPercent
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage > @MaxRange
	END
	ELSE IF (@KPIID = 3) 
	BEGIN	
		--SELECT	@CurrValue = (MAX(msg.odometer)-MIN(msg.odometer))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) AND msg.OriginDateTime Between @dtFDate and @dtEDate
		--GROUP BY msg.BoxId
		SELECT	@CurrValue = @totDistanceTraveled, @CurrValueFormatted = @totDistanceTraveled
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled > @MaxRange
	END
	ELSE IF (@KPIID = 4) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=4 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(SpeedViolations),0), @CurrValueFormatted = ISNULL(SUM(SpeedViolations),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations > @MaxRange
	END
	ELSE IF (@KPIID = 5) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=15 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeAcceleration),0), @CurrValueFormatted = ISNULL(SUM(ExtremeAcceleration),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration > @MaxRange
	END
	ELSE IF (@KPIID = 6) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=17 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeBraking),0), @CurrValueFormatted = ISNULL(SUM(ExtremeBraking),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking > @MaxRange
	END
	ELSE IF (@KPIID = 7) 
	BEGIN
		SELECT	@CurrValue = @totDaysUtilized, @CurrValueFormatted = @totDaysUtilized
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization > @MaxRange
		--SELECT	@CurrValue = COUNT(*) FROM rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) 
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		--AND		msg.BoxMsgInTypeId = 1
		--Group By msg.BoxId
	END		
	ELSE IF(@KPIID = 9)
	BEGIN 
		SELECT	@CurrValue = (@totDistanceTraveled * @CostKPIsValue), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,(@totDistanceTraveled * @CostKPIsValue)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) > @MaxRange
	END
	ELSE IF(@KPIID = 10)
	BEGIN 
		SELECT	@CurrValue = ((@totIdlingTime * @CostKPIsValue)/3600), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,((@totIdlingTime * @CostKPIsValue)/3600)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange
	END
	ELSE IF(@KPIID = 11)
	BEGIN 
		SELECT	@CurrValue = @totTemperatureHigh, @CurrValueFormatted = @totTemperatureHigh
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh > @MaxRange
	END
	ELSE 
	BEGIN
		SELECT @CurrValueFormatted = '15' 
	END
	
	SELECT	@UnitName = CurrencyName FROM rvlfCurrencyType CT
	INNER	JOIN rvlfOrganization O ON CT.CurrencyTypeId = O.CurrencyTypeId
	WHERE	OrganizationId = @bigOrganizationID	and @KPIID in (9,10)

	-- Add the T-SQL statements to compute the return value here
	SET	@Template	= REPLACE(@Template ,'$ChartScript$', 'google.setOnLoadCallback(drawChart_$Sno$);function drawChart_$Sno$() {
										var data = new google.visualization.arrayToDataTable([[''Bands'', ''No.of.Vehicles'', { role: ''style'' }],[''Safe'', '+ ISNULL(@intSafe,0) +', ''#04B713''],[''Warning'', '+ ISNULL(@intWarning,0) +', ''#FF7F00''],[''Critical'', '+ ISNULL(@intCritical,0) +', ''#FE0000''],]);
										var options = {width: 330,height: 400,colors: [''Red''],chartArea: { width: ''50%'' },hAxis: {title: ''KPI Status'',minValue: 0},vAxis: {title: ''No.of.Vehicles'',maxValue: 16,format: ''0'',gridlines: { count: 6 },minorGridlines: { count: 3 }}, legend: { position: "none" }};
										var chart = new google.visualization.ColumnChart(document.getElementById(''chart_div_$Sno$''));chart.draw(data, options);}')
	SET	@Template	= REPLACE(@Template ,'$Sno$', @Sno)
	SET	@Template	= REPLACE(@Template ,'$data-gs-id$', @AssignmentID)
	SET	@Template	= REPLACE(@Template ,'$gridData$', '<thead><th>Vehicle</th><th>$KPICaption$</th><th>Status</th></thead><tbody>'+ @vcDetailData +'</tbody>')
	SET	@Template	= REPLACE(@Template ,'$AssignmentID$', @AssignmentID)
	SET	@Template	= REPLACE(@Template ,'$KPIUnitName$', @UnitName)

	DECLARE @KPIStatus nvarchar(10)
	SET @KPIStatus = CASE WHEN (@CurrValue < @MinRange) THEN 'critical' WHEN (@CurrValue > @MaxRange) THEN 'safe' WHEN (@CurrValue between @MinRange and @MaxRange) THEN 'warning' ELSE 'safe' END
	
	SET	@Template	= REPLACE(@Template ,'$TileImgName$', 'img-' + @KPIStatus + '-kpi')
	SET	@Template	= REPLACE(@Template ,'$KPIValue$', @CurrValueFormatted)
	--SET	@Template	= REPLACE(@Template ,'$PnlTableClass2$', @KPIStatus)
	SET	@Template	= REPLACE(@Template ,'$PnlTableClass1$', CASE @DisplayTypeID WHEN 1  THEN 'tiletable' WHEN 2 THEN 'gaugetable' WHEN 3 THEN 'progresstable' WHEN 4 THEN 'tiletable' WHEN 5 THEN 'gridtable' END)
	SET	@Template	= REPLACE(@Template ,'$PanelClass$', CASE @DisplayTypeID WHEN 1 THEN 'tilediv' WHEN 2 THEN 'gaugediv' WHEN 3 THEN 'progressdiv' WHEN 4 THEN 'chartsdiv' WHEN 5 THEN 'griddiv' END)
	
	DECLARE @CustomTitleLen int 
	SET @CustomTitleLen = CASE @DisplayTypeID WHEN 1 THEN 25 ELSE 55 END 
	SET	@Template	= REPLACE(@Template ,'$CustomTitle$', CASE WHEN LEN(@CustomTitle) > @CustomTitleLen THEN SUBSTRING(@CustomTitle, 0, @CustomTitleLen) + '...' ELSE @CustomTitle END)
	SET	@Template	= REPLACE(@Template ,'$Tooltip$', @CustomTitle)
		
	DECLARE @PosX TINYINT, @PosY TINYINT
	SELECT @PosX = x, @PosY = y FROM rvlfKPIGridPosition POS
	RIGHT JOIN RVLFKPIUSERASSIGNMENT KUA ON POS.AssignmentId = KUA.ASSIGNMENTID
	WHERE KUA.AssignmentId = @AssignmentID

	SET	@Template	= REPLACE(@Template ,'$dataRows$', CASE WHEN @PosX IS NULL THEN 0 ELSE @PosX END)	--CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 3 THEN 3 WHEN 4 THEN 4 WHEN 5 THEN 5 END)  --CASE @Sno WHEN 1 THEN 1 WHEN 1 THEN 1 WHEN 3 THEN 1 WHEN 4 THEN 1 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataCols$', CASE WHEN @PosY IS NULL THEN 0 ELSE @PosY END)	--CASE WHEN @Sno < 5 THEN @Sno ELSE 4 END)

	SET	@Template	= REPLACE(@Template ,'$dataSize-y$', CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 1 WHEN 3 THEN 1 WHEN 4 THEN 3 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataSize-x$', CASE @DisplayTypeID WHEN 1 THEN 3 WHEN 2 THEN 3 WHEN 3 THEN 3 WHEN 4 THEN 4 WHEN 5 THEN 4 END)
	
	SET	@Template	= REPLACE(@Template ,'$KPICaption$', /*LOWER(@KPIName) + */ 'Value(' + @UnitName + ')')
	SET @Template	= REPLACE(@Template, '$TitleColor$', 'style="background-color: ' + CASE WHEN @TitleClrCode IS NOT NULL THEN '#457DC7' ELSE @TitleClrCode END + '"')

	DECLARE @FleetName nvarchar(250)
	SET @FleetName	= (SELECT FleetName FROM rvlfFleet WHERE FleetId = @FleetId)
	SET	@Template	= REPLACE(@Template ,'$Fleet$', @FleetName)

	--DECLARE @Vehicles Table(VehicleId bigint, VehicleDescription nvarchar(50))
	--INSERT INTO @Vehicles 
	--SELECT v.VehicleId,v.VehicleDescription FROM rvlfVehicle v 
	--INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId 
	--WHERE va.BoxId IN (SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI]	(@BoxId,','))

	--DECLARE @minVehicleId bigint
	--SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles
	--DECLARE @VehicleName nvarchar(1000)

	--WHILE @minVehicleId IS NOT NULL
	--BEGIN
	--	IF @VehicleName IS NOT NULL
	--	BEGIN
	--		SET @VehicleName = @VehicleName + ',' + (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	ELSE
	--	BEGIN
	--		SET @VehicleName = (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles WHERE VehicleId > @minVehicleId
	--END

	SET	@Template	= REPLACE(@Template ,'$Vehicles$',	CASE @BoxId	WHEN '0' THEN 'All' 
														ELSE STUFF((SELECT ', ' + VehicleDescription FROM @BoxIds FOR XML PATH('')), 1, 1, '') END)
	SET	@Template	= REPLACE(@Template ,'$RefreshFreq$', CAST(@RefFreq AS VARCHAR(5)) + ' Sec')
	SET	@Template	= REPLACE(@Template ,'$Duration$', 'Last ' + CASE	WHEN @Duration = 336	THEN ' 2 Weeks'
																		WHEN @Duration Between 168	and 336 THEN ' 1 Week'
																		WHEN @Duration Between 48	and 168	THEN CAST(@Duration/24 AS Varchar(20)) + ' Days' 
																		ELSE CAST(@Duration AS Varchar(20)) + ' Hours' END)
	
	
	SET	@Template	= REPLACE(@Template ,'$Range$', ((CASE	WHEN @KPIID IN (9,10) THEN (CONVERT(VARCHAR,CONVERT(MONEY,@MinRange),3) + ' to ' + CONVERT(VARCHAR,CONVERT(MONEY,@MaxRange),3))
															ELSE (CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20))) END)  
															+ ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END))

	--SET	@Template	= REPLACE(@Template ,'$Range$', CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20)) + ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END)
	SET @Template	= @Template + '<input type="hidden" value="KPIStatus:' + @KPIStatus + '">'
		
	-- Return the result of the function	
	SET	@ChangedTemplate = @Template
	RETURN @ChangedTemplate
END



GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplateReversed_Responsive_Test]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasue
-- Create date: 30-09-2016
-- Description:	For RWD KPIs 
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_KPIDbd_ChangeKPITemplateReversed_Responsive_Test]
(
	-- Add the parameters for the function here
	@Sno				int,
	@Template			nvarchar(MAX),
	@TitleClrCode		nvarchar(10),
	@AssignmentID		int,
	@CustomTitle		nvarchar(75),
	@KPIID				int,
	@KPIName			nvarchar(75),
	@DisplayTypeID		tinyint,
	@CostKPIsValue		decimal(18,2),
	@TemperatureType	tinyint,
	@UnitName			nvarchar(10),
	@MinRange			int,
	@MaxRange			int,
	@FleetId			int,
	@BoxId				nvarchar(1000),
	@RefFreq			int,
	@Duration			int,
	@bigUserId			bigint,
	@bigOrganizationID	bigint,
	@VehType tinyint
)				
RETURNS		nvarchar(MAX)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @BoxIds					TABLE (BOXID bigint,VehicleId INT,VehicleDescription nVarchar(150),Vehicletype Varchar(50))
	DECLARE @ChangedTemplate		nvarchar(MAX)
	DECLARE @CurrValue				int
	DECLARE @CurrValueFormatted		nvarchar(50)
	DECLARE @intBoxID				int
	DECLARE @dtStartDate			datetime = NULL  
 	DECLARE @dtEndDate				datetime = NULL

	SET @dtStartDate = DATEADD(Hour,-@Duration,GETUTCDATE())
	SET @dtEndDate = GETUTCDATE()
	
	INSERT	INTO @BoxIds (BOXID,VehicleId,VehicleDescription,Vehicletype)
	SELECT	va.BoxID,v.VehicleId,v.VehicleDescription,VT.VehicleTypeName FROM rvlfVehicleAssignment va
	INNER	JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
	Inner   Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
	INNER	JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
	INNER	JOIN rvlfVehicleType VT ON VT.VehicleTypeId = v.VehicleTypeId
	WHERE	fv.FleetId = @FleetId AND (@BoxId IS NULL OR @BoxId = '0' OR @BoxId = '' or
    va.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@BoxId,','))) AND V.OrganizationId = @bigOrganizationID AND VT.VehicleTypeId = @VehType
    ORDER	BY BoxId
	
	--SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@BoxId,',')
		 
	DECLARE @Lang varchar(50)       
	SELECT @Lang=isnull(Lang,'LanguageEn') FROM rvlfUserPreferences WHERE UserId = @bigUserId

    DECLARE @DefaultDateFormat INT = 0     
	SELECT  @DefaultDateFormat=(CASE WHEN  isnull(up.DefaultDateFormat,0)= 0 THEN 106 ELSE up.DefaultDateFormat END)      
	FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId      
        
        
	IF @FleetId IS NULL      
	BEGIN      
		SELECT @FleetId=FleetID FROM rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1      
	END      
	DECLARE @HoursToBeAdded INT = 0      
	DECLARE @MinsToBeAdded INT = 0      
	DECLARE @ConversionFactor NUMERIC (10,2) = 1.0      
	DECLARE @DistanceCaptionPrefix VARCHAR(15)      
	DECLARE @SpeedCaptionPrefix VARCHAR(15)      
	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
			@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,        
			@DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Kms)' END,      
			@SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END      
	FROM	rvlfUserPreferences up 
	INNER	JOIN rvlfTimeZones tz ON	up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId          
          
	--SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))      
	--SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                 
    
	DECLARE @dtFDate DATETIME = @dtStartDate    
	DECLARE @dtEDate DATETIME = @dtEndDate
	  
	DECLARE @tblVehicles TABLE      
	(
		VehicleId bigint,
		VehicleDescription nvarchar(50),
		LicensePlate varchar(50),
		Vin varchar(50),
		Boxid bigint,
		NoofTrips int,
		Distance int,
		RunningTime INT,
		IdlingTime INT,
		DaysUtilizaed varchar(30),
		FleetName varchar(50),
		SpeedViolations		int,
		HarshAcceleration	int,
		ExtremeAcceleration	int,
		HarshBraking		int,
		ExtremeBraking		int,
		Temperature			int
	)
      
	DECLARE @tblMessageForProcessingTrip TABLE (      
		[ProcessorID] [bigint] identity(1,1) NOT NULL,
		[Boxid] [int] NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[IgnitionStatus] [bit] NULL,
		[CustomProp] [varchar](600) NULL,
		[TripId] [bigint] NULL
	)      

	INSERT	INTO @tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin,FleetName)      
	SELECT	VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin,f.FleetName  
	FROM	rvlfBoxId BI
	INNER	JOIN rvlfVehicleAssignment VA ON BI.BoxId=VA.BoxId       
	INNER	JOIN rvlfFleetVehicles FV ON FV.VehicleId =VA.VehicleId       
	INNER	JOIN rvlfFleet F ON FV.FleetId=F.FleetId       
	INNER	JOIN rvlfVehicle V ON FV.VehicleId=V.VehicleId       
	INNER	JOIN rvlfOrganization O ON O.OrganizationId =F.OrganizationId       
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR V.OrganizationId =@bigOrganizationID AND F.OrganizationId =@bigOrganizationID)      
	AND		(@FleetId IS NULL OR @FleetId='' OR F.FleetId=@FleetId)      
	AND		VA.BoxId IN (SELECT BOXID FROM @BoxIds)      
	ORDER	BY BI.BOXID             

	--GET THE TRIPS      
	DECLARE @tblTrips TABLE      
	(      
		ProcessId bigint identity(1,1),      
		Boxid int null,        
		TripTime datetime null,      
		TripStatus varchar(10)null      
	)       
       
	--GET THE TRIP DETAILS      
	DECLARE @tblTripDetails TABLE      
	(        
		TripId bigint identity(1,1),      
		Boxid int null,        
		StartTime datetime null,      
		EndTime datetime null,      
		TripInStatus varchar(5) null,      
		TripOutStatus varchar(5) null,      
		RunningTime int null,      
		IdlingTime int null       
	)        
      
	DECLARE @intBoxLoop int =(SELECT MIN(Boxid) FROM @tblVehicles)      
      
	WHILE @intBoxLoop IS NOT NULL      
	BEGIN       
		DELETE FROM @tblMessageForProcessingTrip        
		INSERT INTO @tblMessageForProcessingTrip(Boxid,OriginDateTime,BoxMsgInTypeId,IgnitionStatus,CustomProp)      
		SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,      
		CAST(SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,h.CustomProp             
		FROM rvlfMsgInHst h       
		INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                    
		WHERE m.OperationTypeID IN (SELECT p.OperationID  FROM rvlfPackageOperations p WHERE p.PackageId =       
		(SELECT op.PackageId FROM rvlfOrganizationPackage op WHERE op.OrganizationID = @bigOrganizationID      
		AND op.IsActive=1)      
		AND p.ModuleID = 26) and m.OperationTypeID IS NOT NULL                      
		AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
		AND h.BoxID = @intBoxLoop      
		ORDER BY h.origindatetime ASC        
          
		--CALCULATE THE DISTANCE
		UPDATE @tblVehicles SET Distance = (SELECT CEILING((MAX(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,1))) -      
				(CHARINDEX('Odometer=',CustomProp,1)+9)),0) AS BIGINT)) - MIN(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,      
				CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9)),0)AS BIGINT))) * @ConversionFactor)  AS DISTANCE      
				FROM @tblMessageForProcessingTrip M         
				WHERE  (M.BoxId= @intBoxLoop)      
				AND (M.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)      
				AND CustomProp LIKE '%Odometer%' AND BoxMsgInTypeId in(2,3)),
				SpeedViolations = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 4) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 14) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 15) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 16) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId = 17) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				Temperature = (SELECT COUNT(BoxMsgInTypeId) from @tblMessageForProcessingTrip where BoxId = @intBoxLoop and BoxMsgInTypeId = (CASE @TemperatureType WHEN 1 THEN 82 WHEN 2 THEN 86 WHEN 3 THEN 166 WHEN 4 THEN 171 ELSE 0 END))
		WHERE Boxid =@intBoxLoop AND Distance IS NULL      
        
		--CALCULATE THE UTILIZED DAYS
		UPDATE @tblVehicles SET DaysUtilizaed =(SELECT CASE WHEN COUNT(Actions)>CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) THEN CAST(COUNT(Actions)-1 as varchar) ELSE CAST(COUNT(Actions) as varchar) END  
												--+ ' out of '+CAST( CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) AS VARCHAR) 
												FROM (SELECT COUNT(BoxId) AS Actions       
		FROM @tblMessageForProcessingTrip        
		WHERE BoxId=@intBoxLoop AND    
		(OriginDateTime BETWEEN  dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtStartDate) AND dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtEndDate))    
		--(OriginDateTime BETWEEN DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtStartDate)) AND DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEndDate)))    
		AND BoxMsgInTypeId IN (2,3)      
		GROUP BY CONVERT(DATE,OriginDateTime))AS A)      
		WHERE Boxid =@intBoxLoop AND DaysUtilizaed IS NULL      
        
		--CALCULATE THE NOOFTRIPS,RUNNING TIME AND IDLING TIME
		DELETE FROM @tblTrips       
		DELETE FROM @tblTripDetails       
		INSERT INTO @tblTrips (Boxid,TripTime,TripStatus)      
		SELECT BoxId,OriginDateTime,CASE WHEN BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'START'       
		WHEN BoxMsgInTypeId =3 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'STOP' ELSE NULL END          
		FROM rvlfMsgInHst       
		WHERE Boxid =@intBoxLoop      
		AND BoxMsgInTypeId IN(2,3)                
		AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate        
		ORDER BY BoxId,OriginDateTime       
          
		INSERT INTO @tblTripDetails (Boxid,EndTime,TripOutStatus,StartTime,TripInStatus)      
		SELECT MT.Boxid,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus      
		FROM @tblTrips AS MT       
		LEFT OUTER JOIN @tblTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'START'       
         
		--DELETE THE INVALID TRIPS      
		DELETE FROM @tblTripDetails WHERE StartTime IS NULL OR TripInStatus=TripOutStatus        
         
		--CALCULATE THE RUNNING TIME AND IDLING TIME       
		UPDATE @tblTripDetails SET RunningTime =DATEDIFF(S,StartTime,EndTime),      
		IdlingTime=(SELECT SUM(ISNULL(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,      
		(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT),0))                   
		FROM @tblMessageForProcessingTrip  WHERE Boxid=@intBoxLoop AND BoxMsgInTypeId =9 AND OriginDateTime BETWEEN StartTime AND EndTime AND CustomProp NOT LIKE '%Idling:0;%')      
        
		--UPDATE THE DETAILS TO MAIN TABLE      
		UPDATE @tblVehicles SET NoofTrips =(SELECT COUNT(TripId) FROM @tblTripDetails),      
		RunningTime=(SELECT SUM(RunningTime) FROM @tblTripDetails),      
		IdlingTime=(SELECT SUM(IdlingTime) FROM @tblTripDetails)            
		WHERE Boxid=@intBoxLoop        
           
		SELECT @intBoxLoop = MIN(Boxid) FROM @tblVehicles WHERE Boxid >@intBoxLoop       
	END      
    
	--Fetching KPI Details
	DECLARE @intLoopi int = NULL
	SELECT	@intLoopi = MIN(BoxId) FROM @tblVehicles 
	
	DECLARE @vcDetailData VARCHAR(MAX) = ''
	DECLARE @tblDetailData TABLE(BoxId bigint primary key, VehicleDescription nvarchar(50),IdlingDuration nvarchar(10),IdlingPercentage numeric(18,2),
								 DistanceTraveled int,SpeedViolations int, ExtremeAcceleration int, ExtremeBraking int, VehicleUtilization nvarchar(10), TemperatureHigh int)

	WHILE @intLoopi IS NOT NULL
	BEGIN
		INSERT	INTO @tblDetailData 
		SELECT	BoxId, VehicleDescription,ISNULL(IdlingTime,0),CAST(ISNULL((IdlingTime*1.00)/CASE WHEN(ISNULL(RunningTime,0)*1.00) = 0 THEN 1 
											ELSE (ISNULL(RunningTime,0)*1.00) END *100,0) AS NUMERIC(8,2)),
											CASE WHEN ISNULL(Distance,0) = 0 THEN '-' ELSE CAST(Distance AS VARCHAR) END,
				--CASE WHEN	ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END 
				--FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)),0) = 0 THEN '-' 
				--ELSE CAST((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance 
				--ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)) AS VARCHAR) END,
				SpeedViolations, ExtremeAcceleration + HarshAcceleration, ExtremeBraking + HarshBraking, DaysUtilizaed, Temperature			-- Harsh and Extreme values combined for Acceleration & Braking on 22-01-2016 by AnbarasuE
		FROM	@tblVehicles  
		WHERE	Boxid = @intLoopi
				
		SELECT	@vcDetailData = @vcDetailData + 
					(CASE @KPIID 
					WHEN 1 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(dbo.rvlf_fn_GetHHMMSSFromSec(IdlingDuration) AS VARCHAR) + ' </td><td>' + CASE WHEN (IdlingDuration/3600 < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (IdlingDuration/3600 > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">'
																																		WHEN (IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 2 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(IdlingPercentage AS VARCHAR) + ' </td><td>' + CASE	WHEN (IdlingPercentage < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (IdlingPercentage > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (IdlingPercentage BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 3 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(DistanceTraveled AS VARCHAR) + ' </td><td>' + CASE	WHEN (DistanceTraveled < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (DistanceTraveled > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (DistanceTraveled BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 4 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(SpeedViolations AS VARCHAR) + ' </td><td>' + CASE	WHEN (SpeedViolations < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (SpeedViolations > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (SpeedViolations BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 5 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeAcceleration AS VARCHAR) + ' </td><td>' + CASE	WHEN (ExtremeAcceleration < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (ExtremeAcceleration > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (ExtremeAcceleration BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 6 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(ExtremeBraking AS VARCHAR) + ' </td><td>' + CASE	WHEN (ExtremeBraking < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (ExtremeBraking > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (ExtremeBraking BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 7 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(VehicleUtilization AS VARCHAR)+ ' </td><td>'+ CASE	WHEN (VehicleUtilization < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (VehicleUtilization > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (VehicleUtilization BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 9 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,(DistanceTraveled * @CostKPIsValue)),3) + ' </td><td>' + CASE	WHEN ((DistanceTraveled * @CostKPIsValue) < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN ((DistanceTraveled * @CostKPIsValue) > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN ((DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 10 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CONVERT(VARCHAR,CONVERT(MONEY,((IdlingDuration * @CostKPIsValue)/3600)),3) + ' </td><td>' + CASE	WHEN (((IdlingDuration * @CostKPIsValue)/3600) < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">' 
																																		WHEN (((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					WHEN 11 THEN '<tr><td style="text-align:left;">'+ VehicleDescription +'</td><td>'+ CAST(TemperatureHigh AS VARCHAR)+ ' </td><td>'+ CASE	WHEN (TemperatureHigh < @MinRange) THEN '<img src="../images/fuellow-1_.png" title="Critical">'
																																		WHEN (TemperatureHigh > @MaxRange) THEN '<img src="../images/1_.png" title="Safe">'
																																		WHEN (TemperatureHigh BETWEEN @MinRange AND @MaxRange) THEN '<img src="../images/orange-1_.png" title="Warning">' 
																																END	+ '</td></tr>'
					ELSE '<tr><td colspan="3">No data found.</td></tr>'
					END)
		FROM	@tblDetailData  
		WHERE	BoxId = @intLoopi
		
		SELECT @intLoopi = MIN(BoxId) FROM @tblVehicles WHERE Boxid > @intLoopi
	END

	--Fetching KPI Summary
	DECLARE @totIdlingTime			INT = NULL      
	DECLARE @totIdlingPercent		NUMERIC(18,2) = NULL
	DECLARE @totDistanceTraveled	INT = NULL      
	DECLARE @totDaysUtilized		INT = NULL
	DECLARE @totTemperatureHigh		INT = NULL

	SELECT	@totIdlingTime		= SUM(CAST(IdlingDuration AS INT)),
			@totIdlingPercent	= CEILING(AVG(IdlingPercentage)),
			@totDistanceTraveled= SUM(ISNULL(DistanceTraveled,0)),
			@totDaysUtilized	= CAST(ROUND(AVG(CAST(VehicleUtilization AS NUMERIC(18,2))),0)AS INT),
			@totTemperatureHigh = SUM(CAST(TemperatureHigh AS INT))
	FROM	@tblDetailData

	-- Fetching KPI Chart data
	DECLARE @intSafe		VARCHAR(5) = NULL
	DECLARE @intWarning		VARCHAR(5) = NULL
	DECLARE @intCritical	VARCHAR(5) = NULL

	
	-- Template replacing with KPI values based on KPI Type
	IF (@KPIID = 1) 
	BEGIN
		--SELECT	@CurrValue = (SUM(msg.duration)), @CurrValueFormatted = (dbo.rvlf_fn_GetTimeFromSeconds(SUM(msg.duration))) --CAST(dbo.rvlf_fn_GetParamValueWithIndex(msg.CustomProp,'Idling:',';') AS bigint)))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) --AND msg.BoxMsgInTypeId = 9 --AND CHARINDEX('Idling',CustomProp,0)>0
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		SELECT	@CurrValue = @totIdlingTime/3600, @CurrValueFormatted = dbo.rvlf_fn_GetHHMMSSFromSec(@totIdlingTime)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical= COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 < @MinRange 
		SELECT	@intSafe  = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 > @MaxRange
	END
	ELSE IF (@KPIID = 2) 
	BEGIN	
		SELECT	@CurrValue = @totIdlingPercent, @CurrValueFormatted = @totIdlingPercent
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage > @MaxRange
	END
	ELSE IF (@KPIID = 3) 
	BEGIN	
		--SELECT	@CurrValue = (MAX(msg.odometer)-MIN(msg.odometer))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) AND msg.OriginDateTime Between @dtFDate and @dtEDate
		--GROUP BY msg.BoxId
		SELECT	@CurrValue = @totDistanceTraveled, @CurrValueFormatted = @totDistanceTraveled
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled > @MaxRange
	END
	ELSE IF (@KPIID = 4) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=4 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(SpeedViolations),0), @CurrValueFormatted = ISNULL(SUM(SpeedViolations),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations > @MaxRange
	END
	ELSE IF (@KPIID = 5) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=15 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeAcceleration),0), @CurrValueFormatted = ISNULL(SUM(ExtremeAcceleration),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration > @MaxRange
	END
	ELSE IF (@KPIID = 6) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=17 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeBraking),0), @CurrValueFormatted = ISNULL(SUM(ExtremeBraking),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking > @MaxRange
	END
	ELSE IF (@KPIID = 7) 
	BEGIN
		SELECT	@CurrValue = @totDaysUtilized, @CurrValueFormatted = @totDaysUtilized
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization > @MaxRange
		--SELECT	@CurrValue = COUNT(*) FROM rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) 
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		--AND		msg.BoxMsgInTypeId = 1
		--Group By msg.BoxId
	END		
	ELSE IF(@KPIID = 9)
	BEGIN 
		SELECT	@CurrValue = (@totDistanceTraveled * @CostKPIsValue), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,(@totDistanceTraveled * @CostKPIsValue)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) > @MaxRange
	END
	ELSE IF(@KPIID = 10)
	BEGIN 
		SELECT	@CurrValue = ((@totIdlingTime * @CostKPIsValue)/3600), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,((@totIdlingTime * @CostKPIsValue)/3600)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange
	END
	ELSE IF(@KPIID = 11)
	BEGIN 
		SELECT	@CurrValue = @totTemperatureHigh, @CurrValueFormatted = @totTemperatureHigh
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh > @MaxRange
	END
	ELSE 
	BEGIN
		SELECT @CurrValueFormatted = '15' 
	END
	
	SELECT	@UnitName = CurrencyName FROM rvlfCurrencyType CT
	INNER	JOIN rvlfOrganization O ON CT.CurrencyTypeId = O.CurrencyTypeId
	WHERE	OrganizationId = @bigOrganizationID	and @KPIID in (9,10)

	-- Add the T-SQL statements to compute the return value here
	SET	@Template	= REPLACE(@Template ,'$ChartScript$', 'google.setOnLoadCallback(drawChart_$Sno$);function drawChart_$Sno$() {
										var data = new google.visualization.arrayToDataTable([[''Bands'', ''No.of.Vehicles'', { role: ''style'' }],[''Safe'', '+ ISNULL(@intSafe,0) +', ''#04B713''],[''Warning'', '+ ISNULL(@intWarning,0) +', ''#FF7F00''],[''Critical'', '+ ISNULL(@intCritical,0) +', ''#FE0000''],]);
										var options = {width: 330,height: 400,colors: [''Red''],chartArea: { width: ''50%'' },hAxis: {title: ''KPI Status'',minValue: 0},vAxis: {title: ''No.of.Vehicles'',maxValue: 16,format: ''0'',gridlines: { count: 6 },minorGridlines: { count: 3 }}, legend: { position: "none" }};
										var chart = new google.visualization.ColumnChart(document.getElementById(''chart_div_$Sno$''));chart.draw(data, options);}')
	SET	@Template	= REPLACE(@Template ,'$Sno$', @Sno)
	SET	@Template	= REPLACE(@Template ,'$data-gs-id$', @AssignmentID)
	SET	@Template	= REPLACE(@Template ,'$gridData$', '<thead><th>Vehicle</th><th>$KPICaption$</th><th>Status</th></thead><tbody>'+ @vcDetailData +'</tbody>')
	SET	@Template	= REPLACE(@Template ,'$AssignmentID$', @AssignmentID)
	SET	@Template	= REPLACE(@Template ,'$KPIUnitName$', @UnitName)

	DECLARE @KPIStatus nvarchar(10)
	SET @KPIStatus = CASE WHEN (@CurrValue < @MinRange) THEN 'critical' WHEN (@CurrValue > @MaxRange) THEN 'safe' WHEN (@CurrValue between @MinRange and @MaxRange) THEN 'warning' ELSE 'safe' END
	
	SET	@Template	= REPLACE(@Template ,'$TileImgName$', 'img-' + @KPIStatus + '-kpi')
	SET	@Template	= REPLACE(@Template ,'$KPIValue$', @CurrValueFormatted)
	--SET	@Template	= REPLACE(@Template ,'$PnlTableClass2$', @KPIStatus)
	SET	@Template	= REPLACE(@Template ,'$PnlTableClass1$', CASE @DisplayTypeID WHEN 1  THEN 'tiletable' WHEN 2 THEN 'gaugetable' WHEN 3 THEN 'progresstable' WHEN 4 THEN 'tiletable' WHEN 5 THEN 'gridtable' END)
	SET	@Template	= REPLACE(@Template ,'$PanelClass$', CASE @DisplayTypeID WHEN 1 THEN 'tilediv' WHEN 2 THEN 'gaugediv' WHEN 3 THEN 'progressdiv' WHEN 4 THEN 'chartsdiv' WHEN 5 THEN 'griddiv' END)
	
	DECLARE @CustomTitleLen int 
	SET @CustomTitleLen = CASE @DisplayTypeID WHEN 1 THEN 25 ELSE 55 END 
	SET	@Template	= REPLACE(@Template ,'$CustomTitle$', CASE WHEN LEN(@CustomTitle) > @CustomTitleLen THEN SUBSTRING(@CustomTitle, 0, @CustomTitleLen) + '...' ELSE @CustomTitle END)
	SET	@Template	= REPLACE(@Template ,'$Tooltip$', @CustomTitle)
		
	DECLARE @PosX TINYINT, @PosY TINYINT
	SELECT @PosX = x, @PosY = y FROM rvlfKPIGridPosition POS
	RIGHT JOIN RVLFKPIUSERASSIGNMENT KUA ON POS.AssignmentId = KUA.ASSIGNMENTID
	WHERE KUA.AssignmentId = @AssignmentID

	SET	@Template	= REPLACE(@Template ,'$dataRows$', CASE WHEN @PosX IS NULL THEN 0 ELSE @PosX END)	--CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 3 THEN 3 WHEN 4 THEN 4 WHEN 5 THEN 5 END)  --CASE @Sno WHEN 1 THEN 1 WHEN 1 THEN 1 WHEN 3 THEN 1 WHEN 4 THEN 1 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataCols$', CASE WHEN @PosY IS NULL THEN 0 ELSE @PosY END)	--CASE WHEN @Sno < 5 THEN @Sno ELSE 4 END)

	SET	@Template	= REPLACE(@Template ,'$dataSize-y$', CASE @DisplayTypeID WHEN 1 THEN 1 WHEN 2 THEN 1 WHEN 3 THEN 1 WHEN 4 THEN 3 WHEN 5 THEN 2 END)
	SET	@Template	= REPLACE(@Template ,'$dataSize-x$', CASE @DisplayTypeID WHEN 1 THEN 3 WHEN 2 THEN 3 WHEN 3 THEN 3 WHEN 4 THEN 4 WHEN 5 THEN 4 END)
	
	SET	@Template	= REPLACE(@Template ,'$KPICaption$', /*LOWER(@KPIName) + */ 'Value(' + @UnitName + ')')
	SET @Template	= REPLACE(@Template, '$TitleColor$', 'style="background-color: ' + CASE WHEN @TitleClrCode IS NOT NULL THEN '#457DC7' ELSE @TitleClrCode END + '"')

	DECLARE @FleetName nvarchar(250)
	SET @FleetName	= (SELECT FleetName FROM rvlfFleet WHERE FleetId = @FleetId)
	SET	@Template	= REPLACE(@Template ,'$Fleet$', @FleetName)

	--DECLARE @Vehicles Table(VehicleId bigint, VehicleDescription nvarchar(50))
	--INSERT INTO @Vehicles 
	--SELECT v.VehicleId,v.VehicleDescription FROM rvlfVehicle v 
	--INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId 
	--WHERE va.BoxId IN (SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI]	(@BoxId,','))

	--DECLARE @minVehicleId bigint
	--SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles
	--DECLARE @VehicleName nvarchar(1000)

	--WHILE @minVehicleId IS NOT NULL
	--BEGIN
	--	IF @VehicleName IS NOT NULL
	--	BEGIN
	--		SET @VehicleName = @VehicleName + ',' + (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	ELSE
	--	BEGIN
	--		SET @VehicleName = (SELECT VehicleDescription FROM @Vehicles WHERE VehicleId = @minVehicleId)
	--	END
	--	SELECT @minVehicleId = MIN(VehicleId) FROM @Vehicles WHERE VehicleId > @minVehicleId
	--END

	SET @Template   = REPLACE(@Template, '$ESPType$',(SELECT DISTINCT Vehicletype FROM @BoxIds))

	SET	@Template	= REPLACE(@Template ,'$Vehicles$',	CASE @BoxId	WHEN '0' THEN 'All' 
														ELSE STUFF((SELECT ', ' + VehicleDescription FROM @BoxIds FOR XML PATH('')), 1, 1, '') END)
	SET	@Template	= REPLACE(@Template ,'$RefreshFreq$', CAST(@RefFreq AS VARCHAR(5)) + ' Sec')
	SET	@Template	= REPLACE(@Template ,'$Duration$', 'Last ' + CASE	WHEN @Duration = 336	THEN ' 2 Weeks'
																		WHEN @Duration Between 168	and 336 THEN ' 1 Week'
																		WHEN @Duration Between 48	and 168	THEN CAST(@Duration/24 AS Varchar(20)) + ' Days' 
																		ELSE CAST(@Duration AS Varchar(20)) + ' Hours' END)
	
	
	SET	@Template	= REPLACE(@Template ,'$Range$', ((CASE	WHEN @KPIID IN (9,10) THEN (CONVERT(VARCHAR,CONVERT(MONEY,@MinRange),3) + ' to ' + CONVERT(VARCHAR,CONVERT(MONEY,@MaxRange),3))
															ELSE (CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20))) END)  
															+ ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END))

	--SET	@Template	= REPLACE(@Template ,'$Range$', CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20)) + ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END)
	SET @Template	= @Template + '<input type="hidden" value="KPIStatus:' + @KPIStatus + '">'
		
	-- Return the result of the function	
	SET	@ChangedTemplate = @Template
	RETURN @ChangedTemplate
END



GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_KPIDbd_ExportKPIs]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasue
-- Create date: 27-09-2016
-- Description:	To Fetch the KPI summary and data for Export functionality
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_KPIDbd_ExportKPIs]
(
	-- Add the parameters for the function here
	@Sno				int,
	--@Template			nvarchar(MAX),
	--@TitleClrCode		nvarchar(10),
	@AssignmentID		int,
	@CustomTitle		nvarchar(75),
	@KPIID				int,
	@KPIName			nvarchar(75),
	@DisplayTypeID		tinyint,
	@CostKPIsValue		decimal(18,2),
	@TemperatureType	tinyint,
	@UnitName			nvarchar(10),
	@MinRange			int,
	@MaxRange			int,
	@FleetId			int,
	@BoxId				nvarchar(1000),
	@RefFreq			int,
	@Duration			int,
	@bigUserId			bigint,
	@bigOrganizationID	bigint
)
RETURNS	@KPIExport	 TABLE (Sno int, AssignmentId int, CustomTitle nvarchar(75), KPIID int, KPIName	nvarchar(75), CurrValueFormat nvarchar(50), 
							KPIStatus nvarchar(50), FleetName nvarchar(50), VehicleNames varchar(8000), DurationFormat nvarchar(50), 
							RangeFormat  nvarchar(50), UnitName nvarchar(20), MinRange nvarchar(50), MaxRange nvarchar(50), RefFreq nvarchar(50), BoxID bigint, 
							VehicleDescription nvarchar(75), LicensePlate varchar(50), Vin varchar(50), Value nvarchar(50), Status nvarchar(10))
AS
BEGIN
	-- Declare the return variable here
	DECLARE @BoxIds					TABLE (BOXID bigint,VehicleId INT,VehicleDescription nVarchar(150))
	DECLARE @CurrValue				int
	DECLARE @CurrValueFormatted		nvarchar(50)
	DECLARE @intBoxID				int
	DECLARE @dtStartDate			datetime = NULL  
 	DECLARE @dtEndDate				datetime = NULL

	SET @dtStartDate = DATEADD(Hour,-@Duration,GETUTCDATE())
	SET @dtEndDate = GETUTCDATE()
	
	INSERT	INTO @BoxIds (BOXID,VehicleId,VehicleDescription)
	SELECT	va.BoxID,v.VehicleId,v.VehicleDescription FROM rvlfVehicleAssignment va
	INNER	JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
	INNER	JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
	WHERE	fv.FleetId = @FleetId AND (@BoxId IS NULL OR @BoxId = '0' OR @BoxId = '' or
    BoxId	in (select * from rvlf_fn_ConvertArrayToTable(@BoxId,','))) AND V.OrganizationId = @bigOrganizationID
    ORDER	BY BoxId
	
	--SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@BoxId,',')
		 
	DECLARE @Lang varchar(50)       
	SELECT @Lang = ISNULL(Lang,'LanguageEn') FROM rvlfUserPreferences WHERE UserId = @bigUserId

    DECLARE @DefaultDateFormat INT = 0     
	SELECT  @DefaultDateFormat=(CASE WHEN  ISNULL(up.DefaultDateFormat,0)= 0 THEN 106 ELSE up.DefaultDateFormat END)      
	FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId      
            
	IF @FleetId IS NULL      
	BEGIN      
		SELECT @FleetId=FleetID FROM rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1      
	END      
	DECLARE @HoursToBeAdded INT = 0      
	DECLARE @MinsToBeAdded INT = 0      
	DECLARE @ConversionFactor NUMERIC (10,2) = 1.0      
	DECLARE @DistanceCaptionPrefix VARCHAR(15)      
	DECLARE @SpeedCaptionPrefix VARCHAR(15)      
	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
			@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,        
			@DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Kms)' END,      
			@SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END      
	FROM	rvlfUserPreferences up 
	INNER	JOIN rvlfTimeZones tz ON	up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId          
          
	--SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))      
	--SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                 
    
	DECLARE @dtFDate DATETIME = @dtStartDate    
	DECLARE @dtEDate DATETIME = @dtEndDate
	  
	DECLARE @tblVehicles TABLE      
	(
		VehicleId bigint,
		VehicleDescription nvarchar(50),
		LicensePlate varchar(50),
		Vin varchar(50),
		Boxid bigint,
		NoofTrips int,
		Distance int,
		RunningTime INT,
		IdlingTime INT,
		DaysUtilizaed varchar(30),
		FleetName varchar(50),
		SpeedViolations		int,
		HarshAcceleration	int,
		ExtremeAcceleration	int,
		HarshBraking		int,
		ExtremeBraking		int,
		Temperature			int
	)
      
	DECLARE @tblMessageForProcessingTrip TABLE (      
		[ProcessorID] [bigint] identity(1,1) NOT NULL,
		[Boxid] [int] NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[IgnitionStatus] [bit] NULL,
		[CustomProp] [varchar](600) NULL,
		[TripId] [bigint] NULL
	)      

	INSERT	INTO @tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin,FleetName)      
	SELECT	VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin,f.FleetName  
	FROM	rvlfBoxId BI
	INNER	JOIN rvlfVehicleAssignment VA ON BI.BoxId=VA.BoxId       
	INNER	JOIN rvlfFleetVehicles FV ON FV.VehicleId =VA.VehicleId       
	INNER	JOIN rvlfFleet F ON FV.FleetId=F.FleetId       
	INNER	JOIN rvlfVehicle V ON FV.VehicleId=V.VehicleId       
	INNER	JOIN rvlfOrganization O ON O.OrganizationId =F.OrganizationId       
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR V.OrganizationId = @bigOrganizationID AND F.OrganizationId = @bigOrganizationID)
	AND		(@FleetId IS NULL OR @FleetId = '' OR F.FleetId = @FleetId)
	AND		VA.BoxId IN (SELECT BOXID FROM @BoxIds)
	ORDER	BY BI.BOXID

	--GET THE TRIPS      
	DECLARE @tblTrips TABLE
	(
		ProcessId bigint identity(1,1),
		Boxid int null,
		TripTime datetime null,
		TripStatus varchar(10) null
	)
       
	--GET THE TRIP DETAILS      
	DECLARE @tblTripDetails TABLE      
	(        
		TripId bigint identity(1,1),      
		Boxid int null,        
		StartTime datetime null,      
		EndTime datetime null,      
		TripInStatus varchar(5) null,      
		TripOutStatus varchar(5) null,      
		RunningTime int null,      
		IdlingTime int null       
	)

	--GET TEMPERATURE PACKETS
	--DECLARE @tblTemperatureDetails TABLE      
	--(        
	--	MessageInId uniqueidentifier,
	--	BoxId bigint,
	--	BoxMsgInTypeId int,
	--	CustomProp varchar(600),
	--	TemperatureValue numeric(18,2)
	--)
      
	DECLARE @intBoxLoop int =(SELECT MIN(Boxid) FROM @tblVehicles)      
      
	WHILE @intBoxLoop IS NOT NULL      
	BEGIN       
		DELETE FROM @tblMessageForProcessingTrip        
		INSERT INTO @tblMessageForProcessingTrip(Boxid,OriginDateTime,BoxMsgInTypeId,IgnitionStatus,CustomProp)      
		SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,      
		CAST(SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,h.CustomProp             
		FROM rvlfMsgInHst h       
		INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                    
		WHERE m.OperationTypeID IN (SELECT p.OperationID  FROM rvlfPackageOperations p WHERE p.PackageId =       
		(SELECT op.PackageId FROM rvlfOrganizationPackage op WHERE op.OrganizationID = @bigOrganizationID      
		AND op.IsActive=1)      
		AND p.ModuleID = 26) and m.OperationTypeID IS NOT NULL                      
		AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
		AND h.BoxID = @intBoxLoop      
		ORDER BY h.origindatetime ASC        
          
		--CALCULATE THE DISTANCE
		UPDATE	@tblVehicles 
		SET		Distance =  (SELECT CEILING((MAX(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,1))) -      
							(CHARINDEX('Odometer=',CustomProp,1)+9)),0) AS BIGINT)) - MIN(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,      
							CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9)),0)AS BIGINT))) * @ConversionFactor)  AS DISTANCE
							FROM	@tblMessageForProcessingTrip M
							WHERE   (M.BoxId= @intBoxLoop) AND (M.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND CustomProp LIKE '%Odometer%' AND BoxMsgInTypeId in(2,3)),
				SpeedViolations = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 4) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 14) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 15) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 16) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 17) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				Temperature = (SELECT COUNT(BoxMsgInTypeId) from @tblMessageForProcessingTrip where BoxId = @intBoxLoop and BoxMsgInTypeId = (CASE @TemperatureType WHEN 1 THEN 82 WHEN 2 THEN 86 WHEN 3 THEN 166 WHEN 4 THEN 171 ELSE 0 END))
		WHERE	Boxid = @intBoxLoop AND Distance IS NULL
        
		--CALCULATE THE UTILIZED DAYS
		UPDATE @tblVehicles SET DaysUtilizaed =(SELECT CASE WHEN COUNT(Actions)>CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) THEN CAST(COUNT(Actions)-1 as varchar) ELSE CAST(COUNT(Actions) as varchar) END  
												--+ ' out of '+CAST( CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) AS VARCHAR) 
												FROM (SELECT COUNT(BoxId) AS Actions       
		FROM @tblMessageForProcessingTrip        
		WHERE BoxId=@intBoxLoop AND    
		(OriginDateTime BETWEEN  dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtStartDate) AND dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtEndDate))    
		--(OriginDateTime BETWEEN DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtStartDate)) AND DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEndDate)))    
		AND BoxMsgInTypeId IN (2,3)      
		GROUP BY CONVERT(DATE,OriginDateTime))AS A)      
		WHERE Boxid =@intBoxLoop AND DaysUtilizaed IS NULL      
        
		--CALCULATE THE NOOFTRIPS,RUNNING TIME AND IDLING TIME
		DELETE FROM @tblTrips       
		DELETE FROM @tblTripDetails       
		INSERT INTO @tblTrips (Boxid,TripTime,TripStatus)      
		SELECT BoxId,OriginDateTime,CASE WHEN BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'START'       
		WHEN BoxMsgInTypeId = 3 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'STOP' ELSE NULL END          
		FROM rvlfMsgInHst       
		WHERE Boxid =@intBoxLoop      
		AND BoxMsgInTypeId IN (2,3)                
		AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate        
		ORDER BY BoxId,OriginDateTime       
          
		INSERT INTO @tblTripDetails (Boxid,EndTime,TripOutStatus,StartTime,TripInStatus)      
		SELECT MT.Boxid,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus      
		FROM @tblTrips AS MT       
		LEFT OUTER JOIN @tblTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'START'       
         
		--DELETE THE INVALID TRIPS      
		DELETE FROM @tblTripDetails WHERE StartTime IS NULL OR TripInStatus=TripOutStatus        
         
		--CALCULATE THE RUNNING TIME AND IDLING TIME       
		UPDATE @tblTripDetails SET RunningTime =DATEDIFF(S,StartTime,EndTime),      
		IdlingTime=(SELECT SUM(ISNULL(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,      
		(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT),0))                   
		FROM @tblMessageForProcessingTrip  WHERE Boxid=@intBoxLoop AND BoxMsgInTypeId =9 AND OriginDateTime BETWEEN StartTime AND EndTime AND CustomProp NOT LIKE '%Idling:0;%')      
		        
		--UPDATE THE DETAILS TO MAIN TABLE      
		UPDATE @tblVehicles SET 
		NoofTrips   = (SELECT COUNT(TripId) FROM @tblTripDetails),
		RunningTime = (SELECT SUM(RunningTime) FROM @tblTripDetails),
		IdlingTime  = (SELECT SUM(IdlingTime) FROM @tblTripDetails)
		WHERE Boxid = @intBoxLoop
		
		SELECT @intBoxLoop = MIN(BoxId) FROM @tblVehicles WHERE Boxid > @intBoxLoop       
	END      

	--FETCHING KPI DETAILS
	DECLARE @intLoopi int = NULL
	SELECT	@intLoopi = MIN(BoxId) FROM @tblVehicles 
	
	DECLARE @tblVehicleKPIData TABLE(BoxId bigint primary key, VehicleDescription nvarchar(50), LicensePlate nvarchar(50), 
									VIN nvarchar(50), Value nvarchar(50), Status nvarchar(10))
	DECLARE @tblDetailData TABLE(BoxId bigint primary key, VehicleDescription nvarchar(50),LicensePlate nvarchar(50), VIN nvarchar(50),
								IdlingDuration nvarchar(10),IdlingPercentage numeric(18,2),DistanceTraveled int,SpeedViolations int, 
								ExtremeAcceleration int, ExtremeBraking int, VehicleUtilization nvarchar(10), TemperatureHigh int)

	
	WHILE @intLoopi IS NOT NULL
	BEGIN
		INSERT	INTO @tblDetailData 
		SELECT	BoxId, VehicleDescription, LicensePlate, VIN,ISNULL(IdlingTime,0),CAST(ISNULL((IdlingTime*1.00)/CASE WHEN(ISNULL(RunningTime,0)*1.00) = 0 THEN 1 
											ELSE (ISNULL(RunningTime,0)*1.00) END *100,0) AS NUMERIC(8,2)),
											CASE WHEN ISNULL(Distance,0) = 0 THEN '-' ELSE CAST(Distance AS VARCHAR) END,
				--CASE WHEN	ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END 
				--FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)),0) = 0 THEN '-' 
				--ELSE CAST((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance 
				--ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)) AS VARCHAR) END,
				SpeedViolations, ExtremeAcceleration + HarshAcceleration, ExtremeBraking + HarshBraking, DaysUtilizaed, Temperature			-- Harsh and Extreme values combined for Acceleration & Braking on 22-01-2016 by AnbarasuE
		FROM	@tblVehicles  
		WHERE	Boxid = @intLoopi
			
		INSERT	INTO @tblVehicleKPIData 	
		SELECT	BoxId, VehicleDescription, LicensePlate, VIN,
					(CASE @KPIID 
					WHEN 1 THEN CAST(dbo.rvlf_fn_GetHHMMSSFromSec(IdlingDuration) AS VARCHAR) 
					WHEN 2 THEN CAST(IdlingPercentage AS VARCHAR) 
					WHEN 3 THEN CAST(DistanceTraveled AS VARCHAR) 
					WHEN 4 THEN CAST(SpeedViolations AS VARCHAR) 
					WHEN 5 THEN CAST(ExtremeAcceleration AS VARCHAR) 
					WHEN 6 THEN CAST(ExtremeBraking AS VARCHAR) 
					WHEN 7 THEN CAST(VehicleUtilization AS VARCHAR)
					WHEN 9 THEN CONVERT(VARCHAR,CONVERT(MONEY,(DistanceTraveled * @CostKPIsValue)),3) 
					WHEN 10 THEN CONVERT(VARCHAR,CONVERT(MONEY,((IdlingDuration * @CostKPIsValue)/3600)),3) 
					WHEN 11 THEN CAST(TemperatureHigh AS VARCHAR)
					ELSE 'No data found.'
					END),
					(CASE @KPIID 
					WHEN 1 THEN CASE WHEN (IdlingDuration/3600 < @MinRange) THEN 'Safe' WHEN (IdlingDuration/3600 > @MaxRange) THEN 'Critical' WHEN (IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 2 THEN CASE WHEN (IdlingPercentage < @MinRange) THEN 'Safe' WHEN (IdlingPercentage > @MaxRange) THEN 'Critical'WHEN (IdlingPercentage BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END	 
					WHEN 3 THEN CASE WHEN (DistanceTraveled < @MinRange) THEN 'Safe' WHEN (DistanceTraveled > @MaxRange) THEN 'Critical'WHEN (DistanceTraveled BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END	
					WHEN 4 THEN CASE WHEN (SpeedViolations < @MinRange) THEN 'Safe' WHEN (SpeedViolations > @MaxRange) THEN 'Critical'WHEN (SpeedViolations BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 5 THEN CASE WHEN (ExtremeAcceleration < @MinRange) THEN 'Safe' WHEN (ExtremeAcceleration > @MaxRange) THEN 'Critical'WHEN (ExtremeAcceleration BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 6 THEN CASE WHEN (ExtremeBraking < @MinRange) THEN 'Safe' WHEN (ExtremeBraking > @MaxRange) THEN 'Critical'WHEN (ExtremeBraking BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 7 THEN CASE WHEN (VehicleUtilization < @MinRange) THEN 'Safe' WHEN (VehicleUtilization > @MaxRange) THEN 'Critical'WHEN (VehicleUtilization BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 9 THEN CASE WHEN ((DistanceTraveled * @CostKPIsValue) < @MinRange) THEN 'Safe' WHEN ((DistanceTraveled * @CostKPIsValue) > @MaxRange) THEN 'Critical'WHEN ((DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 10 THEN CASE WHEN (((IdlingDuration * @CostKPIsValue)/3600) < @MinRange) THEN 'Safe' WHEN (((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange) THEN 'Critical'WHEN (((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END	
					WHEN 11 THEN CASE WHEN (TemperatureHigh < @MinRange) THEN 'Safe' WHEN (TemperatureHigh > @MaxRange) THEN 'Critical'WHEN (TemperatureHigh BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END	
					ELSE 'No data found.'
					END)
		FROM	@tblDetailData  
		WHERE	BoxId = @intLoopi
		
		SELECT @intLoopi = MIN(BoxId) FROM @tblVehicles WHERE Boxid > @intLoopi
	END
	
	--FETCHING KPI SUMMARY
	DECLARE @totIdlingTime			INT = NULL      
	DECLARE @totIdlingPercent		NUMERIC(18,2) = NULL
	DECLARE @totDistanceTraveled	INT = NULL      
	DECLARE @totDaysUtilized		INT = NULL
	DECLARE @totTemperatureHigh		INT = NULL

	SELECT	@totIdlingTime		= SUM(CAST(IdlingDuration AS INT)),
			@totIdlingPercent	= CEILING(AVG(IdlingPercentage)),
			@totDistanceTraveled= SUM(ISNULL(DistanceTraveled,0)),
			@totDaysUtilized	= CAST(ROUND(AVG(CAST(VehicleUtilization AS NUMERIC(18,2))),0)AS INT),
			@totTemperatureHigh = SUM(CAST(TemperatureHigh AS INT))
	FROM	@tblDetailData

	-- FETCHING KPI CHART DATA
	DECLARE @intSafe		VARCHAR(5) = NULL
	DECLARE @intWarning		VARCHAR(5) = NULL
	DECLARE @intCritical	VARCHAR(5) = NULL
		
	-- TEMPLATE REPLACING WITH KPI VALUES BASED ON KPI TYPE
	IF (@KPIID = 1) 
	BEGIN
		--SELECT	@CurrValue = (SUM(msg.duration)), @CurrValueFormatted = (dbo.rvlf_fn_GetTimeFromSeconds(SUM(msg.duration))) --CAST(dbo.rvlf_fn_GetParamValueWithIndex(msg.CustomProp,'Idling:',';') AS bigint)))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) --AND msg.BoxMsgInTypeId = 9 --AND CHARINDEX('Idling',CustomProp,0)>0
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		SELECT	@CurrValue = @totIdlingTime/3600, @CurrValueFormatted = dbo.rvlf_fn_GetHHMMSSFromSec(@totIdlingTime)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 > @MaxRange
	END
	ELSE IF (@KPIID = 2) 
	BEGIN	
		SELECT	@CurrValue = @totIdlingPercent, @CurrValueFormatted = @totIdlingPercent
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage > @MaxRange
	END
	ELSE IF (@KPIID = 3) 
	BEGIN	
		--SELECT	@CurrValue = (MAX(msg.odometer)-MIN(msg.odometer))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) AND msg.OriginDateTime Between @dtFDate and @dtEDate
		--GROUP BY msg.BoxId
		SELECT	@CurrValue = @totDistanceTraveled, @CurrValueFormatted = @totDistanceTraveled
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled > @MaxRange
	END
	ELSE IF (@KPIID = 4) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=4 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(SpeedViolations),0), @CurrValueFormatted = ISNULL(SUM(SpeedViolations),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations > @MaxRange
	END
	ELSE IF (@KPIID = 5) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=15 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeAcceleration),0), @CurrValueFormatted = ISNULL(SUM(ExtremeAcceleration),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration > @MaxRange
	END
	ELSE IF (@KPIID = 6) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=17 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeBraking),0), @CurrValueFormatted = ISNULL(SUM(ExtremeBraking),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking > @MaxRange
	END
	ELSE IF (@KPIID = 7) 
	BEGIN
		SELECT	@CurrValue = @totDaysUtilized, @CurrValueFormatted = @totDaysUtilized
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization > @MaxRange
		--SELECT	@CurrValue = COUNT(*) FROM rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) 
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		--AND		msg.BoxMsgInTypeId = 1
		--Group By msg.BoxId
	END
	ELSE IF(@KPIID = 9)
	BEGIN 
		SELECT	@CurrValue = (@totDistanceTraveled * @CostKPIsValue), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,(@totDistanceTraveled * @CostKPIsValue)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) > @MaxRange
	END
	ELSE IF(@KPIID = 10)
	BEGIN 
		SELECT	@CurrValue = ((@totIdlingTime * @CostKPIsValue)/3600), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,((@totIdlingTime * @CostKPIsValue)/3600)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange
	END
	ELSE IF(@KPIID = 11)
	BEGIN 
		SELECT	@CurrValue = @totTemperatureHigh, @CurrValueFormatted = @totTemperatureHigh
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh > @MaxRange
	END
	ELSE 
	BEGIN
		SELECT @CurrValueFormatted = '15' 
	END
	
	SELECT	@UnitName = CurrencyName FROM rvlfCurrencyType CT
	INNER	JOIN rvlfOrganization O ON CT.CurrencyTypeId = O.CurrencyTypeId
	WHERE	OrganizationId = @bigOrganizationID	and @KPIID in (9,10)

	DECLARE @KPIStatus nvarchar(10)
	SET @KPIStatus = CASE WHEN (@CurrValue < @MinRange) THEN 'Safe' WHEN (@CurrValue > @MaxRange) THEN 'Critical' WHEN (@CurrValue between @MinRange and @MaxRange) THEN 'Warning' ELSE 'Safe' END
	
	DECLARE @FleetName NVARCHAR(250), @VehicleNames NVARCHAR(2000), @DurationFormat NVARCHAR(50), @RangeFormat NVARCHAR(50)
	SET @FleetName	= (SELECT FleetName FROM rvlfFleet WHERE FleetId = @FleetId)
	--SET	@Template	= REPLACE(@Template ,'$Fleet$', @FleetName)	
	SET	@VehicleNames	= CASE @BoxId	WHEN '0' THEN 'All' ELSE STUFF((SELECT ', ' + VehicleDescription FROM @BoxIds FOR XML PATH('')), 1, 1, '') END
	--SET	@Template	= REPLACE(@Template ,'$RefreshFreq$', CAST(@RefFreq AS VARCHAR(5)) + ' Sec')
	SET	@DurationFormat	= 'Last ' + CASE	WHEN @Duration = 168	THEN ' 1 Week' 
										WHEN @Duration Between 48 and 168	THEN CAST(@Duration/24 AS Varchar(20)) + ' Days' 
										ELSE CAST(@Duration AS Varchar(20)) + ' Hours' END
	
	SET	@RangeFormat	= (CASE	WHEN @KPIID IN (9,10) THEN (CONVERT(VARCHAR,CONVERT(MONEY,@MinRange),3) + ' to ' + CONVERT(VARCHAR,CONVERT(MONEY,@MaxRange),3))
															ELSE (CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20))) END)
															--+ ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END

	INSERT INTO @KPIExport
	SELECT	@Sno Sno, @AssignmentID AssignmentId, @CustomTitle CustomTitle, @KPIID KPIID, @KPIName KPIName, @CurrValueFormatted CurrValueFormat, 
			@KPIStatus KPIStatus, @FleetName FleetName, @VehicleNames VehicleNames, @DurationFormat DurationFormat, @RangeFormat RangeFormat, @UnitName UnitName,
			@MinRange MinRange, @MaxRange MaxRange, @RefFreq RefFreq, BoxId, VehicleDescription, LicensePlate, VIN, Value, Status
	FROM	@tblVehicleKPIData

	RETURN
END			


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_KPIDbd_ExportKPIs_Reversed]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasue
-- Create date: 28-09-2016
-- Description:	To Fetch the Reversed KPI summary and data for Export functionality.
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_KPIDbd_ExportKPIs_Reversed]
(
	-- Add the parameters for the function here
	@Sno				int,
	--@Template			nvarchar(MAX),
	--@TitleClrCode		nvarchar(10),
	@AssignmentID		int,
	@CustomTitle		nvarchar(75),
	@KPIID				int,
	@KPIName			nvarchar(75),
	@DisplayTypeID		tinyint,
	@CostKPIsValue		decimal(18,2),
	@TemperatureType	tinyint,
	@UnitName			nvarchar(10),
	@MinRange			int,
	@MaxRange			int,
	@FleetId			int,
	@BoxId				nvarchar(1000),
	@RefFreq			int,
	@Duration			int,
	@bigUserId			bigint,
	@bigOrganizationID	bigint
)
RETURNS	@KPIExport	 TABLE (Sno int, AssignmentId int, CustomTitle nvarchar(75), KPIID int, KPIName	nvarchar(75), CurrValueFormat nvarchar(50), 
							KPIStatus nvarchar(50), FleetName nvarchar(50), VehicleNames varchar(8000), DurationFormat nvarchar(50), 
							RangeFormat  nvarchar(50), UnitName nvarchar(20), MinRange nvarchar(50), MaxRange nvarchar(50), RefFreq nvarchar(50), BoxID bigint, 
							VehicleDescription nvarchar(75), LicensePlate varchar(50), Vin varchar(50), Value nvarchar(50), Status nvarchar(10))
AS
BEGIN
	-- Declare the return variable here
	DECLARE @BoxIds					TABLE (BOXID bigint,VehicleId INT,VehicleDescription nVarchar(150))
	DECLARE @CurrValue				int
	DECLARE @CurrValueFormatted		nvarchar(50)
	DECLARE @intBoxID				int
	DECLARE @dtStartDate			datetime = NULL  
 	DECLARE @dtEndDate				datetime = NULL

	SET @dtStartDate = DATEADD(Hour,-@Duration,GETUTCDATE())
	SET @dtEndDate = GETUTCDATE()
	
	INSERT	INTO @BoxIds (BOXID,VehicleId,VehicleDescription)
	SELECT	va.BoxID,v.VehicleId,v.VehicleDescription FROM rvlfVehicleAssignment va
	INNER	JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
	INNER	JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
	WHERE	fv.FleetId = @FleetId AND (@BoxId IS NULL OR @BoxId = '0' OR @BoxId = '' or
    BoxId	in (select * from rvlf_fn_ConvertArrayToTable(@BoxId,','))) AND V.OrganizationId = @bigOrganizationID
    ORDER	BY BoxId
	
	--SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@BoxId,',')
		 
	DECLARE @Lang varchar(50)       
	SELECT @Lang = ISNULL(Lang,'LanguageEn') FROM rvlfUserPreferences WHERE UserId = @bigUserId

    DECLARE @DefaultDateFormat INT = 0     
	SELECT  @DefaultDateFormat=(CASE WHEN  ISNULL(up.DefaultDateFormat,0)= 0 THEN 106 ELSE up.DefaultDateFormat END)      
	FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId      
            
	IF @FleetId IS NULL      
	BEGIN      
		SELECT @FleetId=FleetID FROM rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1      
	END      
	DECLARE @HoursToBeAdded INT = 0      
	DECLARE @MinsToBeAdded INT = 0      
	DECLARE @ConversionFactor NUMERIC (10,2) = 1.0      
	DECLARE @DistanceCaptionPrefix VARCHAR(15)      
	DECLARE @SpeedCaptionPrefix VARCHAR(15)      
	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
			@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,        
			@DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Kms)' END,      
			@SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END      
	FROM	rvlfUserPreferences up 
	INNER	JOIN rvlfTimeZones tz ON	up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId          
          
	--SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))      
	--SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                 
    
	DECLARE @dtFDate DATETIME = @dtStartDate    
	DECLARE @dtEDate DATETIME = @dtEndDate
	  
	DECLARE @tblVehicles TABLE      
	(
		VehicleId bigint,
		VehicleDescription nvarchar(50),
		LicensePlate varchar(50),
		Vin varchar(50),
		Boxid bigint,
		NoofTrips int,
		Distance int,
		RunningTime INT,
		IdlingTime INT,
		DaysUtilizaed varchar(30),
		FleetName varchar(50),
		SpeedViolations		int,
		HarshAcceleration	int,
		ExtremeAcceleration	int,
		HarshBraking		int,
		ExtremeBraking		int,
		Temperature			int
	)
      
	DECLARE @tblMessageForProcessingTrip TABLE (      
		[ProcessorID] [bigint] identity(1,1) NOT NULL,
		[Boxid] [int] NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[IgnitionStatus] [bit] NULL,
		[CustomProp] [varchar](600) NULL,
		[TripId] [bigint] NULL
	)      

	INSERT	INTO @tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin,FleetName)      
	SELECT	VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin,f.FleetName  
	FROM	rvlfBoxId BI
	INNER	JOIN rvlfVehicleAssignment VA ON BI.BoxId=VA.BoxId       
	INNER	JOIN rvlfFleetVehicles FV ON FV.VehicleId =VA.VehicleId       
	INNER	JOIN rvlfFleet F ON FV.FleetId=F.FleetId       
	INNER	JOIN rvlfVehicle V ON FV.VehicleId=V.VehicleId       
	INNER	JOIN rvlfOrganization O ON O.OrganizationId =F.OrganizationId       
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR V.OrganizationId = @bigOrganizationID AND F.OrganizationId = @bigOrganizationID)
	AND		(@FleetId IS NULL OR @FleetId = '' OR F.FleetId = @FleetId)
	AND		VA.BoxId IN (SELECT BOXID FROM @BoxIds)
	ORDER	BY BI.BOXID

	--GET THE TRIPS      
	DECLARE @tblTrips TABLE
	(
		ProcessId bigint identity(1,1),
		Boxid int null,
		TripTime datetime null,
		TripStatus varchar(10) null
	)
       
	--GET THE TRIP DETAILS      
	DECLARE @tblTripDetails TABLE      
	(        
		TripId bigint identity(1,1),      
		Boxid int null,        
		StartTime datetime null,      
		EndTime datetime null,      
		TripInStatus varchar(5) null,      
		TripOutStatus varchar(5) null,      
		RunningTime int null,      
		IdlingTime int null       
	)

	--GET TEMPERATURE PACKETS
	--DECLARE @tblTemperatureDetails TABLE      
	--(        
	--	MessageInId uniqueidentifier,
	--	BoxId bigint,
	--	BoxMsgInTypeId int,
	--	CustomProp varchar(600),
	--	TemperatureValue numeric(18,2)
	--)
      
	DECLARE @intBoxLoop int =(SELECT MIN(Boxid) FROM @tblVehicles)      
      
	WHILE @intBoxLoop IS NOT NULL      
	BEGIN       
		DELETE FROM @tblMessageForProcessingTrip        
		INSERT INTO @tblMessageForProcessingTrip(Boxid,OriginDateTime,BoxMsgInTypeId,IgnitionStatus,CustomProp)      
		SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,      
		CAST(SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,h.CustomProp             
		FROM rvlfMsgInHst h       
		INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                    
		WHERE m.OperationTypeID IN (SELECT p.OperationID  FROM rvlfPackageOperations p WHERE p.PackageId =       
		(SELECT op.PackageId FROM rvlfOrganizationPackage op WHERE op.OrganizationID = @bigOrganizationID      
		AND op.IsActive=1)      
		AND p.ModuleID = 26) and m.OperationTypeID IS NOT NULL                      
		AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
		AND h.BoxID = @intBoxLoop      
		ORDER BY h.origindatetime ASC        
          
		--CALCULATE THE DISTANCE
		UPDATE	@tblVehicles 
		SET		Distance =  (SELECT CEILING((MAX(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,1))) -      
							(CHARINDEX('Odometer=',CustomProp,1)+9)),0) AS BIGINT)) - MIN(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,      
							CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9)),0)AS BIGINT))) * @ConversionFactor)  AS DISTANCE
							FROM	@tblMessageForProcessingTrip M
							WHERE   (M.BoxId= @intBoxLoop) AND (M.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND CustomProp LIKE '%Odometer%' AND BoxMsgInTypeId in(2,3)),
				SpeedViolations = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 4) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 14) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeAcceleration = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 15) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				HarshBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 16) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				ExtremeBraking = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE  (BoxId = @intBoxLoop and BoxMsgInTypeId = 17) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
				Temperature = (SELECT COUNT(BoxMsgInTypeId) from @tblMessageForProcessingTrip where BoxId = @intBoxLoop and BoxMsgInTypeId = (CASE @TemperatureType WHEN 1 THEN 82 WHEN 2 THEN 86 WHEN 3 THEN 166 WHEN 4 THEN 171 ELSE 0 END))
		WHERE	Boxid = @intBoxLoop AND Distance IS NULL
        
		--CALCULATE THE UTILIZED DAYS
		UPDATE @tblVehicles SET DaysUtilizaed =(SELECT CASE WHEN COUNT(Actions)>CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) THEN CAST(COUNT(Actions)-1 as varchar) ELSE CAST(COUNT(Actions) as varchar) END  
												--+ ' out of '+CAST( CEILING(CAST(DATEDIFF(HH,@dtStartDate,@dtEndDate)/(24*1.00) AS NUMERIC(6,2))) AS VARCHAR) 
												FROM (SELECT COUNT(BoxId) AS Actions       
		FROM @tblMessageForProcessingTrip        
		WHERE BoxId=@intBoxLoop AND    
		(OriginDateTime BETWEEN  dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtStartDate) AND dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@dtEndDate))    
		--(OriginDateTime BETWEEN DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtStartDate)) AND DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEndDate)))    
		AND BoxMsgInTypeId IN (2,3)      
		GROUP BY CONVERT(DATE,OriginDateTime))AS A)      
		WHERE Boxid =@intBoxLoop AND DaysUtilizaed IS NULL      
        
		--CALCULATE THE NOOFTRIPS,RUNNING TIME AND IDLING TIME
		DELETE FROM @tblTrips       
		DELETE FROM @tblTripDetails       
		INSERT INTO @tblTrips (Boxid,TripTime,TripStatus)      
		SELECT BoxId,OriginDateTime,CASE WHEN BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'START'       
		WHEN BoxMsgInTypeId = 3 AND CustomProp LIKE '%SENSOR_NUM=3%' THEN 'STOP' ELSE NULL END          
		FROM rvlfMsgInHst       
		WHERE Boxid =@intBoxLoop      
		AND BoxMsgInTypeId IN (2,3)                
		AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate        
		ORDER BY BoxId,OriginDateTime       
          
		INSERT INTO @tblTripDetails (Boxid,EndTime,TripOutStatus,StartTime,TripInStatus)      
		SELECT MT.Boxid,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus      
		FROM @tblTrips AS MT       
		LEFT OUTER JOIN @tblTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'START'       
         
		--DELETE THE INVALID TRIPS      
		DELETE FROM @tblTripDetails WHERE StartTime IS NULL OR TripInStatus=TripOutStatus        
         
		--CALCULATE THE RUNNING TIME AND IDLING TIME       
		UPDATE @tblTripDetails SET RunningTime =DATEDIFF(S,StartTime,EndTime),      
		IdlingTime=(SELECT SUM(ISNULL(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,      
		(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT),0))                   
		FROM @tblMessageForProcessingTrip  WHERE Boxid=@intBoxLoop AND BoxMsgInTypeId =9 AND OriginDateTime BETWEEN StartTime AND EndTime AND CustomProp NOT LIKE '%Idling:0;%')      
		        
		--UPDATE THE DETAILS TO MAIN TABLE      
		UPDATE @tblVehicles SET 
		NoofTrips   = (SELECT COUNT(TripId) FROM @tblTripDetails),
		RunningTime = (SELECT SUM(RunningTime) FROM @tblTripDetails),
		IdlingTime  = (SELECT SUM(IdlingTime) FROM @tblTripDetails)
		WHERE Boxid = @intBoxLoop
		
		SELECT @intBoxLoop = MIN(BoxId) FROM @tblVehicles WHERE Boxid > @intBoxLoop       
	END      

	--FETCHING KPI DETAILS
	DECLARE @intLoopi int = NULL
	SELECT	@intLoopi = MIN(BoxId) FROM @tblVehicles 
	
	DECLARE @tblVehicleKPIData TABLE(BoxId bigint primary key, VehicleDescription nvarchar(50), LicensePlate nvarchar(50), 
									VIN nvarchar(50), Value nvarchar(50), Status nvarchar(10))
	DECLARE @tblDetailData TABLE(BoxId bigint primary key, VehicleDescription nvarchar(50),LicensePlate nvarchar(50), VIN nvarchar(50),
								IdlingDuration nvarchar(10),IdlingPercentage numeric(18,2),DistanceTraveled int,SpeedViolations int, 
								ExtremeAcceleration int, ExtremeBraking int, VehicleUtilization nvarchar(10), TemperatureHigh int)

	
	WHILE @intLoopi IS NOT NULL
	BEGIN
		INSERT	INTO @tblDetailData 
		SELECT	BoxId, VehicleDescription, LicensePlate, VIN,ISNULL(IdlingTime,0),CAST(ISNULL((IdlingTime*1.00)/CASE WHEN(ISNULL(RunningTime,0)*1.00) = 0 THEN 1 
											ELSE (ISNULL(RunningTime,0)*1.00) END *100,0) AS NUMERIC(8,2)),
											CASE WHEN ISNULL(Distance,0) = 0 THEN '-' ELSE CAST(Distance AS VARCHAR) END,
				--CASE WHEN	ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END 
				--FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)),0) = 0 THEN '-' 
				--ELSE CAST((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance 
				--ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Distance)) AS VARCHAR) END,
				SpeedViolations, ExtremeAcceleration + HarshAcceleration, ExtremeBraking + HarshBraking, DaysUtilizaed, Temperature			-- Harsh and Extreme values combined for Acceleration & Braking on 22-01-2016 by AnbarasuE
		FROM	@tblVehicles  
		WHERE	Boxid = @intLoopi
			
		INSERT	INTO @tblVehicleKPIData 	
		SELECT	BoxId, VehicleDescription, LicensePlate, VIN,
					(CASE @KPIID 
					WHEN 1 THEN CAST(dbo.rvlf_fn_GetHHMMSSFromSec(IdlingDuration) AS VARCHAR) 
					WHEN 2 THEN CAST(IdlingPercentage AS VARCHAR) 
					WHEN 3 THEN CAST(DistanceTraveled AS VARCHAR) 
					WHEN 4 THEN CAST(SpeedViolations AS VARCHAR) 
					WHEN 5 THEN CAST(ExtremeAcceleration AS VARCHAR) 
					WHEN 6 THEN CAST(ExtremeBraking AS VARCHAR) 
					WHEN 7 THEN CAST(VehicleUtilization AS VARCHAR)
					WHEN 9 THEN CONVERT(VARCHAR,CONVERT(MONEY,(DistanceTraveled * @CostKPIsValue)),3) 
					WHEN 10 THEN CONVERT(VARCHAR,CONVERT(MONEY,((IdlingDuration * @CostKPIsValue)/3600)),3) 
					WHEN 11 THEN CAST(TemperatureHigh AS VARCHAR)
					ELSE 'No data found.'
					END),
					(CASE @KPIID 
					WHEN 1 THEN CASE WHEN (IdlingDuration/3600 < @MinRange) THEN 'Critical' WHEN (IdlingDuration/3600 > @MaxRange) THEN 'Safe' WHEN (IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 2 THEN CASE WHEN (IdlingPercentage < @MinRange) THEN 'Critical' WHEN (IdlingPercentage > @MaxRange) THEN 'Safe'WHEN (IdlingPercentage BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END	 
					WHEN 3 THEN CASE WHEN (DistanceTraveled < @MinRange) THEN 'Critical' WHEN (DistanceTraveled > @MaxRange) THEN 'Safe'WHEN (DistanceTraveled BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END	
					WHEN 4 THEN CASE WHEN (SpeedViolations < @MinRange) THEN 'Critical' WHEN (SpeedViolations > @MaxRange) THEN 'Safe'WHEN (SpeedViolations BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 5 THEN CASE WHEN (ExtremeAcceleration < @MinRange) THEN 'Critical' WHEN (ExtremeAcceleration > @MaxRange) THEN 'Safe'WHEN (ExtremeAcceleration BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 6 THEN CASE WHEN (ExtremeBraking < @MinRange) THEN 'Critical' WHEN (ExtremeBraking > @MaxRange) THEN 'Safe'WHEN (ExtremeBraking BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 7 THEN CASE WHEN (VehicleUtilization < @MinRange) THEN 'Critical' WHEN (VehicleUtilization > @MaxRange) THEN 'Safe'WHEN (VehicleUtilization BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 9 THEN CASE WHEN ((DistanceTraveled * @CostKPIsValue) < @MinRange) THEN 'Critical' WHEN ((DistanceTraveled * @CostKPIsValue) > @MaxRange) THEN 'Safe'WHEN ((DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 10 THEN CASE WHEN (((IdlingDuration * @CostKPIsValue)/3600) < @MinRange) THEN 'Critical' WHEN (((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange) THEN 'Safe'WHEN (((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END	
					WHEN 11 THEN CASE WHEN (TemperatureHigh < @MinRange) THEN 'Critical' WHEN (TemperatureHigh > @MaxRange) THEN 'Safe'WHEN (TemperatureHigh BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END	
					ELSE 'No data found.'
					END)
		FROM	@tblDetailData  
		WHERE	BoxId = @intLoopi
		
		SELECT @intLoopi = MIN(BoxId) FROM @tblVehicles WHERE Boxid > @intLoopi
	END
	
	--FETCHING KPI SUMMARY
	DECLARE @totIdlingTime			INT = NULL      
	DECLARE @totIdlingPercent		NUMERIC(18,2) = NULL
	DECLARE @totDistanceTraveled	INT = NULL      
	DECLARE @totDaysUtilized		INT = NULL
	DECLARE @totTemperatureHigh		INT = NULL

	SELECT	@totIdlingTime		= SUM(CAST(IdlingDuration AS INT)),
			@totIdlingPercent	= CEILING(AVG(IdlingPercentage)),
			@totDistanceTraveled= SUM(ISNULL(DistanceTraveled,0)),
			@totDaysUtilized	= CAST(ROUND(AVG(CAST(VehicleUtilization AS NUMERIC(18,2))),0)AS INT),
			@totTemperatureHigh = SUM(CAST(TemperatureHigh AS INT))
	FROM	@tblDetailData

	-- FETCHING KPI CHART DATA
	DECLARE @intSafe		VARCHAR(5) = NULL
	DECLARE @intWarning		VARCHAR(5) = NULL
	DECLARE @intCritical	VARCHAR(5) = NULL
		
	-- TEMPLATE REPLACING WITH KPI VALUES BASED ON KPI TYPE
	IF (@KPIID = 1) 
	BEGIN
		--SELECT	@CurrValue = (SUM(msg.duration)), @CurrValueFormatted = (dbo.rvlf_fn_GetTimeFromSeconds(SUM(msg.duration))) --CAST(dbo.rvlf_fn_GetParamValueWithIndex(msg.CustomProp,'Idling:',';') AS bigint)))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) --AND msg.BoxMsgInTypeId = 9 --AND CHARINDEX('Idling',CustomProp,0)>0
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		SELECT	@CurrValue = @totIdlingTime/3600, @CurrValueFormatted = dbo.rvlf_fn_GetHHMMSSFromSec(@totIdlingTime)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingDuration/3600 > @MaxRange
	END
	ELSE IF (@KPIID = 2) 
	BEGIN	
		SELECT	@CurrValue = @totIdlingPercent, @CurrValueFormatted = @totIdlingPercent
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE IdlingPercentage > @MaxRange
	END
	ELSE IF (@KPIID = 3) 
	BEGIN	
		--SELECT	@CurrValue = (MAX(msg.odometer)-MIN(msg.odometer))
		--FROM	rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) AND msg.OriginDateTime Between @dtFDate and @dtEDate
		--GROUP BY msg.BoxId
		SELECT	@CurrValue = @totDistanceTraveled, @CurrValueFormatted = @totDistanceTraveled
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE DistanceTraveled > @MaxRange
	END
	ELSE IF (@KPIID = 4) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=4 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(SpeedViolations),0), @CurrValueFormatted = ISNULL(SUM(SpeedViolations),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE SpeedViolations > @MaxRange
	END
	ELSE IF (@KPIID = 5) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=15 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeAcceleration),0), @CurrValueFormatted = ISNULL(SUM(ExtremeAcceleration),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeAcceleration > @MaxRange
	END
	ELSE IF (@KPIID = 6) 
	BEGIN
		--SELECT	@CurrValue = COUNT(*), @CurrValueFormatted = COUNT(*) FROM	rvlfAlarm A 
		--WHERE A.BoxId IN (SELECT BOXID FROM @BoxIds) AND A.AlarmType=17 AND	A.DateTimeCreated Between @dtFDate and @dtEDate
		SELECT	@CurrValue = ISNULL(SUM(ExtremeBraking),0), @CurrValueFormatted = ISNULL(SUM(ExtremeBraking),0) FROM @tblDetailData
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ExtremeBraking > @MaxRange
	END
	ELSE IF (@KPIID = 7) 
	BEGIN
		SELECT	@CurrValue = @totDaysUtilized, @CurrValueFormatted = @totDaysUtilized
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE VehicleUtilization > @MaxRange
		--SELECT	@CurrValue = COUNT(*) FROM rvlfMsgInHst msg 
		--WHERE	msg.BoxId IN (SELECT BOXID FROM @BoxIds) 
		--AND		msg.OriginDateTime Between @dtFDate and @dtEDate
		--AND		msg.BoxMsgInTypeId = 1
		--Group By msg.BoxId
	END
	ELSE IF(@KPIID = 9)
	BEGIN 
		SELECT	@CurrValue = (@totDistanceTraveled * @CostKPIsValue), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,(@totDistanceTraveled * @CostKPIsValue)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE (DistanceTraveled * @CostKPIsValue) > @MaxRange
	END
	ELSE IF(@KPIID = 10)
	BEGIN 
		SELECT	@CurrValue = ((@totIdlingTime * @CostKPIsValue)/3600), @CurrValueFormatted = CONVERT(VARCHAR,CONVERT(MONEY,((@totIdlingTime * @CostKPIsValue)/3600)),3)
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE ((IdlingDuration * @CostKPIsValue)/3600) > @MaxRange
	END
	ELSE IF(@KPIID = 11)
	BEGIN 
		SELECT	@CurrValue = @totTemperatureHigh, @CurrValueFormatted = @totTemperatureHigh
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh BETWEEN @MinRange AND @MaxRange
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh < @MinRange 
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE TemperatureHigh > @MaxRange
	END
	ELSE 
	BEGIN
		SELECT @CurrValueFormatted = '15' 
	END
	
	SELECT	@UnitName = CurrencyName FROM rvlfCurrencyType CT
	INNER	JOIN rvlfOrganization O ON CT.CurrencyTypeId = O.CurrencyTypeId
	WHERE	OrganizationId = @bigOrganizationID	and @KPIID in (9,10)

	DECLARE @KPIStatus nvarchar(10)
	SET @KPIStatus = CASE WHEN (@CurrValue < @MinRange) THEN 'Critical' WHEN (@CurrValue > @MaxRange) THEN 'Safe' WHEN (@CurrValue between @MinRange and @MaxRange) THEN 'Warning' ELSE 'Safe' END
	
	DECLARE @FleetName NVARCHAR(250), @VehicleNames NVARCHAR(2000), @DurationFormat NVARCHAR(50), @RangeFormat NVARCHAR(50)
	SET @FleetName	= (SELECT FleetName FROM rvlfFleet WHERE FleetId = @FleetId)
	--SET	@Template	= REPLACE(@Template ,'$Fleet$', @FleetName)	
	SET	@VehicleNames	= CASE @BoxId	WHEN '0' THEN 'All' ELSE STUFF((SELECT ', ' + VehicleDescription FROM @BoxIds FOR XML PATH('')), 1, 1, '') END
	--SET	@Template	= REPLACE(@Template ,'$RefreshFreq$', CAST(@RefFreq AS VARCHAR(5)) + ' Sec')
	SET	@DurationFormat	= 'Last ' + CASE	WHEN @Duration = 168	THEN ' 1 Week' 
										WHEN @Duration Between 48 and 168	THEN CAST(@Duration/24 AS Varchar(20)) + ' Days' 
										ELSE CAST(@Duration AS Varchar(20)) + ' Hours' END
	
	SET	@RangeFormat	= (CASE	WHEN @KPIID IN (9,10) THEN (CONVERT(VARCHAR,CONVERT(MONEY,@MinRange),3) + ' to ' + CONVERT(VARCHAR,CONVERT(MONEY,@MaxRange),3))
															ELSE (CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20))) END)  
															--+ ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END

	INSERT INTO @KPIExport
	SELECT	@Sno Sno, @AssignmentID AssignmentId, @CustomTitle CustomTitle, @KPIID KPIID, @KPIName KPIName, @CurrValueFormatted CurrValueFormat, 
			@KPIStatus KPIStatus, @FleetName FleetName, @VehicleNames VehicleNames, @DurationFormat DurationFormat, @RangeFormat RangeFormat, @UnitName UnitName,
			@MinRange MinRange, @MaxRange MaxRange, @RefFreq RefFreq, BoxId, VehicleDescription, LicensePlate, VIN, Value, Status
	FROM	@tblVehicleKPIData

	RETURN
END			


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_KPIDbd_ExportKPIs_Test]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--GO
--/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_KPIDbd_ExportKPIs]    Script Date: 27-11-2018 10:18:21 ******/
--SET ANSI_NULLS ON
--GO
--SET QUOTED_IDENTIFIER ON
--GO

---- =============================================
---- Author:		Anbarasue
---- Create date: 27-09-2016
---- Description:	To Fetch the KPI summary and data for Export functionality
---- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_KPIDbd_ExportKPIs_Test]
(
	@Sno				int,
	--@Template			nvarchar(MAX),
	--@TitleClrCode		nvarchar(10),
	@AssignmentID		int,
	@CustomTitle		nvarchar(75),
	@KPIID				int,
	@KPIName			nvarchar(75),
	@DisplayTypeID		tinyint,
	@CostKPIsValue		decimal(18,2),
	@TemperatureType	tinyint,
	@UnitName			nvarchar(10),
	@MinRange			int,
	@MaxRange			int,
	@FleetId			int,
	@BoxId				nvarchar(1000),
	@RefFreq			int,
	@Duration			int,
	@bigUserId			bigint,
	@bigOrganizationID	bigint,
	@EquType int,
	@CurEnergytype INT
)
RETURNS	@KPIExport	 TABLE (Sno int, AssignmentId int, CustomTitle nvarchar(75), KPIID int, KPIName	nvarchar(75), CurrValueFormat nvarchar(50), 
							KPIStatus nvarchar(50), FleetName nvarchar(50), VehicleNames varchar(8000), DurationFormat nvarchar(50), 
							RangeFormat  nvarchar(50), UnitName nvarchar(20), MinRange nvarchar(50), MaxRange nvarchar(50), RefFreq nvarchar(50), BoxID nvarchar(1000), 
							VehicleDescription nvarchar(75), LicensePlate varchar(50), Vin varchar(50), Value nvarchar(50), Status nvarchar(10))
AS
BEGIN
	-- Declare the return variable here
	DECLARE @BoxIds					TABLE (TId INT IDENTITY(1,1),BOXID NVARCHAR(1000),VehicleId INT,VehicleDescription NVARCHAR(150))
	DECLARE @CurrValue				INT
	DECLARE @CurrValueFormatted		NVARCHAR(50)
	DECLARE @intBoxID				INT
	DECLARE @dtStartDate			DATETIME = NULL  
 	DECLARE @dtEndDate				DATETIME = NULL

	SET @dtStartDate = DATEADD(Hour,-@Duration,GETUTCDATE())
	SET @dtEndDate = GETUTCDATE()
	
	INSERT	INTO @BoxIds (BOXID,VehicleId,VehicleDescription)
	SELECT	va.BoxID,v.VehicleId,v.VehicleDescription FROM rvlfVehicleAssignment va
	INNER	JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
	INNER	JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
	INNER	JOIN rvlfVehicleType VT ON VT.VehicleTypeId = v.VehicleTypeId
	WHERE	fv.FleetId = @FleetId AND (@BoxId IS NULL OR @BoxId = '0' OR @BoxId = '' or
    BoxId	in (SELECT * FROM rvlf_fn_ConvertArrayToTable(@BoxId,','))) AND V.OrganizationId = @bigOrganizationID AND VT.VehicleTypeId = @EquType
    ORDER	BY BoxId	

	--SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@BoxId,',')
		 
	DECLARE @Lang varchar(50)       
	SELECT @Lang = ISNULL(Lang,'LanguageEn') FROM rvlfUserPreferences WHERE UserId = @bigUserId

    DECLARE @DefaultDateFormat INT = 0     
	SELECT  @DefaultDateFormat=(CASE WHEN  ISNULL(up.DefaultDateFormat,0)= 0 THEN 106 ELSE up.DefaultDateFormat END)      
	FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId      
            
	IF @FleetId IS NULL      
	BEGIN      
		SELECT @FleetId=FleetID FROM rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1      
	END      
	DECLARE @HoursToBeAdded INT = 0      
	DECLARE @MinsToBeAdded INT = 0      
	DECLARE @ConversionFactor NUMERIC (10,2) = 1.0      
	DECLARE @DistanceCaptionPrefix VARCHAR(15)      
	DECLARE @SpeedCaptionPrefix VARCHAR(15)      
	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
			@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,        
			@DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Kms)' END,      
			@SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END      
	FROM	rvlfUserPreferences up 
	INNER	JOIN rvlfTimeZones tz ON	up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId          
          
	--SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))      
	--SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                 
    
	DECLARE @dtFDate DATETIME = @dtStartDate    
	DECLARE @dtEDate DATETIME = @dtEndDate
	  
	DECLARE @tblVehicles TABLE      
	(
	    VehId INT IDENTITY(1,1),
		VehicleId bigint,
		VehicleDescription nvarchar(50),
		LicensePlate varchar(50),
		Vin varchar(50),
		Boxid nvarchar(1000),
		NoofTrips int,
		Distance int,
		RunningTime INT,
		IdlingTime INT,
		DaysUtilizaed varchar(30),
		FleetName varchar(50),
		SpeedViolations		int,
		HarshAcceleration	int,
		ExtremeAcceleration	int,
		HarshBraking		int,
		ExtremeBraking		int,
		Temperature			int,
		[Current] INT,
	    Energy  INT,
		[Power] INT,
		T1 INT,T2 INT,T3 INT,T4 INT,P1 INT,
		P2 INT,P3 INT, P4 INT,DPp INT,
		DPp1 INT, DPps INT,P5 INT, P6 INT, P7 INT, P8 INT, P9 INT, P10 INT, P11 INT	
	)
      
	DECLARE @tblMessageForProcessingTrip TABLE (      
		[ProcessorID] [bigint] identity(1,1) NOT NULL,
		[Boxid] [nvarchar](1000) NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[IgnitionStatus] [bit] NULL,
		[CustomProp] [varchar](600) NULL,
		[TripId] [bigint] NULL,
		[Current] INT,
	    Energy  INT,
		[Power]  NUMERIC(5,1),
		T1 INT,T2 INT,T3 INT,T4 INT,P1 INT,
		P2 INT,P3 INT, P4 INT,DPp INT,DPp1 INT, DPps INT,P5 INT, P6 INT, P7 INT, P8 INT, P9 INT, P10 INT, P11 INT
	)      

	INSERT	INTO @tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin,FleetName)      
	SELECT	VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin,f.FleetName  
	FROM	rvlfBoxId BI
	INNER	JOIN rvlfVehicleAssignment VA ON BI.BoxId=VA.BoxId       
	INNER	JOIN rvlfFleetVehicles FV ON FV.VehicleId =VA.VehicleId       
	INNER	JOIN rvlfFleet F ON FV.FleetId=F.FleetId       
	INNER	JOIN rvlfVehicle V ON FV.VehicleId=V.VehicleId       
	INNER	JOIN rvlfOrganization O ON O.OrganizationId =F.OrganizationId       
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR V.OrganizationId = @bigOrganizationID AND F.OrganizationId = @bigOrganizationID)
	AND		(@FleetId IS NULL OR @FleetId = '' OR F.FleetId = @FleetId)
	AND		VA.BoxId IN (SELECT BOXID FROM @BoxIds)
	ORDER	BY BI.BOXID

	--GET THE TRIPS      
	DECLARE @tblTrips TABLE
	(
		ProcessId bigint identity(1,1),
		Boxid nvarchar(1000) null,
		TripTime datetime null,
		TripStatus varchar(10) null
	)
       
	--GET THE TRIP DETAILS      
	DECLARE @tblTripDetails TABLE      
	(        
		TripId bigint identity(1,1),      
		Boxid varchar(1000) null,        
		StartTime datetime null,      
		EndTime datetime null,      
		TripInStatus varchar(5) null,      
		TripOutStatus varchar(5) null,      
		RunningTime int null,      
		IdlingTime int null       
	)

	--GET TEMPERATURE PACKETS
	--DECLARE @tblTemperatureDetails TABLE      
	--(        
	--	MessageInId uniqueidentifier,
	--	BoxId bigint,
	--	BoxMsgInTypeId int,
	--	CustomProp varchar(600),
	--	TemperatureValue numeric(18,2)
	--)
      
	DECLARE @intBoxLoop INT =(SELECT MIN(VehId) FROM @tblVehicles)      
    DECLARE @CBoxID NVARCHAR(1000)  
	WHILE @intBoxLoop IS NOT NULL      
	BEGIN       
		DELETE FROM @tblMessageForProcessingTrip        

		SELECT @CBoxID = Boxid FROM @tblVehicles WHERE VehId = @intBoxLoop

		INSERT INTO @tblMessageForProcessingTrip(Boxid,OriginDateTime,BoxMsgInTypeId,IgnitionStatus,CustomProp,[Current],Energy,[Power],T1,T2,T3,T4
		,P1,P2,P3,P4,DPps,DPp,DPp1,P5,P6,P7,P8,P9,P10,P11)      
		SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,      
		CAST(SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,h.CustomProp,
		--dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'CR1_R=',';'),
		CASE WHEN @CurEnergytype = 1 THEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'CR1_R=',';'),'0') 
		     WHEN @CurEnergytype = 2 THEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'CR2_R=',';'),'0')
			 WHEN @CurEnergytype = 3 THEN ISNULL(S.CR3_R,'0') 
			 WHEN @CurEnergytype= 4  THEN ISNULL(S.CR4_R,'0')   WHEN @CurEnergytype =5  THEN ISNULL(S.CR5_R,'0')   WHEN @CurEnergytype = 6  THEN ISNULL(PR.CR6_R,'0')
			 WHEN @CurEnergytype= 7  THEN ISNULL(PR.CR7_R,'0')  WHEN @CurEnergytype =8  THEN ISNULL(PR.CR8_R,'0')  WHEN @CurEnergytype = 9  THEN ISNULL(PR.CR9_R,'0')
			 WHEN @CurEnergytype= 10 THEN ISNULL(PR.CR10_R,'0')WHEN @CurEnergytype =11 THEN ISNULL(PR.CR11_R,'0') WHEN @CurEnergytype = 12 THEN ISNULL(FC.CR12_R,'0')			 
			 WHEN @CurEnergytype= 13 THEN ISNULL(FC.CR13_R,'0')WHEN @CurEnergytype =14 THEN ISNULL(FC.CR14_R,'0') WHEN @CurEnergytype = 15 THEN ISNULL(FC.CR15_R,'0')
			 WHEN @CurEnergytype= 16 THEN ISNULL(FC.CR16_R,'0')WHEN @CurEnergytype =17 THEN ISNULL(FC.CR17_R,'0') WHEN @CurEnergytype = 18 THEN ISNULL(FC.CR18_R,'0')
			 WHEN @CurEnergytype= 19 THEN ISNULL(FC.CR19_R,'0')ELSE '0' END,
		--CASE WHEN h.CustomProp like '%WH1=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'WH1=',';'),'0') END,
		CASE WHEN @CurEnergytype = 1 THEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'WH1=',';'),'0') 
		     WHEN @CurEnergytype = 2 THEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'WH2=',';'),'0')
			 WHEN @CurEnergytype = 3 THEN ISNULL(S.WH3,'0') 
			 WHEN @CurEnergytype= 4  THEN ISNULL(S.WH4,'0')   WHEN @CurEnergytype =5  THEN ISNULL(S.WH5,'0')   WHEN @CurEnergytype = 6  THEN ISNULL(PR.WH6,'0')
			 WHEN @CurEnergytype= 7  THEN ISNULL(PR.WH7,'0')  WHEN @CurEnergytype =8  THEN ISNULL(PR.WH8,'0')  WHEN @CurEnergytype = 9  THEN ISNULL(PR.WH9,'0')
			 WHEN @CurEnergytype= 10 THEN ISNULL(PR.WH10,'0')WHEN @CurEnergytype =11 THEN ISNULL(PR.WH11,'0') WHEN @CurEnergytype = 12 THEN ISNULL(FC.WH12,'0')			 
			 WHEN @CurEnergytype= 13 THEN ISNULL(FC.WH13,'0')WHEN @CurEnergytype =14 THEN ISNULL(FC.WH14,'0') WHEN @CurEnergytype = 15 THEN ISNULL(FC.WH15,'0')
			 WHEN @CurEnergytype= 16 THEN ISNULL(FC.WH16,'0')WHEN @CurEnergytype =17 THEN ISNULL(FC.WH17,'0') WHEN @CurEnergytype = 18 THEN ISNULL(FC.WH18,'0')
			 WHEN @CurEnergytype= 19 THEN ISNULL(FC.WH19,'0')ELSE '0' END,
		CASE WHEN h.CustomProp like '%PO1=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'PO1=',';'),'0') END,
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'T1_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'T2_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'T3_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'T4_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'P1_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'P2_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'P3_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'P4_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'DPps_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'DPp_R=',';'),
		dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp, 'DPp1_R=',';'),  
		ISNULL(S.P5_R,'0'),ISNULL(PR.P6_R,'0'),ISNULL(PR.P7_R,'0'),ISNULL(FC.P8_R,'0'),
		ISNULL(FC.P9_R,'0'),ISNULL(FC.P10_R,'0'),ISNULL(FC.P11_R,'0')   
		--CASE WHEN h.CustomProp like '%CR1=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'CR1=',';'),'0') END,
		--CASE WHEN h.CustomProp like '%WH1=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'WH1=',';'),'0') END,
		--CASE WHEN h.CustomProp like '%PO1=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'PO1=',';'),'0') END,
		--CASE WHEN h.CustomProp like '%T1=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'T1=',';'),'0') END,
  --      CASE WHEN h.CustomProp like '%T2=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'T2=',';'),'0') END,
  --      CASE WHEN h.CustomProp like '%T3=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'T3=',';'),'0') END,
		--CASE WHEN h.CustomProp like '%T4=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'T4=',';'),'0') END,
  --      CASE WHEN h.CustomProp like '%P1=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'P1=',';'),'0') END,
  --      CASE WHEN h.CustomProp like '%P2=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'P2=',';'),'0') END,
		--CASE WHEN h.CustomProp like '%P3=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'P3=',';'),'0') END,
  --      CASE WHEN h.CustomProp like '%P4=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'P4=',';'),'0') END,
		--CASE WHEN h.CustomProp like '%DPps=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'DPps=',';'),'0') END,
		--CASE WHEN h.CustomProp like '%DPp=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'DPp=',';'),'0') END,     
		--CASE WHEN h.CustomProp like '%DPp1=NaN%' THEN '0' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp, 'DPp1=',';'),'0') END                
		FROM rvlfMsgInHst h     
		LEFT OUTER JOIN rvlfMsgInHst_Primary PR ON PR.MessageInID = h.MessageInID
		LEFT OUTER JOIN rvlfMsgInHst_Secondary S ON S.MessageInID = h.MessageInID
		LEFT OUTER JOIN rvlfMsgInHst_FibreCompactor FC ON FC.MessageInID = h.MessageInID          
		INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                    
		WHERE m.OperationTypeID IN (SELECT p.OperationID  FROM rvlfPackageOperations p WHERE p.PackageId =       
		(SELECT op.PackageId FROM rvlfOrganizationPackage op WHERE op.OrganizationID = @bigOrganizationID      
		AND op.IsActive=1)      
		AND p.ModuleID = 26) and m.OperationTypeID IS NOT NULL                      
		AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
		AND h.BoxID = @CBoxID   AND  h.BoxMsgInTypeId NOT IN(8)
		ORDER BY h.origindatetime ASC        
          
		--CALCULATE THE DISTANCE

		UPDATE	@tblVehicles  SET
		   --[Current] = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip  WHERE (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND [Current] > @MaxRange),	
		   [Current] = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip  WHERE (BoxId = @CBoxID  AND [Current] = 1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),	
		   Energy = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip  WHERE (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND Energy > @MaxRange),	
		   [Power] = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip  WHERE (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND [Power] > @MaxRange),	
		   T1 = (SELECT COUNT(*) from @tblMessageForProcessingTrip  WHERE (BoxId = @CBoxID AND T1=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   T2 = (SELECT COUNT(*) from @tblMessageForProcessingTrip  WHERE (BoxId = @CBoxID AND T2=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   T3 = (SELECT COUNT(*) from @tblMessageForProcessingTrip  WHERE (BoxId = @CBoxID AND T3=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   T4 = (SELECT COUNT(*) from @tblMessageForProcessingTrip  WHERE (BoxId = @CBoxID AND T4=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P1 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND P1=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P2 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND P2=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P3 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND P3=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P4 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND P4=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   DPps = (SELECT COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND DPps=1)AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   DPp1 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND DPp1=1)AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   DPp = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND DPp=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P5 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND P5=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P6 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND P6=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P7 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND P7=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P8 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND P8=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P9 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND P9=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P10 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND P10=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)),
		   P11 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID AND P11=1) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate))
		   --T1 = (SELECT COUNT(*) from @tblMessageForProcessingTrip  where (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND T1 > @MaxRange),--AND TV.T1 >= PR.T1_Max), 
		   --T2 = (SELECT COUNT(*) from @tblMessageForProcessingTrip  where (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND T2 > @MaxRange),
		   --T3 = (SELECT COUNT(*) from @tblMessageForProcessingTrip  where (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND T3 > @MaxRange),
		   --T4 = (SELECT COUNT(*) from @tblMessageForProcessingTrip  where (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND T4 > @MaxRange),
		   --P1 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND P1 > @MaxRange),
		   --P2 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND P2 > @MaxRange),
		   --P3 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND P3 > @MaxRange),
		   --P4 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND P4 > @MaxRange),
		   --DPps = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND DPps > @MaxRange),
		   --DPp1 = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND DPp1 > @MaxRange),
		   --DPp = (SELECT  COUNT(*) FROM @tblMessageForProcessingTrip WHERE (BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND DPp > @MaxRange)
		  --      T1 = (SELECT Count(*)from @tblMessageForProcessingTrip TV inner join rvlfParamRange PR ON TV.Boxid = PR.Boxid where (TV.BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)AND TV.T1 >= PR.T1_Max),
				--T2 = (SELECT Count(*)from @tblMessageForProcessingTrip TV inner join rvlfParamRange PR ON TV.Boxid = PR.Boxid where (TV.BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)AND TV.T2 >= PR.T2_Max),
				--T3 = (SELECT Count(*)from @tblMessageForProcessingTrip TV inner join rvlfParamRange PR ON TV.Boxid = PR.Boxid where (TV.BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)AND TV.T3 >= PR.T3_Max),
				--T4 = (SELECT Count(*)from @tblMessageForProcessingTrip TV inner join rvlfParamRange PR ON TV.Boxid = PR.Boxid where (TV.BoxId = @CBoxID ) AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)AND TV.T4 >= PR.T4_Max)
		WHERE	Boxid = @CBoxID     
		
		SELECT @intBoxLoop = MIN(VehId) FROM @tblVehicles WHERE VehId > @intBoxLoop       
	END   

	--FETCHING KPI DETAILS
	DECLARE @intLoopi int = NULL
	DECLARE @cKBoxId nvarchar(1000)
	SELECT	@intLoopi = MIN(VehId) FROM @tblVehicles 
	
	DECLARE @tblVehicleKPIData TABLE(VID Int IDENTITY(1,1) primary key,BoxId nvarchar(1000), VehicleDescription nvarchar(50), 
								 Value nvarchar(50), Status nvarchar(10))
	DECLARE @tblDetailData TABLE(TVID INT IDENTITY(1,1) primary key,BoxId nvarchar(1000), VehicleDescription nvarchar(50),[Current] INT, Energy INT, [Power] INT,T1 INT, T2 INT, T3 INT,T4 INT,P1 INT, P2 INT, P3 INT, P4 INT,DPp INT, DPp1 INT, DPps INT,P5 INT, P6 INT, P7 INT, P8 INT, P9 INT, P10 INT, P11 INT)

	
	WHILE @intLoopi IS NOT NULL
	BEGIN
	    SELECT	@cKBoxId = Boxid  FROM @tblVehicles WHERE VehId=@intLoopi

		INSERT	INTO @tblDetailData 
		SELECT	BoxId, VehicleDescription,[Current],Energy,[Power],T1,T2,T3,T4,P1,P2,P3,P4,DPp,DPp1,DPps,P5,P6,P7,P8,P9,P10,p11			-- Harsh and Extreme values combined for Acceleration & Braking on 22-01-2016 by AnbarasuE
		FROM	@tblVehicles  
		WHERE	Boxid = @cKBoxId
			
		INSERT	INTO @tblVehicleKPIData 	
		SELECT	BoxId, VehicleDescription,
					(CASE @KPIID 				
					WHEN 1 THEN CAST([Current] AS VARCHAR) 
					WHEN 2 THEN CAST(Energy AS VARCHAR) 
					WHEN 3 THEN CAST(T1 AS VARCHAR) 
					WHEN 4 THEN CAST(T2 AS VARCHAR) 
					WHEN 5 THEN CAST(T3 AS VARCHAR) 
					WHEN 6 THEN CAST(T4 AS VARCHAR) 
					WHEN 7 THEN CAST(P1 AS VARCHAR)
					WHEN 8 THEN CAST(P2 AS VARCHAR)
					WHEN 9 THEN CAST(P3 AS VARCHAR) 
					WHEN 10 THEN CAST(P4 AS VARCHAR) 
					WHEN 11 THEN CAST(DPps AS VARCHAR)
					WHEN 12 THEN CAST(DPp AS VARCHAR)
					WHEN 13 THEN CAST(DPp1 AS VARCHAR)
					WHEN 15 THEN CAST([Power] AS VARCHAR)
					WHEN 16 THEN CAST(P5 AS VARCHAR)
					WHEN 17 THEN CAST(P6 AS VARCHAR)
					WHEN 18 THEN CAST(P7 AS VARCHAR)
					WHEN 19 THEN CAST(P8 AS VARCHAR)
					WHEN 20 THEN CAST(P9 AS VARCHAR)
					WHEN 21 THEN CAST(P10 AS VARCHAR)
					WHEN 22 THEN CAST(P11 AS VARCHAR)						
					ELSE 'No data found.'
					END),
					(CASE @KPIID 
					WHEN 1 THEN CASE WHEN ([Current] < @MinRange) THEN 'Safe' WHEN ([Current] > @MaxRange) THEN 'Critical'WHEN ([Current] BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 2 THEN CASE WHEN (Energy < @MinRange) THEN 'Safe' WHEN (Energy > @MaxRange) THEN 'Critical'WHEN (Energy BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END					
					WHEN 3 THEN CASE WHEN (T1 < @MinRange) THEN 'Safe' WHEN (T1 > @MaxRange) THEN 'Critical'WHEN (T1 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END	
					WHEN 4 THEN CASE WHEN (T2 < @MinRange) THEN 'Safe' WHEN (T2 > @MaxRange) THEN 'Critical'WHEN (T2 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 5 THEN CASE WHEN (T3 < @MinRange) THEN 'Safe' WHEN (T3 > @MaxRange) THEN 'Critical'WHEN (T3 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 6 THEN CASE WHEN (T4 < @MinRange) THEN 'Safe' WHEN (T4 > @MaxRange) THEN 'Critical'WHEN (T4 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 7 THEN CASE WHEN (P1 < @MinRange) THEN 'Safe' WHEN (P1 > @MaxRange) THEN 'Critical'WHEN (P1 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 8 THEN CASE WHEN (P2 < @MinRange) THEN 'Safe' WHEN (P2 > @MaxRange) THEN 'Critical'WHEN (P2 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 9 THEN CASE WHEN (P3 < @MinRange) THEN 'Safe' WHEN (P3 > @MaxRange) THEN 'Critical'WHEN (P3 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 10 THEN CASE WHEN (P4 < @MinRange) THEN 'Safe' WHEN (P4 > @MaxRange) THEN 'Critical'WHEN (P4 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 11 THEN CASE WHEN (DPps < @MinRange) THEN 'Safe' WHEN (DPps > @MaxRange) THEN 'Critical'WHEN (DPps BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END	
					WHEN 12 THEN CASE WHEN (DPp < @MinRange) THEN 'Safe' WHEN (DPp > @MaxRange) THEN 'Critical'WHEN (DPp BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 13 THEN CASE WHEN (DPp1 < @MinRange) THEN 'Safe' WHEN (DPp1 > @MaxRange) THEN 'Critical'WHEN (DPp1 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END	
					WHEN 15 THEN CASE WHEN ([Power] < @MinRange) THEN 'Safe' WHEN ([Power] > @MaxRange) THEN 'Critical'WHEN ([Power] BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END	
					WHEN 16 THEN CASE WHEN (P5 < @MinRange) THEN 'Safe' WHEN (P5 > @MaxRange) THEN 'Critical'WHEN (P5 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 17 THEN CASE WHEN (P6 < @MinRange) THEN 'Safe' WHEN (P6 > @MaxRange) THEN 'Critical'WHEN (P6 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 18 THEN CASE WHEN (P7 < @MinRange) THEN 'Safe' WHEN (P7 > @MaxRange) THEN 'Critical'WHEN (P7 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 19 THEN CASE WHEN (P8 < @MinRange) THEN 'Safe' WHEN (P8 > @MaxRange) THEN 'Critical'WHEN (P8 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END			
					WHEN 20 THEN CASE WHEN (P9 < @MinRange) THEN 'Safe' WHEN (P9 > @MaxRange) THEN 'Critical'WHEN (P9 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 21 THEN CASE WHEN (P10 < @MinRange) THEN 'Safe' WHEN (P10 > @MaxRange) THEN 'Critical'WHEN (P10 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					WHEN 22 THEN CASE WHEN (P11 < @MinRange) THEN 'Safe' WHEN (P11 > @MaxRange) THEN 'Critical'WHEN (P11 BETWEEN @MinRange AND @MaxRange) THEN 'Warning' END
					ELSE 'No data found.'
					END)
		FROM	@tblDetailData  
		WHERE	BoxId = @cKBoxId
		
		SELECT @intLoopi = MIN(VehId) FROM @tblVehicles WHERE VehId > @intLoopi
	END
	
	--FETCHING KPI SUMMARY	
	DECLARE @TotalCurrent INT = NULL, @TotalEnergy INT = NULL, @TotalPower INT = NULL, @TotalP1 INT = NULL,@TotalP2 INT = NULL, @TotalP3 INT = NULL, @TotalP4 INT = NULL
	DECLARE @TotalDPp INT = NULL, @TotalDPps INT = NULL, @TotalDPp1 INT = NULL
	DECLARE @TotalT1                INT =NULL,@TotalP5 INT, @TotalP6 INT, @TotalP7 INT, @TotalP8 INT,@TotalP9 INT, @TotalP10 INT, @TotalP11 INT	
	DECLARE @TotalT2                INT =NULL
	DECLARE @TotalT3                INT =NULL
	DECLARE @TotalT4                INT =NULL
	DECLARE @KPICurrSts varchar(20) =NULL,@KPIP3Sts     varchar(20) =NULL
    DECLARE @KPIT1Sts   varchar(20) =NULL,  @KPIP4Sts   varchar(20) =NULL
	DECLARE @KPIT2Sts   varchar(20) =NULL,  @KPIDPpsSts varchar(20) =NULL
	DECLARE @KPIT3Sts   varchar(20) =NULL,  @KPIDPpSts  varchar(20) =NULL 
	DECLARE @KPIT4Sts   varchar(20) =NULL,  @KPIDPp1Sts varchar(20) =NULL
	DECLARE @KPIP1Sts   varchar(20) =NULL,  @KPIP5Sts   varchar(20) ,@KPIP6Sts  varchar(20), @KPIP7Sts varchar(20) ,@KPIP8Sts varchar(20) 
	DECLARE @KPIP2Sts   varchar(20) =NULL,  @KPIP9Sts   varchar(20) ,@KPIP10Sts varchar(20), @KPIP11Sts varchar(20) 

	SELECT	
			--@TotalCurrent = SUM(CAST([Current] AS INT)),
		@TotalCurrent =CASE WHEN [Current] > @MaxRange THEN Count(VehicleDescription) ELSE 
			               CASE WHEN 
			               (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE [Current] < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE [Current] BETWEEN @MinRange AND @MaxRange) 
			               THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE [Current] < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE [Current] BETWEEN @MinRange AND @MaxRange) END 
			               END,
		@TotalEnergy= SUM(CAST(Energy AS INT)), 
			--@TotalT1 = SUM(CAST(T1 AS INT)),
		@TotalT1 = CASE WHEN T1 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T1 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T1 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T1 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T1 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
			--@TotalT2 = SUM(CAST(T2 AS INT)),
		@TotalT2 = CASE WHEN T2 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T2 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T2 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T2 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T2 BETWEEN @MinRange AND @MaxRange) END 
			           END,
		    --@TotalT3 = SUM(CAST(T3 AS INT))
		@TotalT3 = CASE WHEN T3 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T3 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T3 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T3 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T3 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
		     --@TotalT4 = SUM(CAST(T4 AS INT)),
		@TotalT4 = CASE WHEN T4 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T4 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T4 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T4 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T4 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
			--@TotalDPp =SUM(CAST(DPp AS INT)),
		@TotalDPp = CASE WHEN DPp > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp BETWEEN @MinRange AND @MaxRange) END 
			           END,	
	    @TotalPower = SUM(CAST([Power] AS INT)), 
			--@TotalP1 = SUM(CAST(P1 AS INT)), 
	    @TotalP1 = CASE WHEN P1 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
			--@TotalP2 = SUM(CAST(P2 AS INT)),
		@TotalP2 = CASE WHEN P2 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P2 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P2 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P2 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P2 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
			--@TotalP3 = SUM(CAST(P3 AS INT)),
		@TotalP3 = CASE WHEN P3 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P3 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P3 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P3 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P3 BETWEEN @MinRange AND @MaxRange) END 
			           END,
			--@TotalP4 = SUM(CAST(P4 AS INT)),
	    @TotalP4 = CASE WHEN P4 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P4 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P4 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P4 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P4 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
			--@TotalDPp1 = SUM(CAST(DPp1 AS INT)),
	    @TotalDPp1 =  CASE WHEN DPp1 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp1 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp1 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp1 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp1 BETWEEN @MinRange AND @MaxRange) END 
			           END,
			--@TotalDPps = SUM(CAST(DPps AS INT)),
		 @TotalDPps = CASE WHEN DPps > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps BETWEEN @MinRange AND @MaxRange) END 
			           END,
         @TotalP5 = CASE WHEN P5 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P5 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P5 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P5 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P5 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
		 @TotalP6 = CASE WHEN P6 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P6 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P6 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P6 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P6 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
	     @TotalP7 = CASE WHEN P7 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P7 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P7 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P7 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P7 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
		 @TotalP8 = CASE WHEN P8 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P8 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P8 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P8 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P8 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
		 @TotalP9 = CASE WHEN P9 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P9 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P9 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P9 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P9 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
		 @TotalP10 = CASE WHEN P10 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P10 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P10 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P10 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P10 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
		 @TotalP11 = CASE WHEN P11 > @MaxRange THEN Count(VehicleDescription) ELSE 
			           CASE WHEN 
			           (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P11 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P11 BETWEEN @MinRange AND @MaxRange) 
			           THEN (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P11 < @MinRange) ELSE (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P11 BETWEEN @MinRange AND @MaxRange) END 
			           END,	
					   ---------------------- KPI Status -----------------------------------------
			@KPICurrSts = CASE WHEN [Current] > @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE [Current] < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE [Current] BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIT1Sts = CASE WHEN T1 > @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T1 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T1 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIT2Sts = CASE WHEN T2 > @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T2 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T2 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,	
			 @KPIT3Sts = CASE WHEN T3 > @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T3 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T3 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,	
			 @KPIT4Sts = CASE WHEN T4 > @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T4 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE T4 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,	
			 @KPIP1Sts = CASE WHEN P1> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P1 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			  @KPIP2Sts = CASE WHEN P2> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P2 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P2 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIP3Sts = CASE WHEN P3> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P3 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P3 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIP4Sts =CASE WHEN P4> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P4 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P4 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIDPpSts =CASE WHEN DPp> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIDPpsSts =CASE WHEN DPps> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIDPpsSts =CASE WHEN DPps> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPps BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIDPp1Sts =CASE WHEN DPp1> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp1 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE DPp1 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIP5Sts =CASE WHEN P5> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P5 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P5 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIP6Sts =CASE WHEN P6> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P6 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P6 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIP7Sts =CASE WHEN P7> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P7 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P7 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIP8Sts =CASE WHEN P8> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P8 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P8 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIP9Sts =CASE WHEN P9> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P9 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P9 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIP10Sts =CASE WHEN P10> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P10 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P10 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END,
			 @KPIP11Sts =CASE WHEN P11> @MaxRange THEN 'critical' ELSE 
			CASE WHEN 
			(SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P11 < @MinRange) > (SELECT COUNT(VehicleDescription) FROM @tblDetailData WHERE P11 BETWEEN @MinRange AND @MaxRange) 
			THEN 'safe' ELSE 'warning' END 
			 END
				FROM	@tblDetailData GROUP BY [Current],T1,T2,T3,T4,P1,P2,P3,P4,DPp,DPp1,DPps,P5,P6,P7,P8,P9,P10,P11

	-- FETCHING KPI CHART DATA
	DECLARE @intSafe		VARCHAR(5) = NULL
	DECLARE @intWarning		VARCHAR(5) = NULL
	DECLARE @intCritical	VARCHAR(5) = NULL
		
	-- TEMPLATE REPLACING WITH KPI VALUES BASED ON KPI TYPE
	IF (@KPIID = 1) 
	BEGIN		
		SELECT	@CurrValue = @TotalCurrent, @CurrValueFormatted = @TotalCurrent
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalCurrent BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalCurrent < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalCurrent > @MaxRange
	END
	ELSE IF(@KPIID = 2) 
	BEGIN	
		SELECT	@CurrValue = @TotalEnergy, @CurrValueFormatted = @TotalEnergy
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalEnergy BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalEnergy < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalEnergy > @MaxRange
	END
	ELSE IF (@KPIID = 3) 
	BEGIN	
		SELECT	@CurrValue = @TotalT1, @CurrValueFormatted = @TotalT1
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalT1 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalT1 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalT1 > @MaxRange
	END
	ELSE IF (@KPIID = 4) 
	BEGIN
	
		SELECT	@CurrValue = @TotalT2, @CurrValueFormatted = @TotalT2
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalT2 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalT2 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalT2 > @MaxRange
	END
	ELSE IF (@KPIID = 5) 
	BEGIN
	    SELECT	@CurrValue = @TotalT3, @CurrValueFormatted = @TotalT3
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalT3 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalT3 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalT3 > @MaxRange
	END
	ELSE IF (@KPIID = 6) 
	BEGIN
		 SELECT	@CurrValue = @TotalT4, @CurrValueFormatted = @TotalT4
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalT4 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalT4 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalT4 > @MaxRange
	END
	ELSE IF (@KPIID = 7) 
	BEGIN
		SELECT	@CurrValue = @TotalP1, @CurrValueFormatted = @TotalP1
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP1 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP1 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP1 > @MaxRange		
	END
	ELSE IF (@KPIID = 8) 
	BEGIN
		SELECT	@CurrValue = @TotalP2, @CurrValueFormatted = @TotalP2
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP2 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP2 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP2 > @MaxRange		
	END
	ELSE IF(@KPIID = 9)
	BEGIN 
		SELECT	@CurrValue = @TotalP3, @CurrValueFormatted = @TotalP3
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP3 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP3 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP3 > @MaxRange
	END
	ELSE IF(@KPIID = 10)
	BEGIN 
		SELECT	@CurrValue = @TotalP4, @CurrValueFormatted = @TotalP4
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP4 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP4 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP4 > @MaxRange
	END
	ELSE IF(@KPIID = 11)
	BEGIN 
		SELECT	@CurrValue = @TotalDPps, @CurrValueFormatted = @TotalDPps
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalDPps BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalDPps < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalDPps > @MaxRange
	END
	ELSE IF(@KPIID = 12)
	BEGIN 
		SELECT	@CurrValue = @TotalDPp, @CurrValueFormatted = @TotalDPp
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalDPp BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalDPp < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalDPp > @MaxRange
	END
	ELSE IF(@KPIID = 13)
	BEGIN 
		SELECT	@CurrValue = @TotalDPp1, @CurrValueFormatted = @TotalDPp1
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalDPp1 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalDPp1 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalDPp1 > @MaxRange
	END
	ELSE IF(@KPIID = 15)
	BEGIN 
		SELECT	@CurrValue = @TotalPower, @CurrValueFormatted = @TotalPower
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalPower BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalPower < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalPower > @MaxRange
	END
	ELSE IF (@KPIID = 16) 
	BEGIN
		SELECT	@CurrValue = @TotalP5, @CurrValueFormatted = @TotalP5
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP5 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP5 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP5 > @MaxRange		
	END
	ELSE IF (@KPIID = 17) 
	BEGIN
		SELECT	@CurrValue = @TotalP6, @CurrValueFormatted = @TotalP6
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP6 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP6 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP6 > @MaxRange		
	END
	ELSE IF (@KPIID = 18) 
	BEGIN
		SELECT	@CurrValue = @TotalP7, @CurrValueFormatted = @TotalP7
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP7 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP7 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP7 > @MaxRange		
	END
	ELSE IF (@KPIID = 19) 
	BEGIN
		SELECT	@CurrValue = @TotalP8, @CurrValueFormatted = @TotalP8
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP8 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP8 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP8 > @MaxRange		
	END
	ELSE IF (@KPIID = 20) 
	BEGIN
		SELECT	@CurrValue = @TotalP9, @CurrValueFormatted = @TotalP9
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP9 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP9 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP9 > @MaxRange		
	END
	ELSE IF (@KPIID = 21) 
	BEGIN
		SELECT	@CurrValue = @TotalP10, @CurrValueFormatted = @TotalP10
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP10 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP10 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP10 > @MaxRange		
	END
	ELSE IF (@KPIID = 22) 
	BEGIN
		SELECT	@CurrValue = @TotalP11, @CurrValueFormatted = @TotalP11
		SELECT	@intWarning = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP11 BETWEEN @MinRange AND @MaxRange
		SELECT	@intSafe = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP11 < @MinRange 
		SELECT	@intCritical = COUNT(BoxId) FROM @tblDetailData WHERE @TotalP11 > @MaxRange		
	END
	ELSE 
	BEGIN
		SELECT @CurrValueFormatted = '15' 
	END
	
	SELECT	@UnitName = CurrencyName FROM rvlfCurrencyType CT
	INNER	JOIN rvlfOrganization O ON CT.CurrencyTypeId = O.CurrencyTypeId
	WHERE	OrganizationId = @bigOrganizationID	and @KPIID in (9,10)

	DECLARE @KPIStatus nvarchar(10)
	IF @KPIID IN(2,15)
	BEGIN	
	SET @KPIStatus = CASE WHEN (@CurrValue < @MinRange) THEN 'safe' WHEN (@CurrValue > @MaxRange) THEN 'critical' WHEN (@CurrValue between @MinRange and @MaxRange) THEN 'warning' ELSE 'safe' END
	END
     ELSE
	   BEGIN
	  SET @KPIStatus = CASE WHEN @KPIID = 1 THEN @KPICurrSts WHEN @KPIID = 6 THEN @KPIT4Sts   WHEN @KPIID =10 THEN @KPIP4Sts
	                        WHEN @KPIID = 7 THEN @KPIP1Sts   WHEN @KPIID =11 THEN @KPIDPpsSts WHEN @KPIID =12 THEN @KPIDPpSts
						    WHEN @KPIID = 3 THEN @KPIT1Sts   WHEN @KPIID = 8 THEN @KPIP2Sts   WHEN @KPIID =13 THEN @KPIDPp1Sts
						    WHEN @KPIID = 4 THEN @KPIT2Sts   WHEN @KPIID = 9 THEN @KPIP3Sts   WHEN @KPIID =16 THEN @KPIP5Sts 
						    WHEN @KPIID = 19 THEN @KPIP8Sts   WHEN @KPIID =20 THEN @KPIP9Sts  WHEN @KPIID =21 THEN @KPIP10Sts 
							WHEN @KPIID = 22 THEN @KPIP11Sts  ELSE 'safe' END
	END
	--SET @KPIStatus = CASE WHEN (@CurrValue < @MinRange) THEN 'Safe' WHEN (@CurrValue > @MaxRange) THEN 'Critical' WHEN (@CurrValue between @MinRange and @MaxRange) THEN 'Warning' ELSE 'Safe' END
	
	DECLARE @FleetName NVARCHAR(250), @VehicleNames NVARCHAR(2000), @DurationFormat NVARCHAR(50), @RangeFormat NVARCHAR(50)
	SET @FleetName	= (SELECT FleetName FROM rvlfFleet WHERE FleetId = @FleetId)
	--SET	@Template	= REPLACE(@Template ,'$Fleet$', @FleetName)	
	SET	@VehicleNames	= CASE @BoxId	WHEN '0' THEN 'All' ELSE STUFF((SELECT ', ' + VehicleDescription FROM @BoxIds FOR XML PATH('')), 1, 1, '') END
	--SET	@Template	= REPLACE(@Template ,'$RefreshFreq$', CAST(@RefFreq AS VARCHAR(5)) + ' Sec')
	SET	@DurationFormat	= 'Last ' + CASE	WHEN @Duration = 168	THEN ' 1 Week' 
										WHEN @Duration Between 48 and 168	THEN CAST(@Duration/24 AS Varchar(20)) + ' Days' 
										ELSE CAST(@Duration AS Varchar(20)) + ' Hours' END
	
	SET	@RangeFormat	= (CASE	WHEN @KPIID IN (9,10) THEN (CONVERT(VARCHAR,CONVERT(MONEY,@MinRange),3) + ' to ' + CONVERT(VARCHAR,CONVERT(MONEY,@MaxRange),3))
															ELSE (CAST(@MinRange AS varchar(20)) + ' to ' + CAST(@MaxRange AS varchar(20))) END)
															--+ ' ' + CASE @KPIID WHEN 1 THEN 'Hours' ELSE @UnitName END

	INSERT INTO @KPIExport
	SELECT	@Sno Sno, @AssignmentID AssignmentId, @CustomTitle CustomTitle, @KPIID KPIID, @KPIName KPIName, @CurrValueFormatted CurrValueFormat, 
			@KPIStatus KPIStatus, @FleetName FleetName, @VehicleNames VehicleNames, @DurationFormat DurationFormat, @RangeFormat RangeFormat, @UnitName UnitName,
			@MinRange MinRange, @MaxRange MaxRange, @RefFreq RefFreq, BoxId, VehicleDescription,'' AS LicensePlate, '' AS VIN, Value, Status
	FROM	@tblVehicleKPIData

	RETURN
END			


GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_KPIDbd_SplitforKPI]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 25-11-2015
-- Description:	Splits and Returns Integer coloumn values from a string.
-- =============================================
CREATE FUNCTION [dbo].[rvlf_fn_KPIDbd_SplitforKPI] 
(
	@text VARCHAR(8000), 
	@delimiter VARCHAR(20) = ' '
)

	RETURNS @Strings TABLE (SNO INT IDENTITY PRIMARY KEY, ASSIGNMENTIDS BIGINT)

AS BEGIN
	DECLARE @index int
	SET @index = -1

	WHILE (LEN(@text) > 0) BEGIN
		-- Find the first delimiter
		SET @index = CHARINDEX(@delimiter , @text)

		-- No delimiter left?
		-- Insert the remaining @text and break the loop
		IF (@index = 0) AND (LEN(@text) > 0) BEGIN  
			INSERT INTO @Strings VALUES (@text)
			BREAK 
		END 

		-- Found a delimiter
		-- Insert left of the delimiter and truncate the @text
		IF (@index > 1) BEGIN
			INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))
			SET @text = RIGHT(@text, (LEN(@text) - @index))
		END
		-- Delimiter is 1st position = no @text to insert
		ELSE SET @text = RIGHT(@text, (LEN(@text) - @index))
	END
	RETURN
END

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_StringSplitter]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_StringSplitter](@ParamaterList VARCHAR(MAX),@Delimiter CHAR(1))
RETURNS @ReturnList TABLE(Sno int identity(1,1),FieldValue VARCHAR(MAX))
AS BEGIN

	 DECLARE @ArrayList TABLE
        (
          FieldValue VARCHAR(MAX)
        )
    DECLARE @Value VARCHAR(MAX)
    DECLARE @CurrentPosition INT
 
    SET @ParamaterList = LTRIM(RTRIM(@ParamaterList))
        + CASE WHEN RIGHT(@ParamaterList, 1) = @Delimiter THEN ''
               ELSE @Delimiter
          END
    SET @CurrentPosition = ISNULL(CHARINDEX(@Delimiter, @ParamaterList, 1), 0)  

    IF @CurrentPosition = 0
        INSERT  INTO @ArrayList ( FieldValue )
                SELECT  @ParamaterList
    ELSE
        BEGIN
            WHILE @CurrentPosition > 0
                BEGIN
                    SET @Value = LTRIM(RTRIM(LEFT(@ParamaterList,
                                                  @CurrentPosition - 1))) --make sure a value exists between the delimiters
                    IF LEN(@ParamaterList) > 0
                        AND @CurrentPosition <= LEN(@ParamaterList)
                        BEGIN
                            INSERT  INTO @ArrayList ( FieldValue )
                                    SELECT  @Value
                        END
                    SET @ParamaterList = SUBSTRING(@ParamaterList,
                                                   @CurrentPosition
                                                   + LEN(@Delimiter),
                                                   LEN(@ParamaterList))
                    SET @CurrentPosition = CHARINDEX(@Delimiter,
                                                     @ParamaterList, 1)
                END
        END
    INSERT  @ReturnList ( FieldValue )
            SELECT  FieldValue
            FROM    @ArrayList
    RETURN
END

GO
/****** Object:  UserDefinedFunction [dbo].[udf_StripHTML]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create FUNCTION [dbo].[udf_StripHTML]  
(@HTMLText NVARCHAR(MAX))  
RETURNS NVARCHAR(MAX)  
AS  
BEGIN  
DECLARE @Start INT  
DECLARE @End INT  
DECLARE @Length INT  
SET @Start = CHARINDEX('<',@HTMLText)  
SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))  
SET @Length = (@End - @Start) + 1  
WHILE @Start > 0  
AND @End > 0  
AND @Length > 0  
BEGIN  
SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')  
SET @Start = CHARINDEX('<',@HTMLText)  
SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))  
SET @Length = (@End - @Start) + 1  
END  
RETURN LTRIM(RTRIM(@HTMLText))  
END  

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetDistanceBasedOrg]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[rvlf_fn_GetDistanceBasedOrg]
(
	@OrganizationId bigint,
	@Distance bigint
)
RETURNS TABLE
AS
/******************************************************************************/
--	Name		:	[rvlf_fn_GetDistanceBasedOrg]
--	Description	:	Getting Distance
--	Author		:	Sakthi Gopinath S
--	History		:	Initial Version
/******************************************************************************/
RETURN
SELECT OrgDistIncPercentValue,
CASE WHEN ISNULL(OrgDistIncPercentValue,1.0) >= 1 THEN CAST(@Distance as varchar) ELSE CAST((@Distance*OrgDistIncPercentValue)+@Distance as varchar) END AS Distance
FROM rvlfOrganization WHERE OrganizationId=@OrganizationId

GO
/****** Object:  UserDefinedFunction [dbo].[rvlf_fn_GetUserPreferences]    Script Date: 02/01/2022 04:06:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREate FUNCTION [dbo].[rvlf_fn_GetUserPreferences](@bigQueryingUser int)
RETURNS table
/******************************************************************************/
--	Name		:	[rvlf_fn_ConvertDateFormat]
--	Description	:	Getting User preferences
--	Author		:	Ranjith. N
--	History		:	Initial Version
/******************************************************************************/
AS  
return(  
		SELECT tz.HoursToBeAdded  , tz.MinToBeAdded,up.Distance,up.DefaultDateFormat
			FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz	ON up.TimeZoneId = tz.TimeZoneId 
			AND up.UserId = @bigQueryingUser		
	 )

GO
